Migrating from the Vercel AI SDK
Move from `streamText` + `useChat` to a `SessionRuntime` — what maps cleanly, what doesn't, and how to keep the AI SDK as your provider.
The Vercel AI SDK is the most common starting point for chat
applications. @pleach/core doesn't replace it — the AI SDK
remains an excellent provider integration, and AiSdkProvider
keeps it in the stack. What changes is what wraps the provider:
a typed runtime with sessions, per-call audit, family lock,
checkpointing, and replay.
This guide walks the migration. You can stop at any step — the runtime works with a single provider, no plugins, no audit adapter, no checkpointer. Add capabilities as you need them.
Two shapes: recognized provider vs bespoke infra
This guide keeps a recognized provider — core ships
AiSdkProvider, so your provider drops straight in. If your
provider or store is bespoke (an in-house gateway, a custom
Postgres schema), the same graft still works, but you implement
the adapter interface yourself. See
Adoption paths → Pick core-brownfield when
and the bundled examples/brownfield-adapter/.
When to migrate, when not to
Stay on the AI SDK if
- The app is a single-shot chat with tools and no audit needs.
- Streaming,
useChat, and provider switching cover your shape. - You don't need per-tenant cost allocation or per-call audit.
Migrate to @pleach/core when one of these lands on your roadmap:
- A regulator, customer, or finance team will eventually ask "show me which tools this session invoked, which subagents it spawned, and what each cost — attributed to the turn the user typed." The lattice stages are a structural invariant; the ledger is where the variable surface lives.
- Multi-tenant cost allocation requires
(tenantId, turnId, toolName, subagentDepth, model, tokens)joined cleanly. - You need to replay a recorded turn from its record, without calling the model, for eval or regression testing.
- You need to swap providers mid-product without breaking tool-call dialect or refusal handling.
The migration cost is real but bounded. The runtime contract is the new mental model; everything else is configuration.
Keep your provider; add a runtime
Today (AI SDK alone):
import { streamText } from "ai";
import { anthropic } from "@ai-sdk/anthropic";
const result = await streamText({
model: anthropic("claude-sonnet-4-5"),
messages,
tools,
});
for await (const part of result.fullStream) {
// ...
}After migration:
import { SessionRuntime, AiSdkProvider, definePleachPlugin, fromAiSdkTools } from "@pleach/core";
import { anthropic } from "@ai-sdk/anthropic";
const runtime = new SessionRuntime({
provider: new AiSdkProvider({
model: anthropic("claude-sonnet-4-5"),
maxSteps: 5,
}),
// Register your existing AI SDK tool set; the record keys stay the tool names.
plugins: [definePleachPlugin("my-app", { tools: fromAiSdkTools(tools) })],
userId,
});
const session = await runtime.createSession({
tools: { enabled: Object.keys(tools) },
});
for await (const event of runtime.executeMessage(session.id, prompt)) {
// ...
}What changed:
- A
SessionRuntimeconstructed once at startup (or per request, depending on your architecture). - A
Sessioninstead of a raw message list — the runtime owns the conversation state. - An
AsyncGenerator<StreamEvent>instead of afullStream— the events are typed and richer (tool lifecycle, sync, interrupts, subagents, checkpoints).
What stayed the same: the provider. AiSdkProvider wraps
streamText exactly; your model factory, tool defs, and stream
mechanics are unchanged.
Step-cap and tool-control mapping
The three per-call control knobs map directly:
| AI SDK | Pleach | Where it lives |
|---|---|---|
maxSteps (v4) / stopWhen: stepCountIs(n) (v5+) | maxSteps | AiSdkProvider options — passed to streamText as stopWhen: stepCountIs(n) |
| — | maxGraphSteps | SessionRuntimeConfig — caps the runtime's own graph steps per turn |
toolChoice | toolChoice | executeMessage options — per turn |
experimental_activeTools (v4) / activeTools (v5+) | activeTools | executeMessage options — per turn |
toolChoice and activeTools take effect on the default turn
loop. A custom graph client that doesn't implement
setTurnDispatchDirectives logs a warning and ignores them for that
turn.
const runtime = new SessionRuntime({
provider: new AiSdkProvider({ model, maxSteps: 5 }),
userId,
});
for await (const event of runtime.executeMessage(session.id, prompt, {
toolChoice: "required",
activeTools: ["search_corpus"],
})) {
// ...
}Two semantic differences to know. maxGraphSteps counts graph
supersteps, not LLM calls, and it is lowering-only — a value above
the runtime's hard safety bound is clamped down with a warning.
toolChoice and activeTools are per-turn: a turn that omits them
resets to the full tool set and the provider default. See
SessionRuntime → Per-turn tool directives.
Convert your tools
AI SDK tools translate to defineTool 1:1:
// Before
import { tool } from "ai";
import { z } from "zod";
const searchCorpus = tool({
description: "Search the corpus",
inputSchema: z.object({ query: z.string() }),
execute: async ({ query }) => fetchCorpus(query),
});
// After
import { defineTool } from "@pleach/core";
const searchCorpus = defineTool({
name: "search_corpus",
description: "Search the corpus",
inputSchema: z.object({ query: z.string() }),
async execute(input, ctx) {
return fetchCorpus(input.query, { signal: ctx.signal });
},
});Two real differences:
nameis explicit — the AI SDK derives it from the object key; the runtime requires it on the definition.- The second arg is
ToolContextwith anAbortSignal. Thread it through every fetch or spawn — tools that ignore the signal keep burning resources after the user hits stop.
Register tools through a plugin or the legacy
setOrchestratorRegistry shim. See Tools for the
options.
Convert the stream consumer
The AI SDK's fullStream carries typed chunks
(text-delta / tool-call / tool-result / finish). The
runtime's StreamEvent is a richer union with the same shapes
plus lifecycle, sync, and interrupt events.
// Before
for await (const part of result.fullStream) {
switch (part.type) {
case "text-delta": onTextDelta(part.textDelta); break;
case "tool-call": onToolCall(part); break;
case "tool-result": onToolResult(part); break;
case "finish": onFinish(part); break;
}
}
// After
for await (const event of runtime.executeMessage(session.id, prompt)) {
switch (event.type) {
case "message.delta": onTextDelta(event.delta); break;
case "tool.started": onToolCall(event.toolCall); break;
case "tool.completed": onToolResult(event.toolCall, event.result); break;
case "message.complete": onFinish(event.message); break;
}
}The mapping is mostly mechanical. See Stream events for the full catalog — there's more you can react to, but porting only the four above gets your existing UI working.
Convert the React surface
useChat and useHarness cover overlapping ground; the runtime's
hook is shaped for the richer event stream.
// Before
import { useChat } from "ai/react";
function Chat() {
const { messages, input, handleInputChange, handleSubmit, isLoading } = useChat({
api: "/api/chat",
});
return <>...</>;
}
// After
import { HarnessProvider, useHarness } from "@pleach/core/react";
function App() {
// HarnessProvider builds its own SessionRuntime; it takes userId and
// an optional storage adapter, not a runtime.
return (
<HarnessProvider userId={userId}>
<Chat />
</HarnessProvider>
);
}
function Chat() {
const { messages, sendMessage, isLoading } = useHarness();
return <>...</>;
}Two structural differences:
HarnessProviderowns the runtime — single source of truth across components.useChatis per-component.sendMessage(text)instead ofhandleSubmit(e)— the runtime handles event wiring; the form submit is yours to compose.
The messages array carries the same shape (role, content,
id), so existing message-rendering components transfer.
Pick storage and a checkpointer
The AI SDK doesn't persist sessions. The runtime expects you to pick a storage adapter even if it's in-memory:
import { SessionRuntime } from "@pleach/core";
import { MemoryAdapter } from "@pleach/core/sessions";
import { MemorySaver } from "@pleach/core/checkpointing";
const runtime = new SessionRuntime({
storage: new MemoryAdapter(),
checkpointer: new MemorySaver(),
provider: new AiSdkProvider({ model }),
userId: "user_123",
});For production, swap MemoryAdapter/MemorySaver for
SupabaseAdapter/SupabaseSaver and apply the schema bundle —
see Storage and CLI.
Add the API route (optional)
If you were using the AI SDK's pattern with a Next.js API route, swap the handler:
// Before (Next.js app router)
import { streamText } from "ai";
export async function POST(req: Request) {
const { messages } = await req.json();
const result = streamText({ model, messages, tools });
return result.toDataStreamResponse();
}
// After
export async function POST(req: Request) {
const { sessionId, content } = await req.json();
const stream = new ReadableStream({
async start(controller) {
for await (const event of runtime.executeMessage(sessionId, content)) {
controller.enqueue(`data: ${JSON.stringify(event)}\n\n`);
}
controller.close();
},
});
return new Response(stream, {
headers: { "Content-Type": "text/event-stream" },
});
}Or use the shipped createPleachRoute from @pleach/core/quickstart
for a one-line POST handler — see API routes for
the full wire contract.
Already on the AI SDK?
The AI SDK ai@6.0.146 already does some of this natively. Each
other row alone is a side module beside it. Pleach's column is what
the runtime path does today; the four interactions that get hard together are on
the landscape page.
| Capability | Native on the AI SDK (ai@6.0.146) | Easy beside it | Hard in combination | Pleach today |
|---|---|---|---|---|
| Row per attempt | — | — | an aborted streamText gives no usage and no onFinish | On the built-in providers, every request the runtime sends writes its own row, retries included, for sub-agents too; a provider that doesn't declare per-attempt rows keeps one row per call. The provider SDK's own retries are turned off so none hide inside it. An attempt cut off by an abort still closes its row. |
| Chained row | — | — | children finish before parents | Call rows are hash-chained by default, in Postgres and in the quickstart store. The verifier names the first row that doesn't match. It catches an edit, a backfill or a deletion; it doesn't stop one, and an unkeyed chain can be rewritten end to end by anyone with write access. |
| Typed keys + sub-agent rollup | — | a side module beside the call | — | Root turn and subagent depth on every row |
| Cost per turn and tenant | — | — | failed attempts carry no usage | modelCall.costUsd on each per-call row (costOmitted says why when it is absent). Calls that write the prompt cache are priced only when the call reports how many writes were 5-minute and how many 1-hour and there is a rate for each, and marked unpriced otherwise. |
| Tenant on row, span and HTTP | ≈native (headers) | — | — | Tenant on every row and span. Providers stamp it on outbound HTTP as x-tenant-id by default; tenantHeader: false turns that off and tenantHeader: "<name>" renames it. |
| Scrub before write | — | — | spans carry the raw prompt | A default PII redactor runs on the call ledger before the row is hashed. Opt out explicitly with piiRedactorNoop(). Event-log scrubbers run on the Postgres and SQLite writers by default; opt out of SQLite scrubbing with createSqliteDurableStore(path, { redaction: "off" }) (the sidecar uses PLEACH_REDACT=0). |
| Replay without re-firing | — | — | not provided | Replay re-serves a turn's recorded responses instead of calling the model. replayRecordedTurn (from @pleach/replay/recorded) replays a recorded turn against its original record and names the first request that drifted; steps the runtime doesn't fingerprint yet (decision, synthesize) are marked blind, so a turn on a stock runtime is never reported matched. |
| Fork and rewind | — | — | no time travel | A fork's first row commits to the parent row it branched from; verifyBranchPoint checks it. A rollback leaves a tombstone row. |
| Erasure with a chain | — | — | not provided | Crypto-shred erasure keeps every event-log row hash verifying. Call-ledger rows are sealed per subject by default wherever a key store is configured; shredding the subject's key keeps every call-row hash verifying and makes the sealed fields unreadable. User ids and the row's wrapper fields aren't erased, and the quickstart's default store has no key store, so its rows stay plaintext unless you pass subjectKeys. |
| Human-in-the-loop | tool approvals | — | — | interrupt.requested / interrupt.resolved |
| Checkpoints and crash resume | — | — | not provided | runtime.checkpoints save, resume and rollback |
| Family lock | — | a side module beside the call | — | A session stays in one model family. When a model fails, the cascade retries within that family and never silently widens, including for models outside the routing matrix. The old cross-family fallback is opt-in. |
| OTel threading | native | — | — | parent-threaded spans |
What gets hard on the AI SDK together
- An abort drops the accounting. An aborted
streamTextgives no usage and noonFinish, so a cut-off attempt leaves no row unless something outside the stream closes it. - An in-band error chunk flushes as OK. A provider error that arrives as a stream chunk ends the response normally, so a logger keyed on the HTTP status records a failure as a success.
- Parents commit after children. Parallel tools and sub-agents finish before the call that spawned them, so a chain written in completion order doesn't match the call tree.
What you keep paying
Costs that don't go away
- The runtime contract is a model you have to learn. The
SessionRuntimeConfigsurface is small but real. - Storage and checkpointing add a database dependency. Mock mode works for dev; production needs schema migrations.
- Plugin authoring is a new abstraction. You don't need it on day one — the substrate stands on its own.
Common migration pitfalls
| Symptom | Likely cause |
|---|---|
| Tools fire but don't appear in the stream | Tool registered but not added to createSession({ tools: { enabled: [...] } }) |
executeMessage throws on first call | Missing setHarnessModuleLoader if your host has legacy orchestrator integration |
[UXParity:metaToolNames-config-missing] warning | Pass metaToolNames on the runtime config — see SessionRuntime |
| Stream silently disconnects in production | SSE response wasn't flushed; check Cache-Control: no-cache and disable response buffering |
| React hooks return stale data | HarnessProvider re-mounted because runtime was re-created on every render — wrap in useMemo |
See Troubleshooting for the longer list.