Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

events.md

252 lines10.6 KB

1---
2title: Events
3id: events
4order: 9
5description: "Everything a harness agent does inside a sandbox (text, tool calls, reasoning, session ids, and file edits) streams back as AG-UI chunks plus namespaced CUSTOM events."
6---
7​
8When a harness adapter runs inside a [sandbox](./overview), everything it does is
9observable on the `chat()` stream: the same AG-UI `StreamChunk`s any `chat()` run
10produces, plus namespaced `CUSTOM` events for sandbox- and harness-specifics.
11​
12This page is about the **stream the client reads**. To run server-side callbacks
13on file changes, or to log sandbox internals, see [Observability](./observability).
14​
15## The stream
16​
17A harness run produces standard AG-UI `StreamChunk`s:
18​
19- **Text**: incremental assistant output.
20- **Tool calls**, including bridged [tools](./tools), which surface as ordinary
21 tool-call chunks the moment the in-sandbox agent invokes them.
22- **Reasoning**: the agent's thinking, where the harness exposes it.
23- **Run lifecycle**: run started, run finished, and related boundaries.
24​
25## Custom events
26​
27On top of the standard chunks, the sandbox and harness layers emit `CUSTOM`
28events (`chunk.type === 'CUSTOM'`), each with a `name` and a `value`:
29​
30| Event `name` | Emitted by | When | `value` |
31| --- | --- | --- | --- |
32| `grok-build.session-id` | Grok Build adapter | once, when the in-sandbox session is created or resumed | the resumable harness session id |
33| `claude-code.session-id` | Claude Code adapter | once, when the in-sandbox session is created or resumed | the resumable harness session id |
34| `codex.session-id` | Codex adapter | once, when the session is created or resumed | the resumable harness session id |
35| `opencode.session-id` | OpenCode adapter | once, when the session is created or resumed | the resumable harness session id |
36| `file.changed` | harness adapter (e.g. Grok Build, Claude Code) | after the run completes | `{ path: string; diff: string }`: the whole working-tree `git diff` (`path` is always `'.'`, the tree root) |
37| `sandbox.file` | the engine, automatically | per file create / change / delete while a sandbox is active | `{ type: 'create' \| 'change' \| 'delete'; path: string; timestamp: number }` |
38| `sandbox.file.diff` | the engine, opt-in via `fileEvents: { diff: true }` | per file create / change / delete, after the matching `sandbox.file` | `{ path: string; diff: string }`: a unified patch of that one file vs the session's git baseline |
39​
40The `*.session-id` event lets you resume a harness session on a follow-up run
41(pass it back via the adapter's `modelOptions.sessionId`). `sandbox.file` is
42emitted automatically whenever a sandbox is active and file watching is on, with
43no hooks required. `sandbox.file.diff` is off by default (computing a diff on
44every change has a cost); turn it on with `fileEvents: { diff: true }` on
45`defineSandbox` when the client needs to render the change itself, not just
46know it happened:
47​
48```ts
49import { defineSandbox } from "@tanstack/ai-sandbox";
50import { dockerSandbox } from "@tanstack/ai-sandbox-docker";
51​
52const repoSandbox = defineSandbox({
53 id: "repo-agent",
54 provider: dockerSandbox({ image: "node:22" }),
55 fileEvents: { diff: true }, // also emit sandbox.file.diff per change
56});
57```
58​
59See [Observability](./observability) to also handle file changes server-side
60via hooks (which get the same diff, plus `before()`/`after()`), or to turn
61the watcher off entirely.
62​
63> **Bridged tools emit their own events too.** A `chat()` tool that runs through
64> the [tool bridge](./tools) can stream `CUSTOM` events back mid-execution. Code
65> mode, for example, emits `code_mode:execution_started` and `code_mode:console`
66> (plus `code_mode:external_call` / `…_result` / `…_error`) so you can show its
67> progress live. Read them with the same pattern below.
68​
69## Reading CUSTOM events on the client
70​
71Every `CUSTOM` event TanStack AI itself emits, `sandbox.file`,
72`sandbox.file.diff`, `file.changed`, the `*.session-id` events, and more, has
73a fixed `name` and a concrete `value` shape, unified as `KnownCustomEvent`.
74`chat()`'s return type narrows accordingly: check `chunk.type === 'CUSTOM'`
75and then compare `chunk.name` to a literal string. No helper, no cast, the
76plain `if` types `chunk.value` for you:
77​
78```ts
79import { stream } from "./my-run";
80​
81for await (const chunk of stream) {
82 if (chunk.type === "CUSTOM" && chunk.name === "sandbox.file") {
83 console.log(chunk.value.type, chunk.value.path); // typed, no cast
84 } else if (chunk.type === "CUSTOM" && chunk.name === "sandbox.file.diff") {
85 console.log(chunk.value.path, chunk.value.diff); // typed, no cast
86 } else if (chunk.type === "CUSTOM" && chunk.name === "file.changed") {
87 console.log(chunk.value.diff); // typed, no cast
88 }
90```
91​
92### Session-id events aren't one literal name
93​
94`*.session-id` is emitted per-adapter (`claude-code.session-id`,
95`codex.session-id`, `grok-build.session-id`, `opencode.session-id`), so its
96type is the template-literal name `` `${string}.session-id` ``, not a single
97string. If you know which adapter you're running, compare the exact literal
98it narrows `chunk.value` the same as any other event:
99​
100```ts
101import { resumeSession } from "./session";
102import { stream } from "./my-run";
103​
104for await (const chunk of stream) {
105 if (chunk.type === "CUSTOM" && chunk.name === "claude-code.session-id") {
106 resumeSession(chunk.value.sessionId); // typed as string, no cast
107 }
109```
110​
111> **`chunk.name.endsWith('.session-id')` does *not* narrow.** It's a plain
112> boolean expression, not something TypeScript can attach to a type, so
113> `chunk.value` stays whatever it was before the check (effectively
114> `unknown`), even though the check happens to be correct at runtime. If you
115> need to handle *any* adapter's session id without listing every adapter's
116> literal name, write a small type predicate instead:
118> ```ts
119> import type { KnownCustomEvent, SessionIdEvent } from "@tanstack/ai";
120> import { resumeSession } from "./session";
121> import { stream } from "./my-run";
123> function isSessionIdEvent(
124> chunk: KnownCustomEvent,
125> ): chunk is SessionIdEvent {
126> return chunk.name.endsWith(".session-id");
127> }
129> for await (const chunk of stream) {
130> if (chunk.type === "CUSTOM" && isSessionIdEvent(chunk)) {
131> resumeSession(chunk.value.sessionId); // typed as string, no cast
132> }
133> }
134> ```
136> This predicate is something you write yourself when you need it, TanStack
137> AI doesn't ship a guard API. Plain literal-`name` narrowing (as above) is
138> the primary, no-helper pattern; reach for a predicate only for this
139> "any adapter" case.
140​
141See [Custom Events Reference](../protocol/custom-events) for the full typed
142event taxonomy, the `ChatStream` type this narrowing relies on, and the
143tradeoff for your own `emitCustomEvent` calls.
144​
145## What gets stored
146​
147Your user reopens a thread the next morning and wants what they saw before: the
148commands the agent ran and what came back. The stream on this page is live output.
149The transcript your app keeps is a different thing.
150​
151Wire [chat persistence](../persistence/chat-persistence) next to `withSandbox` and a
152finished run leaves this in the message store:
153​
154| The harness produced | In the store |
155| --- | --- |
156| Text | Yes, as the assistant message. |
157| Tool calls (name and arguments) | Yes, as `toolCalls` on an assistant message. |
158| Tool results | Yes, as a `role: 'tool'` message. |
159| Reasoning | No. |
160| `CUSTOM` events (file events, code-mode console, session ids) | No. |
161​
162So reopening the thread rebuilds the tool cards with their results, on any device.
163​
164`CUSTOM` events are not messages, so anything your UI builds from them (a file list,
165a console panel) lasts only for that visit. Keep that state yourself if you want it
166back.
167​
168Two limits to know about:
169​
170- All of the harness's text arrives as one final assistant message. A restored thread
171 reads as the tool cards in the order they ran, then the full text.
172- A stored result is the string the harness reported. Reopening a thread never re-runs
173 a tool.
174​
175### Trim what you keep
176​
177To decide whether to store a transcript at all, see
178[Build a Sandbox Adapter](../persistence/build-a-sandbox-adapter). This section is the finer knob:
179you are storing one, and you want it smaller.
180​
181One run's tool output can be hundreds of kilobytes, and results reach your store
182whole. Your `MessageStore` decides what to keep. `isSandboxToolCall` tells you which
183calls the harness ran inside the sandbox, so you never have to know how they are
184marked. It reads a rendered `tool-call` part too, which is handy for filtering a
185client-side view.
186​
187Capping each result keeps the cards and bounds the size:
188​
189```ts
190import type { ModelMessage } from "@tanstack/ai";
191import type { MessageStore } from "@tanstack/ai-persistence";
192import { db } from "./db";
193​
194const MAX_RESULT = 8_000;
195​
196const store: MessageStore = {
197 async saveThread(threadId, messages) {
198 const capped = messages.map((message: ModelMessage) =>
199 message.role === "tool" && typeof message.content === "string"
200 ? { ...message, content: message.content.slice(0, MAX_RESULT) }
201 : message,
202 );
203 await db.saveThread(threadId, capped);
204 },
205 loadThread: (threadId) => db.loadThread(threadId),
206};
207```
208​
209To drop the history instead, remove each result with its call. A result whose call is
210missing is worse than either, because providers reject it.
211​
212```ts
213import { isSandboxToolCall } from "@tanstack/ai-sandbox";
214import type { ModelMessage } from "@tanstack/ai";
215import type { MessageStore } from "@tanstack/ai-persistence";
216import { db } from "./db";
217​
218const store: MessageStore = {
219 async saveThread(threadId, messages) {
220 const dropped = new Set<string>();
221 const kept: Array<ModelMessage> = [];
222 for (const message of messages) {
223 const calls = message.toolCalls;
224 if (calls && calls.length > 0 && calls.every(isSandboxToolCall)) {
225 for (const call of calls) dropped.add(call.id);
226 continue;
227 }
228 if (
229 message.role === "tool" &&
230 message.toolCallId !== undefined &&
231 dropped.has(message.toolCallId)
232 ) {
233 continue;
234 }
235 kept.push(message);
236 }
237 await db.saveThread(threadId, kept);
238 },
239 loadThread: (threadId) => db.loadThread(threadId),
240};
241```
242​
243Dropping them is safe. They are display history, and nothing resumes from them: the
244next turn's request to the model never carries them either, because they name tools
245the provider was never given.
246​
247## Related
248​
249- [Observability](./observability), server-side file-event hooks (with `before()`/`after()`/`diff()`), debug logging, and the low-level watcher.
250- [Custom Events Reference](../protocol/custom-events), the full `KnownCustomEvent` taxonomy and the `ChatStream` type.
251- [Tools](./tools), bridged host tools that surface as tool-call (and CUSTOM) chunks.
252- [Quick Start](./quick-start), read the `file.changed` diff end to end.