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

events.md

233 lines10.2 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 named CUSTOM events. Read them, show them, and choose what to store."
6---
7​
8Sandbox events stream the agent text, tool calls, and file edits to the UI while the run is in progress.
9​
10Everything a harness does in a sandbox comes back on the `chat()` stream. You get the normal AG-UI chunks, plus `CUSTOM` events with a `name` for sandbox-specific things such as file edits.
11​
12## Read the events
13​
14This sample prints the agent's text and every file it touches:
15​
16```ts
17import { chat } from '@tanstack/ai'
18import { GROK_CLI_INSTALL_COMMAND, grokBuildText } from '@tanstack/ai-grok-build'
19import {
20 createSecrets,
21 defineSandbox,
22 defineWorkspace,
23 githubRepo,
24 withSandbox,
25} from '@tanstack/ai-sandbox'
26import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
27​
28const repoSandbox = defineSandbox({
29 id: 'repo-agent',
30 provider: dockerSandbox({ image: 'node:22' }),
31 workspace: defineWorkspace({
32 source: githubRepo({ repo: 'owner/app' }),
33 setup: [GROK_CLI_INSTALL_COMMAND],
34 secrets: createSecrets({ XAI_API_KEY: process.env.XAI_API_KEY ?? '' }),
35 }),
36 fileEvents: { diff: true }, // also send sandbox.file.diff for each change
37})
38​
39const stream = chat({
40 threadId: 'thread-1',
41 adapter: grokBuildText('grok-build'),
42 messages: [{ role: 'user', content: 'Add a README section on testing.' }],
43 middleware: [withSandbox(repoSandbox)],
44})
45​
46for await (const chunk of stream) {
47 if (chunk.type === 'TEXT_MESSAGE_CONTENT') {
48 process.stdout.write(chunk.delta)
49 } else if (chunk.type === 'CUSTOM' && chunk.name === 'sandbox.file') {
50 console.log(chunk.value.type, chunk.value.path)
51 } else if (chunk.type === 'CUSTOM' && chunk.name === 'sandbox.file.diff') {
52 console.log(chunk.value.path, chunk.value.diff)
53 } else if (chunk.type === 'CUSTOM' && chunk.name === 'file.changed') {
54 console.log(chunk.value.diff)
55 }
57```
58​
59You see `create`, `change`, and `delete` lines while the agent works. When the run ends, you see the full `git diff`.
60​
61Compare `chunk.name` to a literal string, and TypeScript types `chunk.value` for you. You need no helper and no cast.
62​
63## The stream
64​
65A harness run sends the standard AG-UI `StreamChunk`s:
66​
67- **Text**: the assistant output, piece by piece.
68- **Tool calls**, also bridged [tools](./tools). They show up as normal tool-call chunks when the agent calls them.
69- **Reasoning**: the agent's thinking, when the harness exposes it.
70- **Run lifecycle**: run started, run finished, and other boundaries.
71​
72This page is about the stream that the client reads. To run server-side callbacks on file changes, or to log sandbox internals, see [Observability](./observability).
73​
74## Custom events
75​
76On top of the standard chunks, the sandbox and harness layers send `CUSTOM` events (`chunk.type === 'CUSTOM'`). Each one has a `name` and a `value`:
77​
78| Event `name` | Sent by | When | `value` |
79| --- | --- | --- | --- |
80| `grok-build.session-id` | Grok Build adapter | Once, when the session is created or resumed | `{ sessionId: string }` |
81| `claude-code.session-id` | Claude Code adapter | Once, when the session is created or resumed | `{ sessionId: string }` |
82| `codex.session-id` | Codex adapter | Once, when the session is created or resumed | `{ sessionId: string }` |
83| `opencode.session-id` | OpenCode adapter | Once, when the session is created or resumed | `{ sessionId: string }` |
84| `file.changed` | Harness adapter (for example Grok Build, Claude Code) | After the run completes | `{ path: string; diff: string }`: the whole working-tree `git diff`. `path` is always `'.'`, the tree root. |
85| `sandbox.file` | The engine, automatically | For each file create, change, or delete while a sandbox is active | `{ type: 'create' \| 'change' \| 'delete'; path: string; timestamp: number }` |
86| `sandbox.file.diff` | The engine, with `fileEvents: { diff: true }` | For each file create, change, or delete, after the matching `sandbox.file` | `{ path: string; diff: string }`: a unified patch of that one file against the git baseline of the session |
87​
88- **`*.session-id`**: pass the id back with the adapter's `modelOptions.sessionId` to resume the harness session on a later run.
89- **`sandbox.file`**: sent whenever a sandbox is active and file watching is on. You need no hooks.
90- **`sandbox.file.diff`**: off by default, because a diff on every change has a cost. Turn it on with `fileEvents: { diff: true }` on `defineSandbox` when the client must show the change, not only know that it happened.
91​
92To handle file changes on the server with hooks, or to turn the watcher off, see [Observability](./observability). Hooks get the same diff, plus `before()` and `after()`.
93​
94For the full typed event list and the `ChatStream` type, see [Custom Events Reference](../protocol/custom-events).
95​
96## What gets stored
97​
98Your user opens a thread the next morning and wants to see the commands the agent ran and their results. The stream on this page is live output. The transcript your app keeps is a different thing.
99​
100Add [chat persistence](../persistence/chat-persistence) next to `withSandbox`. A finished run then leaves this in the message store:
101​
102| The harness produced | In the store |
103| --- | --- |
104| Text | Yes, as the assistant message. |
105| Tool calls (name and arguments) | Yes, as `toolCalls` on an assistant message. |
106| Tool results | Yes, as a `role: 'tool'` message. |
107| Reasoning | No. |
108| `CUSTOM` events (file events, code-mode console, session ids) | No. |
109​
110So when the user opens the thread again, on any device, the tool cards come back with their results.
111​
112`CUSTOM` events are not messages. Anything your UI builds from them (a file list, a console panel) lasts only for that visit. If you want it back later, store that state yourself.
113​
114Two limits:
115​
116- All of the harness text arrives as one final assistant message. A restored thread shows the tool cards in the order they ran, then the full text.
117- A stored result is the string that the harness reported. Opening a thread again never runs a tool again.
118​
119## Advanced
120​
121### Bridged tools send their own events
122​
123A `chat()` tool that runs through the [tool bridge](./tools) can stream `CUSTOM` events during its run. Code mode, for example, sends:
124​
125- `code_mode:execution_started`
126- `code_mode:console`
127- `code_mode:external_call`, `code_mode:external_result`, and `code_mode:external_error`
128​
129Read them with the same literal-name pattern to show progress live.
130​
131### Session-id events with any adapter
132​
133Each adapter sends its own name (`claude-code.session-id`, `codex.session-id`, `grok-build.session-id`, `opencode.session-id`). So the type of the name is the template literal `` `${string}.session-id` ``, not one string.
134​
135If you know the adapter, compare the exact name. It types `chunk.value` like any other event:
136​
137```ts
138import { resumeSession } from './session'
139import { stream } from './my-run'
140​
141for await (const chunk of stream) {
142 if (chunk.type === 'CUSTOM' && chunk.name === 'claude-code.session-id') {
143 resumeSession(chunk.value.sessionId) // typed as string
144 }
146```
147​
148`chunk.name.endsWith('.session-id')` does **not** narrow the type. It is a plain boolean, so `chunk.value` stays untyped, even though the check is correct at runtime.
149​
150To handle the session id of any adapter without a list of names, write a small type predicate:
151​
152```ts
153import type { KnownCustomEvent, SessionIdEvent } from '@tanstack/ai'
154import { resumeSession } from './session'
155import { stream } from './my-run'
156​
157function isSessionIdEvent(chunk: KnownCustomEvent): chunk is SessionIdEvent {
158 return chunk.name.endsWith('.session-id')
160​
161for await (const chunk of stream) {
162 if (chunk.type === 'CUSTOM' && isSessionIdEvent(chunk)) {
163 resumeSession(chunk.value.sessionId) // typed as string
164 }
166```
167​
168TanStack AI does not ship this guard. You write it yourself, only for this "any adapter" case.
169​
170### Trim what you keep
171​
172To decide if you store a transcript at all, see [Build a Sandbox Adapter](../persistence/build-a-sandbox-adapter). This section is for when you store one and want it smaller.
173​
174The tool output of one run can be hundreds of kilobytes, and results reach your store whole. Your `MessageStore` decides what to keep.
175​
176To keep the cards but limit the size, cap each result:
177​
178```ts
179import type { ModelMessage } from '@tanstack/ai'
180import type { MessageStore } from '@tanstack/ai-persistence'
181import { db } from './db'
182​
183const MAX_RESULT = 8_000
184​
185const store: MessageStore = {
186 async saveThread(threadId, messages) {
187 const capped = messages.map((message: ModelMessage) =>
188 message.role === 'tool' && typeof message.content === 'string'
189 ? { ...message, content: message.content.slice(0, MAX_RESULT) }
190 : message,
191 )
192 await db.saveThread(threadId, capped)
193 },
194 loadThread: (threadId) => db.loadThread(threadId),
196```
197​
198To drop the history, remove each result together with its call. A result without its call is worse than both options, because providers reject it.
199​
200`isSandboxToolCall` tells you which calls the harness ran inside the sandbox, so you do not need to know how they are marked. It also reads a rendered `tool-call` part, which helps when you filter a client-side view.
201​
202```ts
203import { isSandboxToolCall } from '@tanstack/ai-sandbox'
204import type { ModelMessage } from '@tanstack/ai'
205import type { MessageStore } from '@tanstack/ai-persistence'
206import { db } from './db'
207​
208const store: MessageStore = {
209 async saveThread(threadId, messages) {
210 const dropped = new Set<string>()
211 const kept: Array<ModelMessage> = []
212 for (const message of messages) {
213 const calls = message.toolCalls
214 if (calls && calls.length > 0 && calls.every(isSandboxToolCall)) {
215 for (const call of calls) dropped.add(call.id)
216 continue
217 }
218 if (
219 message.role === 'tool' &&
220 message.toolCallId !== undefined &&
221 dropped.has(message.toolCallId)
222 ) {
223 continue
224 }
225 kept.push(message)
226 }
227 await db.saveThread(threadId, kept)
228 },
229 loadThread: (threadId) => db.loadThread(threadId),
231```
232​
233Dropping them is safe. They are display history, and nothing resumes from them. The next request to the model never carries them either, because they name tools that the provider never got.