# Agents without chatObject

> Build your own agent handler with cairnMiddleware and cairnTools, and the contract the chat transport expects.

Source: https://cairnflow.dev/docs/agents/custom-agents

`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

No browser, no chat: a workflow runs once per ID, survives crashes and deploys, and can wait for an
approval before publishing.

```ts title="research.ts"

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](/docs/agents/approvals).

## 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 reads `GET /invocations/{id}/streams/ui`.
- It emits its own `start` chunk with `messageId` set to the invocation ID, and its own `finish`
  chunk; `start` and `finish` records 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 promise `approvalId` on the object
  `{service}/{chatId}`. Tool approvals must therefore wait on the same object that received the
  message, which is what `cairnTools(ctx, …)` inside `send` does.

### Example: also keep the transcript in your database

```ts title="support.ts"
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

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 at `messageId`
  before 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
  `messages` includes the user message while the answer is still being generated.
- **Pending approvals after a reload.** `cairnTools` keeps each pending request in the object's
  state under a key starting with `pending-approval/` until it is answered. `chatObject`'s
  `messages` turns those into an assistant message with tool parts in state `approval-requested`.
  Without that, a page opened during a long wait shows no approval buttons.
- **Approval decisions in history.** The history that `toUIMessageStream` builds shows a rejected
  tool as an ordinary result (`{ denied: true }`). `chatObject` marks such parts `output-denied`
  and records the decision on each approved or rejected part, so a reloaded chat matches what the
  live page showed.

## Rules that still apply

- Model calls go through `cairnMiddleware`, side effects through `cairnTools` or `ctx.run`. An
  unwrapped call runs again on every replay.
- No `Date.now()`, `Math.random()` or generated IDs outside `ctx.run`; use `ctx.invocationId`
  where you need a stable ID.
- Ignore `Suspend` in any `onError` you write (`cairnOnError(ctx)` does); it is not an error of
  your code.
- Do not change state in a `catch` for errors that are not `TerminalError`.

## Next

- [Vercel AI SDK](/docs/agents/vercel-ai-sdk)
- [Durable steps](/docs/develop/durable-steps)
- [Services, objects and workflows](/docs/develop/services)
