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

custom-events.md

224 lines10.9 KB

1---
2title: Custom Events Reference
3id: custom-events
4order: 1
5description: "Every CUSTOM event TanStack AI itself emits, unified as KnownCustomEvent, and the ChatStream type that lets a plain `if (chunk.name === '…')` narrow chunk.value — no helper, no cast."
6keywords:
7 - tanstack ai
8 - custom events
9 - KnownCustomEvent
10 - ChatStream
11 - ag-ui protocol
12 - CUSTOM event
13 - stream narrowing
14---
15​
16You're reading a `chat()` stream and you've hit a `CUSTOM` event — maybe
17[`sandbox.file.diff`](../sandbox/events), maybe a Code Mode progress event,
18maybe `structured-output.complete`. Each feature page documents its own
19events in context. This page is the map: every `CUSTOM` event TanStack AI
20itself emits, in one table, plus the type mechanism that lets you read any of
21them with a plain `if` — no helper function, no cast.
22​
23## The type: `ChatStream`
24​
25`chat()` returns `ChatStream` by default (no `outputSchema`, `stream` not
26explicitly `false`):
27​
28```ts
29import { chat } from "@tanstack/ai";
30import { openaiText } from "@tanstack/ai-openai";
31import type { ChatStream } from "@tanstack/ai";
32​
33const stream: ChatStream = chat({
34 adapter: openaiText("gpt-5.5"),
35 messages: [{ role: "user", content: "Hello" }],
36});
37```
38​
39`ChatStream` is defined as:
40​
41```ts ignore
42type ChatStream = AsyncIterable<Exclude<StreamChunk, CustomEvent> | KnownCustomEvent>
43```
44​
45`StreamChunk` (the raw AG-UI event union) has exactly one `CUSTOM`-shaped
46member: the generic `CustomEvent` interface, with `name: string` and
47`value: any`. Left in the union unchanged, that single `any` "poisons" every
48narrow — even `if (chunk.type === 'CUSTOM' && chunk.name === 'sandbox.file')`
49would still leave `chunk.value` typed `any`, because TypeScript can't
50distinguish the generic member from a specific one once they're merged.
51`ChatStream` fixes this in two steps: `Exclude<StreamChunk, CustomEvent>`
52removes that generic member, and `| KnownCustomEvent` adds back a
53discriminated union of every event TanStack AI actually emits — each with a
54literal `name` and a concrete `value`. The result is a stream where `CUSTOM`
55events narrow like anything else.
56​
57## Reading events: the plain narrowing pattern
58​
59Check `chunk.type === 'CUSTOM'`, then compare `chunk.name` to a literal
60string. That's the entire client-side API — there is no `isCustomEvent` or
61`isSandboxEvent` guard to import:
62​
63```ts ignore
64import { chat } from "@tanstack/ai";
65import { openaiText } from "@tanstack/ai-openai";
66​
67const stream = chat({
68 adapter: openaiText("gpt-5.5"),
69 messages: [{ role: "user", content: "Hello" }],
70});
71​
72for await (const chunk of stream) {
73 if (chunk.type === "CUSTOM" && chunk.name === "sandbox.file.diff") {
74 console.log(chunk.value.path, chunk.value.diff); // typed, no helper, no cast
75 } else if (chunk.type === "CUSTOM" && chunk.name === "structured-output.complete") {
76 console.log(chunk.value.object); // typed, no helper, no cast
77 }
79```
80​
81## Full taxonomy
82​
83Every interface below extends the base `CustomEvent` (`type: 'CUSTOM'`, plus
84an optional `model?`) with a literal `name` and a concrete `value`. All are
85unioned as `KnownCustomEvent`, exported from `@tanstack/ai` alongside each
86individual interface.
87​
88| Interface | `name` | `value` | Emitted when |
89| --- | --- | --- | --- |
90| `SandboxFileCustomEvent` | `sandbox.file` | `{ type: 'create' \| 'change' \| 'delete'; path: string; timestamp: number }` | per file create/change/delete in an active [sandbox](../sandbox/events) |
91| `SandboxFileDiffEvent` | `sandbox.file.diff` | `{ path: string; diff: string }` | per file change, opt-in via `fileEvents: { diff: true }` |
92| `FileChangedEvent` | `file.changed` | `{ path: string; diff: string }` | a harness adapter (Grok Build, Claude Code, …), once after the run completes |
93| `SessionIdEvent` | `` `${string}.session-id` `` | `{ sessionId: string }` | a harness adapter, once when its in-sandbox session is created or resumed |
94| `CodeModeExecutionStartedEvent` | `code_mode:execution_started` | `{ timestamp: number; codeLength: number }` | [Code Mode](../code-mode/code-mode), when sandbox execution begins |
95| `CodeModeConsoleEvent` | `code_mode:console` | `{ level: 'log' \| 'warn' \| 'error' \| 'info'; message: string; timestamp: number }` | Code Mode, per `console.*` call inside the sandbox |
96| `CodeModeExternalCallEvent` | `code_mode:external_call` | `{ function: string; args: unknown; timestamp: number }` | Code Mode, before a bound `external_*` function runs |
97| `CodeModeExternalResultEvent` | `code_mode:external_result` | `{ function: string; result: unknown; duration: number }` | Code Mode, after a successful `external_*` call |
98| `CodeModeExternalErrorEvent` | `code_mode:external_error` | `{ function: string; error: string; duration: number }` | Code Mode, when an `external_*` call throws |
99| `CodeModeSnippetCallEvent` | `code_mode:snippet_call` | `{ snippet: string; input: unknown; timestamp: number }` | [Code Mode with Snippets](../code-mode/code-mode-with-snippets), before a snippet runs |
100| `CodeModeSnippetResultEvent` | `code_mode:snippet_result` | `{ snippet: string; result: unknown; duration: number; timestamp: number }` | Code Mode with Snippets, after a successful snippet run |
101| `CodeModeSnippetErrorEvent` | `code_mode:snippet_error` | `{ snippet: string; error: string; duration: number; timestamp: number }` | Code Mode with Snippets, when a snippet throws |
102| `SnippetRegisteredEvent` | `snippet:registered` | `{ id: string; name: string; description: string; timestamp: number }` | when a snippet is registered into the tool registry |
103| `StructuredOutputStartEvent` | `structured-output.start` | `{ messageId: string }` | [`chat({ outputSchema, stream: true })`](../structured-outputs/streaming), once per structured message |
104| `StructuredOutputCompleteEvent<T>` | `structured-output.complete` | `{ object: T; raw: string; reasoning?: string }` | structured-output streaming, once with the validated object |
105| `ApprovalRequestedEvent` | `approval-requested` | `{ toolCallId: string; toolName: string; input: unknown; approval: { id: string; needsApproval: true } }` | a server tool needs approval — the run pauses; see [Tool Approval Flow](../tools/tool-approval) |
106| `ToolInputAvailableEvent` | `tool-input-available` | `{ toolCallId: string; toolName: string; input: unknown }` | a client tool is invoked — the run pauses; see [Client Tools](../tools/client-tools) |
107| `UIResourceEvent` | `ui-resource` | `{ resource; serverId?: string; toolCallId: string; toolName: string; meta?: Record<string, unknown> }` | an MCP tool returns a `ui://` resource ([MCP Apps](../mcp/apps)) |
108​
109## These stay CUSTOM
110​
111Harness `*.session-id` events and `structured-output.start` / `structured-output.complete` stay `CUSTOM`. They are not fields on `RUN_FINISHED`.
112​
113Read them with the same `chunk.type === "CUSTOM" && chunk.name === "..."` branch as the rest of this page. See [Streaming structured output](../structured-outputs/streaming) for the complete event.
114​
115## Your own custom events aren't in this union
116​
117Tools and chat middleware can emit application-defined events through
118`emitCustomEvent`.
119​
120A server tool receives `emitCustomEvent` on its execution context:
121​
122```ts
123import { toolDefinition } from "@tanstack/ai";
124import { z } from "zod";
125​
126const importRows = toolDefinition({
127 name: "importRows",
128 description: "Import rows into the dataset, reporting progress as it runs",
129 inputSchema: z.object({ rows: z.array(z.string()) }),
130}).server(async ({ rows }, context) => {
131 for (let i = 0; i < rows.length; i++) {
132 context?.emitCustomEvent("my-app:progress", {
133 done: i + 1,
134 total: rows.length,
135 });
136 }
137 return { imported: rows.length };
138});
139```
140​
141Chat middleware calls the same helper on `ChatMiddlewareContext`. The engine
142yields the chunk while the hook is still running, so a long `onConfig` can
143send `started` before the work finishes:
144​
145```ts
146import { type ChatMiddleware } from "@tanstack/ai";
147​
148async function prepare() {
149 await new Promise<void>((resolve) => {
150 setTimeout(resolve, 1);
151 });
153​
154const progress: ChatMiddleware = {
155 name: "progress",
156 async onConfig(ctx) {
157 if (ctx.phase !== "beforeModel") return;
158 ctx.emitCustomEvent("my-app:progress", { step: "prepare" });
159 await prepare();
160 ctx.emitCustomEvent("my-app:progress", { step: "ready" });
161 },
162};
163```
164​
165With durability on the response, each of these events flushes as soon as it
166is emitted, so `prepare` reaches the client while `prepare()` is still
167running. High-volume names stay in the durability batch:
168`process.stdout`, `process.stderr`, `sandbox.file`, and `sandbox.file.diff`.
169Pass `{ batch: true }` to keep one of your own events in that batch:
170​
171```ts
172import { type ChatMiddleware } from "@tanstack/ai";
173​
174const noisy: ChatMiddleware = {
175 name: "noisy",
176 async onConfig(ctx) {
177 ctx.emitCustomEvent("my-app:ticks", { n: 1 }, { batch: true });
178 },
179};
180```
181​
182These flow over the wire exactly like the built-in events: same `CUSTOM`
183chunk shape, same runtime behavior. But `'my-app:progress'` isn't one of the
184literal names in `KnownCustomEvent`, so it's intentionally absent from
185`ChatStream`'s type. This is the same tradeoff `StructuredOutputStream`
186already made: including a generic fallback member would reintroduce the
187`value: any` poison for every other event on the stream.
188​
189To read your own event's `value`, don't rely on `ChatStream`'s narrowed
190union for that branch — annotate the stream as the wider `StreamChunk` type
191instead, where the generic `CUSTOM` member's `value: any` needs no cast:
192​
193```ts ignore
194import { chat } from "@tanstack/ai";
195import { openaiText } from "@tanstack/ai-openai";
196import type { StreamChunk } from "@tanstack/ai";
197import { importRows } from "./tools";
198​
199const stream: AsyncIterable<StreamChunk> = chat({
200 adapter: openaiText("gpt-5.5"),
201 messages: [{ role: "user", content: "Import these rows" }],
202 tools: [importRows],
203});
204​
205for await (const chunk of stream) {
206 if (chunk.type === "CUSTOM" && chunk.name === "my-app:progress") {
207 console.log(chunk.value.done, chunk.value.total); // value: any — your event, your shape
208 }
210```
211​
212The event still arrives at runtime either way — this only changes what
213TypeScript will let you write. `ChatStream` is the right default for reading
214TanStack AI's own events with full type safety; fall back to `StreamChunk`
215for the branches that read your own.
216​
217## Related
218​
219- [Event metadata](./metadata) — `metadata.tanstack` fields a custom AG-UI server must send so `useChat` gets `finishReason` and model.
220- [Sandbox Events](../sandbox/events) — the sandbox- and harness-specific rows of this table, in context, plus `sandbox.file.diff`'s opt-in.
221- [Observability](../sandbox/observability) — the server-side hook accessors (`before()`/`after()`/`diff()`) that back `sandbox.file.diff`.
222- [Showing Code Mode in the UI](../code-mode/client-integration) — rendering the `code_mode:*` events live.
223- [Streaming UIs](../structured-outputs/streaming) — reading `structured-output.complete` end to end.
224- [Stream Events](../chat/stream-events) for the standard AG-UI `StreamChunk` lifecycle this union extends.