Agents without chatObject
chatObject covers the common case: one chat per key, history in state, the browser on
useChat. When you need something else (history in your own database, several agents behind one
chat, an agent that runs without a browser) use the two building blocks directly:
cairnMiddleware(ctx)makes each model call a durable step and streams its UI chunks.cairnTools(ctx, tools, opts?)makes each tool call a durable step, with optional approval.
Both work in any handler that has a ctx. Approval needs ctx.promise, so it needs a virtual
object or a workflow.
A background agent in a workflow
Section titled “A background agent in a workflow”No browser, no chat: a workflow runs once per ID, survives crashes and deploys, and can wait for an approval before publishing.
import { stepCountIs, streamText, wrapLanguageModel } from "ai";import { anthropic } from "@ai-sdk/anthropic";import { cairnMiddleware, cairnOnError, cairnTools, workflow } from "@cairnflow/sdk";
const research = workflow("Research", { run: async (ctx, topic: string) => { const result = streamText({ model: wrapLanguageModel({ model: anthropic("claude-sonnet-5-5"), middleware: cairnMiddleware(ctx), }), tools: cairnTools(ctx, tools, { approve: ["publish"] }), prompt: `Research ${topic} and publish a short brief.`, stopWhen: stepCountIs(10), onError: cairnOnError(ctx), }); for await (const _ of result.fullStream) { // Drain the stream; every model and tool call is journaled as it completes. } return await result.text; },});Start it with POST /invoke/Research/run/send?key=<workflow id>, and answer the approval with
POST /promises/Research/<workflow id>/<approvalId>/resolve. The approval ID is the
approvalIdOf(toolCallId) of the tool call; see Human approval.
Your own chat object
Section titled “Your own chat object”The browser transport does not require chatObject. It needs a virtual object, keyed by chat ID,
with three handlers that keep this contract:
| Handler | Type | Receives | Must |
|---|---|---|---|
send (or the name in the transport’s handler option) |
exclusive | A JSON body: chatId, trigger, and message (the new user message) or messages (with sendHistory: true); optional messageId, after, body |
Write the turn’s UI chunks to the ui stream (cairnMiddleware and cairnTools do it). While it runs, make active return its invocation ID |
active |
shared | nothing | Return the invocation ID of the running send, or null |
messages |
shared | nothing | Return the history as UIMessage[] |
Details the transport relies on:
- It sends to
POST /invoke/{service}/{handler}/send?key=<chatId>and reads the invocation ID from the answer, then readsGET /invocations/{id}/streams/ui. - It emits its own
startchunk withmessageIdset to the invocation ID, and its ownfinishchunk;startandfinishrecords on the stream are ignored. Use the invocation ID as the assistant message ID in the history you save, so the saved message matches the one the page built. transport.approve(chatId, approvalId, …)resolves the promiseapprovalIdon the object{service}/{chatId}. Tool approvals must therefore wait on the same object that received the message, which is whatcairnTools(ctx, …)insidesenddoes.
Example: also keep the transcript in your database
Section titled “Example: also keep the transcript in your database”import { convertToModelMessages, stepCountIs, streamText, wrapLanguageModel, type UIMessage } from "ai";import { anthropic } from "@ai-sdk/anthropic";import { cairnMiddleware, cairnOnError, cairnTools, service, TerminalError, type ChatRequest, type Context,} from "@cairnflow/sdk";
const support = service( "Support", { async send(ctx: Context, req: ChatRequest) { ctx.set("active", ctx.invocationId); try { const saved = (await ctx.get<UIMessage[]>("messages")) ?? []; const history = req.message === undefined ? saved : [...saved, req.message as UIMessage]; const result = streamText({ model: wrapLanguageModel({ model: anthropic("claude-sonnet-5-5"), middleware: cairnMiddleware(ctx), }), tools: cairnTools(ctx, tools, { approve: ["refund"] }), messages: await convertToModelMessages(history), stopWhen: stepCountIs(8), onError: cairnOnError(ctx), }); let final: UIMessage[] = history; for await (const _ of result.toUIMessageStream({ originalMessages: history, generateMessageId: () => ctx.invocationId, onFinish: (e) => { final = e.messages; }, })) { // The chunks already went to the `ui` stream from the middleware and tools. } ctx.set("messages", final); // A side effect, so it goes through ctx.run. await ctx.run("save-transcript", () => db.transcripts.save(ctx.key, final)); ctx.clear("active"); return { id: ctx.invocationId }; } catch (e) { // Clear only on a terminal failure. A transient error is retried from the journal, // and a state change here would make the retry's journal differ. if (e instanceof TerminalError) ctx.clear("active"); throw e; } }, async active(ctx: Context) { return (await ctx.get<string>("active")) ?? null; }, async messages(ctx: Context) { return (await ctx.get<UIMessage[]>("messages")) ?? []; }, }, { type: "VIRTUAL_OBJECT", handlerTypes: { send: "EXCLUSIVE", active: "SHARED", messages: "SHARED" }, },);In the browser: cairnChatTransport({ baseUrl: "/cairn", service: "Support" }).
What chatObject does that this example does not
Section titled “What chatObject does that this example does not”If you write your own object, decide whether you need these; chatObject has them built in.
- Regenerate. On
trigger: "regenerate-message"it cuts the saved history atmessageIdbefore the turn. - Stale history. It compares
after(the ID of the message before the new one on the page) with the saved history, and refuses the turn when the page is behind. - History during a turn. It keeps the turn’s input in state as soon as the turn starts, so
messagesincludes the user message while the answer is still being generated. - Pending approvals after a reload.
cairnToolskeeps each pending request in the object’s state under a key starting withpending-approval/until it is answered.chatObject’smessagesturns those into an assistant message with tool parts in stateapproval-requested. Without that, a page opened during a long wait shows no approval buttons. - Approval decisions in history. The history that
toUIMessageStreambuilds shows a rejected tool as an ordinary result ({ denied: true }).chatObjectmarks such partsoutput-deniedand records the decision on each approved or rejected part, so a reloaded chat matches what the live page showed.
Rules that still apply
Section titled “Rules that still apply”- Model calls go through
cairnMiddleware, side effects throughcairnToolsorctx.run. An unwrapped call runs again on every replay. - No
Date.now(),Math.random()or generated IDs outsidectx.run; usectx.invocationIdwhere you need a stable ID. - Ignore
Suspendin anyonErroryou write (cairnOnError(ctx)does); it is not an error of your code. - Do not change state in a
catchfor errors that are notTerminalError.