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

observability.md

182 lines7.2 KB

1---
2title: Observability (Advanced)
3id: observability
4order: 10
5description: "Run server-side code on every file the agent creates, changes, or deletes, read the diff, log sandbox internals, and watch a workspace outside a chat() run."
6---
7​
8Observe sandbox file changes on the server. Log each edit, store an audit trail, or post the diff.
9​
10File hooks do that. Declare them on the sandbox, and they run on the server for every file the agent touches.
11​
12## Log every change the agent makes
13​
141. Add `hooks` to `defineSandbox`.
152. Read `e.path` and `e.type`, and call `e.diff()` when you want the patch.
16​
17```ts
18import { defineSandbox } from '@tanstack/ai-sandbox'
19import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
20​
21export const repoSandbox = defineSandbox({
22 id: 'repo-agent',
23 provider: dockerSandbox({ image: 'node:22' }),
24 hooks: {
25 // Every event.
26 onFile: (e) => console.log(`[${e.type}] ${e.path}`),
27 // Changes only, with the patch.
28 onFileChange: async (e) => {
29 const patch = await e.diff()
30 console.log(`${e.path} changed:\n${patch}`)
31 },
32 },
33})
34```
35​
36Run the agent with this sandbox. Each edit prints its path, and each change prints its unified diff.
37​
38## How it works
39​
40- **A watcher starts with the sandbox.** On local-process it uses native OS file watching. On Docker and other exec-only providers, it polls with a portable `find`. No extra dependencies, no image changes.
41- **Sandbox hooks fire once per file event**, however many runs share the sandbox.
42- **Content is lazy.** `before()`, `after()`, and `diff()` are methods. They read the file or call `git` only when you call them. A hook that reads only `e.path` and `e.type` costs nothing.
43- **The client gets events too.** The engine emits one `CUSTOM` [`sandbox.file`](./events#custom-events) event per change, with or without hooks.
44​
45## Advanced
46​
47### Sandbox-scoped hooks
48​
49All hooks on `defineSandbox({ hooks })`:
50​
51| Hook | Fires |
52| --- | --- |
53| `onFile` | For every file event. |
54| `onFileCreate`, `onFileChange`, `onFileDelete` | For one event type. |
55| `onReady(handle)` | When the sandbox is ready. |
56| `onError(err)` | When the sandbox fails. |
57| `onDestroy()` | When the sandbox is destroyed. |
58​
59A hook that throws is logged under the `errors` category. It does not break the run.
60​
61### Run-scoped hooks
62​
63For per-request work, such as an audit log keyed by run, use the `sandbox` hook group on `defineChatMiddleware`. These hooks fire **per run**, and each one gets the run's `ChatMiddlewareContext` first:
64​
65```ts
66import { defineChatMiddleware } from '@tanstack/ai'
67import { db } from './db'
68​
69export const auditMiddleware = defineChatMiddleware({
70 name: 'audit',
71 sandbox: {
72 onFile: (ctx, e) => console.log(ctx.runId, e.type, e.path),
73 onFileChange: async (ctx, e) => {
74 const [before, after] = await Promise.all([e.before(), e.after()])
75 db.log({ run: ctx.runId, path: e.path, before, after })
76 },
77 },
78})
79```
80​
81Both hook groups run on the server, separate from the stream.
82​
83### What `before`, `after`, and `diff` return
84​
85The event every hook gets:
86​
87```ts
88interface SandboxFileHookEvent {
89 type: 'create' | 'change' | 'delete'
90 path: string
91 timestamp: number
92 before(): Promise<string> // content at the session baseline
93 after(): Promise<string> // current content
94 diff(): Promise<string> // unified patch against the baseline
96```
97​
98At `onReady`, the sandbox runs `git rev-parse HEAD` once and keeps that commit as the session baseline. If the workspace is not a git repo, or has no commits, the baseline is empty. Every `before()` and `diff()` in the session compares to that same baseline. So `onFileChange` reports the **total** change since the run started, not the change since the last poll. `after()` always reads the file as it is on disk now.
99​
100| Case | `before()` | `after()` | `diff()` |
101| --- | --- | --- | --- |
102| Tracked file, changed | Baseline content | Current content | Patch against the baseline |
103| Tracked file, same as baseline | Baseline content | Current content | `''` |
104| New untracked file, on create and on every later edit | `''` | Current content | A synthesized add-patch from `after()` |
105| Deleted file | Baseline content | `''` | Delete patch |
106| Non-git workspace | `''` | `''` | A synthesized add-patch from `after()`. `''` for a delete. |
107| Untracked, git-ignored file (a `.env`, a credentials file) | `''` | Current content | `''`, so its content never reaches the diff feed. The event still fires. |
108​
109`git diff` ignores untracked files. That is why a file the agent creates gets the synthesized add-patch on every later edit too: it never streams an empty diff.
110​
111The accessors never throw. A failed `git`, `exec`, or file read falls back to `''` (the watcher keeps its last snapshot). Each failure is logged first:
112​
113- **Real faults** go to the `errors` category, which is on by default: a failed `git diff`, an unreadable file, a `find` poll that exits non-zero, a lost git baseline.
114- **Expected empty values** go to the `sandbox` debug category: for example, `before()` of a new file. Turn it on with [`debug`](#debugging).
115​
116### Turn off file watching
117​
118Set `fileEvents: false`. The watcher does not start, and no `sandbox.file` events are sent:
119​
120```ts
121import { defineSandbox } from '@tanstack/ai-sandbox'
122import { dockerSandbox } from '@tanstack/ai-sandbox-docker'
123​
124export const quietSandbox = defineSandbox({
125 id: 'quiet-agent',
126 provider: dockerSandbox({ image: 'node:22' }),
127 fileEvents: false,
128})
129```
130​
131To also send a `sandbox.file.diff` event per change to the client, set `fileEvents: { diff: true }`. See [Events](./events).
132​
133### Debugging
134​
135To log sandbox internals (watcher start and stop, event dispatch, lifecycle steps), pass the `sandbox` debug category to `chat()`:
136​
137```ts
138import { chat, chatParamsFromRequest, toServerSentEventsResponse } from '@tanstack/ai'
139import { grokBuildText } from '@tanstack/ai-grok-build'
140import { withSandbox } from '@tanstack/ai-sandbox'
141import { repoSandbox } from './sandbox'
142​
143export async function POST(request: Request) {
144 const { messages, threadId } = await chatParamsFromRequest(request)
145 const stream = chat({
146 adapter: grokBuildText('grok-build'),
147 messages,
148 threadId,
149 middleware: [withSandbox(repoSandbox)],
150 debug: { sandbox: true }, // or `debug: true` for every category
151 })
152 return toServerSentEventsResponse(stream)
154```
155​
156### Watch a workspace outside a run
157​
158The hooks are built on `watchWorkspace()`. Use it directly when you want the watcher outside a `chat()` run:
159​
160```ts
161import { watchWorkspace } from '@tanstack/ai-sandbox'
162import { repoSandbox } from './sandbox'
163​
164const handle = await repoSandbox.ensure({ threadId: 'thread-1', runId: 'run-1' })
165const watcher = await watchWorkspace(handle, {
166 onEvent: (event) => {
167 // event.type is 'create' | 'change' | 'delete'
168 console.log(`${event.type} ${event.path}`)
169 },
170})
171​
172// Do your work here, then stop the watcher.
173await watcher.stop()
174```
175​
176| Option | Default | What it does |
177| --- | --- | --- |
178| `onEvent` | required | Called for each file event. |
179| `root` | `/workspace` | The directory to watch. |
180| `intervalMs` | `700` | Poll interval, for the `find` fallback only. |
181| `ignore` | `['.git', 'node_modules']` | Skip any path that contains `/<entry>/`. |
182| `signal` | none | Stop watching when it aborts. |