# Migrating from the Vercel AI SDK (/docs/migrating-from-ai-sdk)



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.

<Callout title="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](/docs/adoption-paths)
  and the bundled `examples/brownfield-adapter/`.
</Callout>

## When to migrate, when not to [#when-to-migrate-when-not-to]

<Callout type="info" title="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.
</Callout>

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.

<Steps>
  <Step>
    ## Keep your provider; add a runtime [#keep-your-provider-add-a-runtime]

    Today (AI SDK alone):

    ```typescript
    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:

    ```typescript
    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 `SessionRuntime` constructed once at startup (or per request,
      depending on your architecture).
    * A `Session` instead of a raw message list — the runtime owns the
      conversation state.
    * An `AsyncGenerator<StreamEvent>` instead of a `fullStream` — 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 [#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.

    ```typescript
    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](/docs/session-runtime#per-turn-tool-directives).
  </Step>

  <Step>
    ## Convert your tools [#convert-your-tools]

    AI SDK tools translate to `defineTool` 1:1:

    ```typescript
    // 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:

    1. `name` is explicit — the AI SDK derives it from the object key;
       the runtime requires it on the definition.
    2. The second arg is `ToolContext` with an `AbortSignal`. 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](/docs/tools) for the
    options.
  </Step>

  <Step>
    ## Convert the stream consumer [#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.

    ```typescript
    // 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](/docs/stream-events)
    for the full catalog — there's more you can react to, but
    porting only the four above gets your existing UI working.
  </Step>

  <Step>
    ## Convert the React surface [#convert-the-react-surface]

    `useChat` and `useHarness` cover overlapping ground; the runtime's
    hook is shaped for the richer event stream.

    ```tsx
    // 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:

    1. `HarnessProvider` owns the runtime — single source of truth
       across components. `useChat` is per-component.
    2. `sendMessage(text)` instead of `handleSubmit(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.
  </Step>

  <Step>
    ## Pick storage and a checkpointer [#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:

    ```typescript
    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](/docs/storage) and [CLI](/docs/cli).
  </Step>

  <Step>
    ## Add the API route (optional) [#add-the-api-route-optional]

    If you were using the AI SDK's pattern with a Next.js API route,
    swap the handler:

    ```typescript
    // 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](/docs/api-routes) for
    the full wire contract.
  </Step>
</Steps>

<a id="what-you-gain-after-the-migration" />

## Already on the AI SDK? [#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](/docs/landscape#if-you-already-run-a-runtime).

| 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 [#what-gets-hard-on-the-ai-sdk-together]

* **An abort drops the accounting.** An aborted `streamText` gives
  no usage and no `onFinish`, 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 [#what-you-keep-paying]

<Callout type="info" title="Costs that don't go away">
  * The runtime contract is a model you have to learn. The
    `SessionRuntimeConfig` surface 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.
</Callout>

## Common migration pitfalls [#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](/docs/session-runtime)          |
| 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](/docs/troubleshooting) for the longer list.

## Where to go next [#where-to-go-next]

<Cards>
  <Card title="Providers" href="/docs/providers" description="`AiSdkProvider` config — keeping your AI SDK setup intact." />

  <Card title="Tools" href="/docs/tools" description="Converting AI SDK tools to `defineTool`." />

  <Card title="Stream events" href="/docs/stream-events" description="The richer event union your stream consumer now reads." />

  <Card title="Recipes" href="/docs/recipes" description="Multi-tenant, BYO storage, and other end-to-end patterns." />
</Cards>
