# Vercel AI SDK

> Durable chat agents with streamText, useChat, tools and human approval.

Source: https://cairnflow.dev/docs/agents/vercel-ai-sdk

Write the agent with `streamText` and `useChat` as usual; cairnflow makes each model call and each
tool call a durable step. If the process dies mid-run, the run continues from the unfinished step
without calling the model again for steps that already answered. A run can wait for a human
approval as long as it takes without holding a process, and its output streams to the browser:
token by token in streaming mode, a step at a time in request-response mode, the default on
Cairnflow Cloud (see [Streaming versus request-response](#streaming-versus-request-response)). A
page reload reconnects to the same run.

The adapter ships in `@cairnflow/sdk` and targets **AI SDK v7** (`ai@7`). The SDK does not depend
on `ai`: install `ai`, `@ai-sdk/react` and your provider package in your app.

## What you get

| You write | Cairnflow does |
|---|---|
| `wrapLanguageModel({ model, middleware: cairnMiddleware(ctx) })` | Each model call is a `ctx.run`: the result is journaled and replayed from the journal. A span `llm <model>` records input and output tokens |
| `cairnTools(ctx, tools)` | Each tool `execute` is a `ctx.run` with a span `tool <name>`; input, result and error reach the UI |
| `cairnTools(ctx, tools, { approve: ["refund"] })` | The tool waits on a durable promise until someone approves; if rejected, it never runs |
| `chatObject("Chat", run)` | A virtual object keyed by chat ID: history in state, one turn at a time per chat |
| `useChat({ transport: cairnChatTransport(…) })` | Messages go through cairnflow, UI chunks come back over SSE; reload resumes; `stop()` cancels |
| `onError: turn.onError` | Errors from `streamText` go to the invocation's log |

## Server

```ts title="agent.ts"

const tools = {
  lookupOrder: tool({
    description: "Look up an order",
    inputSchema: z.object({ id: z.number() }),
    execute: async ({ id }) => db.orders.get(id),
  }),
  refund: tool({
    description: "Refund an order (needs approval)",
    inputSchema: z.object({ id: z.number(), amount: z.number() }),
    execute: async ({ id, amount }) => payments.refund(id, amount),
  }),
};

const chat = chatObject("Chat", async (ctx, turn) =>
  streamText({
    model: wrapLanguageModel({
      model: anthropic("claude-sonnet-5-5"),
      middleware: cairnMiddleware(ctx),
    }),
    system: "You are the support assistant of a shop.",
    tools: cairnTools(ctx, tools, { approve: ["refund"] }),
    messages: await convertToModelMessages(turn.messages),
    stopWhen: stepCountIs(8),
    onError: turn.onError,
  }),
);

await serve({
  services: [chat],
  port: Number(process.env.PORT ?? 9080),
  hostname: "0.0.0.0", // the default, 127.0.0.1, is unreachable from outside a container
  identityKeys: ["<your identity key>"],
});
```

Then register the deployment (`POST /deployments`, see [Deployments](/docs/cloud/deployments)).

In request-response mode, a model call that takes longer than the
[turn time limit](/docs/cloud/limits#turn-time-limit) is cut and made again on the next attempt.
For long generations, declare a longer `inactivityTimeout` in `opts.options` (below) and set a
retry policy.

### What `chatObject` builds

`chatObject(name, run, opts?)` returns a virtual object with three handlers. The browser transport
talks to exactly these three.

| Handler | Type | What it does |
|---|---|---|
| `send` | exclusive | Records itself as the active turn, builds the history from state plus the new message (or cuts it at the message to regenerate), calls `run`, drains `toUIMessageStream` (the assistant message ID is the invocation ID), saves the new history, clears the active turn. Returns `{ id }` |
| `active` | shared | The invocation ID of the running `send`, or `null` |
| `messages` | shared | The saved history (`UIMessage[]`). During a turn: the history of that turn, including the message just sent, plus pending approval requests |

Because `send` is exclusive, two messages to the same chat never run at the same time; the second
waits in the object's queue. The shared handlers answer while `send` runs.

The `turn` argument of `run` carries:

- `messages` — the UI history to pass to `convertToModelMessages`;
- `onError` — pass it to `streamText({ onError })`;
- `chatId`, `trigger` (`"submit-message"` or `"regenerate-message"`), `messageId`;
- `body` — the `body` option the browser passed to `sendMessage`, if any.

`opts.options` takes the handler options shared by every cairnflow handler, such as
`retryPolicy`. When it sets no `retryPolicy.maxAttempts`, `chatObject` uses 5
(`CHAT_MAX_ATTEMPTS`). `opts.stream` renames the stream the UI chunks go to (default `ui`).

### The three rules

These apply to every cairnflow handler, and they matter more in an agent loop:

1. **Every side effect goes through `cairnTools` or `ctx.run`.** The handler body runs again on
   every replay. A tool `execute` that is not wrapped calls the outside API again each time.
2. **No `Date.now()`, `Math.random()` or `generateId()` outside `ctx.run`.**
3. **Do not catch and swallow errors around `ctx` commands.** A failed turn is still retried,
   whatever your `catch` does.

## Browser

The transport implements the AI SDK `ChatTransport` interface. `useChat` uses it for sending,
reconnecting and stopping; you call two extra methods yourself.

```tsx title="chat.tsx"

const transport = cairnChatTransport({ baseUrl: "/cairn", service: "Chat" });

function ChatPage({ chatId, initial }: { chatId: string; initial: UIMessage[] }) {
  const { messages, sendMessage, stop, status } = useChat({
    id: chatId,
    transport,
    messages: initial, // await transport.messages(chatId) when rendering the page
    resume: true, // reload mid-generation: reconnect to the running turn
  });
  const approve = (approvalId: string, approved: boolean) =>
    transport.approve(chatId, approvalId, { approved });
  // …render messages; tool parts waiting for approval have state "approval-requested"
}
```

| Option | Meaning |
|---|---|
| `baseUrl` | Where cairnflow is reached. In a browser, a same-origin proxy path (see below) |
| `service` | The virtual object, usually your `chatObject` name |
| `handler` | The handler that receives messages (default `send`) |
| `scope` | Scope of the object, if you use scopes |
| `headers` | Extra headers, for example `authorization` when running server-side |
| `stream` | The stream to read (default `ui`) |
| `sendHistory` | Send the whole history instead of only the last message (default `false`) |

| Method | Use |
|---|---|
| `transport.messages(chatId)` | The saved history, to initialise `useChat` after a page load |
| `transport.approve(chatId, approvalId, { approved, reason? })` | Answer a tool approval request — see [Human approval](/docs/agents/approvals). Throws if the request was already answered with a different decision |

By default the transport sends only the **last** message; the object keeps the history in its
state. `sendHistory: true` makes the object use the client's history instead, and adds a second
copy of it to every turn's journal.

### Stale history

With each message the transport sends the ID of the message right before it. If the page holds an
older history than the object (another tab sent a message, or the page never loaded `messages`),
`send` does not run the turn and does not change the history: the UI receives an `error` chunk and
`useChat` reports an error. Reload the history with `transport.messages(chatId)` and send again.
Initialising `useChat` with `messages: await transport.messages(chatId)` avoids it.

### Keep the API key on the server

Cairnflow does not send CORS headers, and an API key must never reach the browser: anyone holding
it can call every handler, read every chat and approve every request of the environment. Put a
proxy on your app's origin that checks your user and adds the key.

```ts title="app/cairn/[...path]/route.ts"
// Sketch of a Next.js route handler. `auth` and `allowed` are your code.
async function handler(req: Request, { params }: { params: Promise<{ path: string[] }> }) {
  const { path } = await params;
  const user = await auth(req);
  if (!(await allowed(user, req.method, path, new URL(req.url)))) {
    return new Response("forbidden", { status: 403 });
  }
  const target = `/${path.join("/")}${new URL(req.url).search}`;
  const headers: Record<string, string> = {
    "content-type": "application/json",
    authorization: `Bearer ${process.env.CAIRN_INVOKE_KEY}`,
    // Run the request at the node that leads this chat's range.
    "x-cairn-forward": "leader",
  };
  // The transport sends Idempotency-Key with each message, Last-Event-ID when it reconnects.
  for (const h of ["idempotency-key", "accept", "last-event-id"]) {
    const v = req.headers.get(h);
    if (v !== null) headers[h] = v;
  }
  return fetch(`${process.env.CAIRN_URL}${target}`, {
    method: req.method,
    headers,
    body: req.method === "GET" ? undefined : await req.text(),
  }); // the SSE body streams straight through
}
export { handler as GET, handler as POST };
```

An **Invoke only** key is enough. `allowed` should let through exactly these routes, and check
that the user may use that chat:

| Route | Chat ID is in |
|---|---|
| `POST /invoke/Chat/send/send`, `POST /invoke/Chat/active`, `POST /invoke/Chat/messages` | `?key=<chatId>` |
| `POST /promises/Chat/{chatId}/{approvalId}/resolve` | the path |
| `GET /invocations/{id}/streams/ui`, `POST /invocations/{id}/cancel` | the invocation ID: the proxy sees it in the answers of `send/send` (`{ id }`) and `active`, so it can keep an `id → chatId` map |

Do not buffer or compress `text/event-stream` responses in the proxy (with nginx:
`X-Accel-Buffering: no`).

On a server that talks to cairnflow directly, give the key to the transport instead:
`cairnChatTransport({ baseUrl, service, headers: { authorization: "Bearer …" } })`.

## Retries and errors

| What fails | What happens |
|---|---|
| A transient error in a model or tool call (provider 429 or 5xx, timeout, a tool throwing a normal `Error`) | The turn fails and cairnflow retries it under the handler's retry policy. Completed steps replay from the journal; only the failed step runs again |
| A provider error marked not retryable (`isRetryable: false`, such as 400 prompt too long or 401 bad key) | Journaled as the step's failed result. The UI receives an `error`, the turn ends, no retry |
| A tool throws `TerminalError` | Journaled, so a replay does not run the tool again. The model sees the tool error (`tool-output-error` in the UI, `errorText` in history) and carries on |

Because retries happen at the turn level, the AI SDK's own `maxRetries` has no effect on calls
that go through `cairnMiddleware`.

So that a provider that keeps refusing does not retry forever, `chatObject` stops after 5
attempts unless you set your own policy:

```ts
const chat = chatObject("Chat", run, {
  options: { retryPolicy: { maxAttempts: 3, onMaxAttempts: "PAUSE" } },
});
```

After the last attempt the invocation is paused; fix the cause, then resume it from the
[console](/docs/cloud/console). See [Errors and retries](/docs/develop/errors-retries).

### `turn.onError` and `Suspend`

`streamText` reports every error to `onError`, and its default is `console.error`. `turn.onError`
writes errors to the invocation's log instead, where the console's **Log** tab shows them.

When a turn waits (for an acknowledgement, a promise or an approval), nothing is thrown through
your code: the waiting promise stays pending until the turn ends. The SDK throws `Suspend` only for
a `ctx` command made after the turn has already suspended. That is not an error of your code, so
`turn.onError` ignores it. If you write your own `onError`, ignore it too:

```ts

const onError = ({ error }: { error: unknown }) => {
  if (error instanceof Suspend) return;
  report(error);
};
```

`cairnOnError(ctx)` is the same function `turn.onError` uses, for agents built without
`chatObject`.

## Streaming versus request-response

How your environment calls the service decides what the chat can do. See
[Deployments](/docs/cloud/deployments) for how the mode is chosen.

| | `BIDI_STREAM` | `REQUEST_RESPONSE` |
|---|---|---|
| Tokens in the browser | As they are generated | All the text of a step at once, when the step completes |
| `stop()` during a model or tool call | The call receives an `AbortSignal` and stops; the partial answer is kept | The running step finishes; cancellation takes effect from the next step |
| Reload during the first model call | Reconnects at once | `active` is visible only after the first durable step, so there is nothing to reconnect to yet |
| A long model call | The SDK keeps the connection alive while it runs | It must finish within the [turn time limit](/docs/cloud/limits#turn-time-limit), or it is cut and made again |
| Needs | HTTP/2 all the way to your service | Any HTTPS host, serverless functions included |

On Cairnflow Cloud an `https://` endpoint is registered in request-response mode unless you ask
for the declared mode (`"transport": "declared"`); streaming has not been verified on Fly.io yet.
More in [Streaming to the browser](/docs/agents/streaming).

## Size and cost

- **Each model step's journal entry** keeps every part of the model stream (text, tool calls,
  usage). The middleware drops the request body sent to the provider and the raw response body.
- **History lives in state.** Each turn reads it once and writes it back. Above 256 KiB the
  history is stored as immutable segments: the journal keeps references plus the open tail, so
  journal bytes per turn stay about the same as the conversation grows. In our tests a turn
  journals about 218 KB whether the history is 1, 3 or 6 MiB.
- **No need to trim for the payload limit.** A history larger than the
  [payload limit](/docs/cloud/limits#payload) (1 MiB during the Beta) is stored as segments
  instead of failing the turn. `transport.messages` returns the whole history in one response,
  capped at 64 MiB. Trim or summarise when the model's context window needs it, not the runtime.
- **The SDK caches segments.** A long-running `serve()` keeps the segments it has read in memory
  (`valueCacheBytes`, 64 MiB by default), so a turn downloads only segments it has not seen.
- **Each approval** adds a journal entry and a durable wait.

## Observe a chat

| To see | Ask |
|---|---|
| The running turn of a chat | `POST /invoke/Chat/active?key=<chatId>` |
| Spans and tokens of a turn | `GET /invocations/{id}/spans`, or the console's **Trace** tab |
| `streamText` errors and `ctx.log` lines | `GET /invocations/{id}/logs`, or the **Log** tab |
| Each model step, tool call and approval | `GET /invocations/{id}/journal`, or the **Journal** tab |
| Whether an approval was answered | `GET /promises/Chat/{chatId}/{approvalId}` |

## Known limitations

- **AI SDK v7 only.** Earlier major versions declare middleware and usage differently.
- **Providers.** The adapter is provider-agnostic and its tests use the AI SDK mock model. It has
  been run against a real model through `@ai-sdk/openai-compatible`; not every provider package has
  been tried yet.
- **A provider that refuses permanently with a transient status code** (for example a quota
  exhausted reported as `429`) is retried with backoff; the UI just waits. The error shows in the
  invocation's status and log. Set `retryPolicy.maxAttempts`.

## Next

- [Human approval](/docs/agents/approvals)
- [Streaming to the browser](/docs/agents/streaming)
- [Agents without chatObject](/docs/agents/custom-agents)
