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

observability.md

228 lines8.4 KB

1---
2title: Observability (Advanced)
3id: observability
4order: 10
5description: "Run server-side hooks on every file the agent touches, log sandbox internals, and watch a workspace outside a chat() run."
6---
7​
8The [events stream](./events) is what a *client* reads. This page is the
9*server-side* half: hooks that fire on every file the agent touches, sandbox
10debug logging, and the low-level watcher you can drive outside a `chat()` run.
11​
12## File-event hooks
13​
14Listen to files being created, changed or deleted inside a sandbox, for
15example to watch what the agent edits as it works. The watcher is
16provider-agnostic: it uses native OS watching where the provider supports it
17(local-process) and falls back to a portable `find` poll everywhere else (Docker
18and other exec-only providers), with no extra dependencies or image changes.
19​
20There are two places to declare these hooks, with different scopes.
21​
22### Sandbox-scoped hooks
23​
24Declared directly on `defineSandbox({ hooks })`. They fire **once per file
25event**, regardless of how many runs share the sandbox, alongside the sandbox's
26own lifecycle callbacks:
27​
28```ts
29import { defineSandbox } from '@tanstack/ai-sandbox'
30import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
31​
32const repoSandbox = defineSandbox({
33 id: 'repo-agent',
34 provider: dockerSandbox({ image: 'node:22' }),
35 hooks: {
36 // catch-all: fires for every event
37 onFile: (e) => console.log(`[${e.type}] ${e.path}`),
38 // type-specific variants
39 onFileCreate: (e) => console.log('created', e.path),
40 onFileChange: (e) => console.log('changed', e.path),
41 onFileDelete: (e) => console.log('deleted', e.path),
42 // lifecycle
43 onReady: (handle) => console.log('sandbox ready', handle.id),
44 onError: (err) => console.error('sandbox error', err),
45 onDestroy: () => console.log('sandbox destroyed'),
46 },
47})
48```
49​
50### Run-scoped hooks
51​
52To handle file events inside a middleware (for example per-request audit
53logging), use the `sandbox` hook group on `defineChatMiddleware`. These fire
54**per-run**, and each handler receives the current run's `ChatMiddlewareContext`:
55​
56```ts
57import { defineChatMiddleware } from '@tanstack/ai'
58import { db } from './db'
59​
60const auditMiddleware = defineChatMiddleware({
61 name: 'audit',
62 // ctx is the ChatMiddlewareContext for the current run
63 sandbox: {
64 onFile: (ctx, e) => console.log(ctx.runId, e.type, e.path),
65 onFileCreate: (ctx, e) => db.log({ run: ctx.runId, event: e }),
66 },
67})
68```
69​
70Both hook groups fire **server-side** and are independent of the stream: the
71engine automatically emits one `CUSTOM` [`sandbox.file`](./events#custom-events)
72event per change regardless of whether you register any hooks, so the client
73can react to the same edits without extra middleware.
74​
75## Reading content and diffs in hooks
76​
77The event every hook receives is more than `{ type, path, timestamp }`. It also
78carries lazy, git-backed accessors for the file's content:
79​
80```ts
81interface SandboxFileHookEvent {
82 type: "create" | "change" | "delete";
83 path: string;
84 timestamp: number;
85 before(): Promise<string>; // content at the session baseline ('' if new / non-git)
86 after(): Promise<string>; // current content ('' if deleted)
87 diff(): Promise<string>; // unified patch vs the baseline
89```
90​
91Reach for `diff()` to show what the agent changed. There is no need to hand-roll a
92`git diff` yourself:
93​
94```ts
95import { defineSandbox } from "@tanstack/ai-sandbox";
96import { dockerSandbox } from "@tanstack/ai-sandbox-docker";
97​
98const repoSandbox = defineSandbox({
99 id: "repo-agent",
100 provider: dockerSandbox({ image: "node:22" }),
101 hooks: {
102 onFileChange: async (e) => {
103 const patch = await e.diff();
104 console.log(`${e.path} changed:\n${patch}`);
105 },
106 },
107});
108```
109​
110The same accessors are available on run-scoped hooks, where `e` is the
111second argument:
112​
113```ts
114import { defineChatMiddleware } from "@tanstack/ai";
115import { db } from "./db";
116​
117const auditMiddleware = defineChatMiddleware({
118 name: "audit",
119 sandbox: {
120 onFileChange: async (ctx, e) => {
121 const [before, after] = await Promise.all([e.before(), e.after()]);
122 db.log({ run: ctx.runId, path: e.path, before, after });
123 },
124 },
125});
126```
127​
128**Lazy, path-only hooks pay nothing.** `before()`, `after()`, and `diff()`
129are methods, not fields: each one only reads the file or shells out to `git`
130when you call it. A hook that only reads `e.path` / `e.type` (like the
131catch-all logger in [Sandbox-scoped hooks](#sandbox-scoped-hooks) above)
132never touches the filesystem or spawns a process.
133​
134**Git session baseline.** At `onReady`, the sandbox snapshots
135`git rev-parse HEAD` once, as the session's baseline commit (empty if the
136workspace isn't a git repo, or has no commits yet). Every `before()` and
137`diff()` call for the rest of the session diffs against that same fixed
138baseline, so `onFileChange` always reports the file's **cumulative** change
139since the run started, not just the delta since the watcher's last poll.
140`after()` always reads the file's current on-disk content, independent of
141the baseline. None of the three accessors throw: a deleted file resolves
142`after()` to `''` (it still has `before()`); a new file resolves `before()`
143to `''` (it still has `after()`); a non-git workspace resolves **both**
144`before()` and `after()` to `''` and makes `diff()` fall back to a
145synthesized add-patch built from `after()`, except for a `delete` event in
146a non-git workspace, where there's nothing to synthesize and `diff()`
147resolves to `''`. In a git workspace, a file git **is not tracking yet** (one the
148agent just created) and every later edit to it diff empty because
149`git diff` ignores untracked files, so `diff()` falls back to that same
150synthesized add-patch whenever the file is absent at the baseline. A file the
151agent creates (and keeps editing) therefore never streams an empty diff, while
152a **tracked** file that's identical to the baseline correctly stays empty.
153A **git-ignored** file (e.g. a `.env` or a credentials file) is the exception:
154the file event still fires so you're notified it changed, but `diff()` returns
155`''` so its contents are never surfaced in the diff feed.
156​
157Every git, exec and fs failure behind these accessors, and behind the `find`-poll
158watcher, still falls back to `''` (or preserves the last snapshot), but is
159**logged first** so a failure is observable rather than a silent empty value:
160real anomalies (a failed `git diff`, an unreadable file, a `find` poll that
161exits non-zero, a lost git baseline) under the `errors` category (on by
162default), and expected-empty conditions (a new file's `before()`) under the
163`sandbox` debug category. Enable `debug: { sandbox: true }` (see
164[Debugging](#debugging)) to see the latter.
165​
166## Disabling file watching
167​
168To stop the watcher and suppress `sandbox.file` events for a sandbox entirely,
169set `fileEvents: false`:
170​
171```ts
172import { defineSandbox } from '@tanstack/ai-sandbox'
173import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
174​
175const sandbox = defineSandbox({
176 id: 'quiet-agent',
177 provider: dockerSandbox({ image: 'node:22' }),
178 fileEvents: false, // watcher not started; no sandbox.file events emitted
179})
180```
181​
182## Debugging
183​
184To log sandbox internals (watcher start and stop, event dispatch, lifecycle
185transitions) pass the `sandbox` debug category to `chat()`:
186​
187```ts
188import { chat } from '@tanstack/ai'
189import { grokBuildText } from '@tanstack/ai-grok-build'
190import { withSandbox } from '@tanstack/ai-sandbox'
191import { repoSandbox } from './sandbox'
192import { messages } from './chat-context'
193​
194chat({
195 threadId: 'thread-1',
196 adapter: grokBuildText('grok-build'),
197 messages,
198 middleware: [withSandbox(repoSandbox)],
199 debug: { sandbox: true }, // or `debug: true` for all categories
200})
201```
202​
203## Low-level: `watchWorkspace()`
204​
205`watchWorkspace()` is the building block the hooks are built on. Reach for it
206when you want the watcher **outside** a `chat()` run:
207​
208```ts
209import { watchWorkspace } from '@tanstack/ai-sandbox'
210import { repoSandbox } from './sandbox'
211​
212const handle = await repoSandbox.ensure({ threadId: 'thread-1', runId: 'run-1' })
213const watcher = await watchWorkspace(handle, {
214 onEvent: (event) => {
215 // event.type is 'create' | 'change' | 'delete'
216 console.log(`${event.type} ${event.path}`)
217 },
218 ignore: ['.git', 'node_modules'], // default
219})
220// …do work outside a chat run…
221await watcher.stop()
222```
223​
224## Related
225​
226- [Events](./events): the `CUSTOM` event stream the client reads.
227- [Lifecycle & Snapshots](./lifecycle): when sandboxes are created and torn down.
228- [Tools](./tools): bridged host tools that surface as tool-call chunks.