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

watch.ts

456 lines17.7 KB

1/**
2 * Sandbox file-event hooks — observe create / change / delete of files inside a
3 * sandbox (e.g. as an in-sandbox agent edits the workspace).
4 *
5 * Provider-agnostic: coded against the {@link SandboxHandle} contract only.
6 * Two mechanisms, auto-selected:
7 *
8 * - **Native** — when a provider implements the optional `fs.watch` seam
9 * (local-process does, via Node `fs.watch`), OS events drive the feed with low
10 * latency.
11 * - **Exec-poll** — otherwise (Docker, Cloudflare, any exec-only provider), a
12 * single `find … -printf` snapshot of `mtime\tsize\tpath` is taken every
13 * `intervalMs` and diffed. Works on any Linux container with GNU findutils
14 * (true for `node:*` / debian images) with no extra deps or image changes.
15 *
16 * The feed intentionally rides only the portable surface, so the same
17 * `watchWorkspace` call behaves identically across providers.
18 */
19import { DEFAULT_WORKSPACE_ROOT } from './bootstrap'
20import type { SandboxHandle } from './contracts'
21import type { SandboxFileEvent } from '@tanstack/ai'
22import type { InternalLogger } from '@tanstack/ai/adapter-internals'
23​
24export type { SandboxFileEvent } from '@tanstack/ai'
25export type FileEventType = SandboxFileEvent['type']
26​
27export interface WatchOptions {
28 /** Called for every observed file event. */
29 onEvent: (event: SandboxFileEvent) => void
30 /** Workspace root to watch. Defaults to `/workspace`. */
31 root?: string
32 /** Poll interval for the exec-poll fallback, in ms. Defaults to 700. */
33 intervalMs?: number
34 /**
35 * Directory-name fragments to ignore (a path containing `/<entry>/` is
36 * skipped). Defaults to `['.git', 'node_modules']`.
37 */
38 ignore?: Array<string>
39 /** Stop watching when this signal aborts. */
40 signal?: AbortSignal
41 /**
42 * Optional logger. When present, a failed `find` poll (non-zero exit or a
43 * thrown exec) is logged instead of silently degrading the snapshot — the
44 * failure mode a plain exec-poll watcher hides.
45 */
46 logger?: InternalLogger
48​
49export interface SandboxWatchHandle {
50 /** Stop the watcher and release its resources. */
51 stop: () => Promise<void>
53​
54const DEFAULT_INTERVAL_MS = 700
55const DEFAULT_IGNORE = ['.git', 'node_modules']
56​
57/** POSIX single-quote escape for embedding values in a shell command. */
58function q(value: string): string {
59 return `'${value.replace(/'/g, `'\\''`)}'`
61​
62/**
63 * Diff two file snapshots (`Map<path, signature>`, signature = `mtime\tsize`).
64 * Pure — the heart of the exec-poll path, unit-tested in isolation.
65 */
66export function diffSnapshots(
67 prev: Map<string, string>,
68 next: Map<string, string>,
69 timestamp: number,
70): Array<SandboxFileEvent> {
71 const events: Array<SandboxFileEvent> = []
72 for (const [path, sig] of next) {
73 const before = prev.get(path)
74 if (before === undefined) events.push({ type: 'create', path, timestamp })
75 else if (before !== sig) events.push({ type: 'change', path, timestamp })
76 }
77 for (const path of prev.keys()) {
78 if (!next.has(path)) events.push({ type: 'delete', path, timestamp })
79 }
80 return events
82​
83/**
84 * Build the `find` command that prints `mtime\tsize\tpath` for every file.
85 * Searches `.` (relative to the exec `cwd`) rather than an absolute root: a
86 * provider's `exec` maps only `cwd` onto the real filesystem, not literal path
87 * arguments, so `find <virtual-root>` would look at a non-existent host path on
88 * mapped-root providers (e.g. local-process). Emitted `%p` values are
89 * root-normalized in {@link parseFindOutput}.
90 */
91function buildFindCommand(ignore: Array<string>): string {
92 const prunes = ignore
93 .map((entry) => `-not -path ${q(`*/${entry}/*`)}`)
94 .join(' ')
95 return `find . -type f ${prunes} -printf '%T@\\t%s\\t%p\\n'`
97​
98/**
99 * Parse `find -printf` output into a `Map<path, signature>`. `find .` prints
100 * paths like `./sub/file`; map them back under `root` so event paths match the
101 * native-watch shape (`<root>/sub/file`).
102 */
103function parseFindOutput(stdout: string, root: string): Map<string, string> {
104 const base = root.replace(/\/+$/, '')
105 const snapshot = new Map<string, string>()
106 for (const line of stdout.split('\n')) {
107 if (line === '') continue
108 const firstTab = line.indexOf('\t')
109 const secondTab = line.indexOf('\t', firstTab + 1)
110 if (firstTab === -1 || secondTab === -1) continue
111 const mtime = line.slice(0, firstTab)
112 const size = line.slice(firstTab + 1, secondTab)
113 const rel = line.slice(secondTab + 1).replace(/^\.\/?/, '')
114 const path = rel === '' ? base : `${base}/${rel}`
115 snapshot.set(path, `${mtime}\t${size}`)
116 }
117 return snapshot
119​
120/** Whether a path should be ignored (contains a `/<entry>/` fragment). */
121function isIgnored(path: string, ignore: Array<string>): boolean {
122 return ignore.some((entry) => path.includes(`/${entry}/`))
124​
125/**
126 * Start watching a sandbox workspace for file events. Picks the native
127 * `fs.watch` fast-path when the provider advertises it, otherwise polls via
128 * `find`. Returns a handle whose `stop()` tears everything down.
129 */
130export async function watchWorkspace(
131 handle: SandboxHandle,
132 options: WatchOptions,
133): Promise<SandboxWatchHandle> {
134 const root = options.root ?? DEFAULT_WORKSPACE_ROOT
135 const ignore = options.ignore ?? DEFAULT_IGNORE
136 const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS
137​
138 // Already aborted before we start — don't begin any async work.
139 if (options.signal?.aborted) return { stop: () => Promise.resolve() }
140​
141 if (handle.fs.watch) {
142 return startNativeWatch(handle, { ...options, root, ignore })
143 }
144 return startPollWatch(handle, { ...options, root, ignore, intervalMs })
146​
147/** Native fs.watch path: OS events, disambiguated against a known-path set. */
148async function startNativeWatch(
149 handle: SandboxHandle,
150 options: WatchOptions & { root: string; ignore: Array<string> },
151): Promise<SandboxWatchHandle> {
152 const { onEvent, root, ignore, logger } = options
153 const watch = handle.fs.watch
154 if (!watch) throw new Error('native watch is unavailable on this provider')
155 // Seed the set of existing files so the first event per path is classified
156 // correctly (create vs change).
157 const seed = await collectPaths(handle, root, ignore, logger)
158 const known = seed.files
159 // If the ROOT list failed, `known` is untrustworthy — every pre-existing
160 // file would misclassify as `create` on its first edit. Re-seed lazily on
161 // the next event(s): by the time real activity arrives the fs has usually
162 // recovered, and re-listing then establishes the baseline. Dedupe concurrent
163 // re-seeds behind a single in-flight promise.
164 // ponytail: a file genuinely CREATED in the narrow window between the failed
165 // seed and the first event gets picked up by the re-seed and so mislabels as
166 // `change` once. That's strictly better than the whole-run mislabel a
167 // never-recovered empty seed causes, and `diff()` is correct regardless.
168 let seeded = seed.rootOk
169 let reseeding: Promise<void> | null = null
170 const ensureSeeded = (): Promise<void> => {
171 if (seeded) return Promise.resolve()
172 if (!reseeding) {
173 reseeding = collectPaths(handle, root, ignore, logger).then((r) => {
174 if (r.rootOk) {
175 for (const p of r.files) known.add(p)
176 seeded = true
177 logger?.sandbox(
178 'sandbox watch: re-seeded after failed initial seed',
179 {
180 root,
181 },
182 )
183 }
184 reseeding = null
185 })
186 }
187 return reseeding
188 }
189​
190 const subscription = await watch(root, (raw) => {
191 const path = raw.path
192 if (isIgnored(path, ignore)) return
193 void (async () => {
194 await ensureSeeded()
195 const exists = await handle.fs.exists(path)
196 const timestamp = Date.now()
197 if (!exists) {
198 if (known.delete(path)) onEvent({ type: 'delete', path, timestamp })
199 return
200 }
201 if (known.has(path)) onEvent({ type: 'change', path, timestamp })
202 else {
203 known.add(path)
204 onEvent({ type: 'create', path, timestamp })
205 }
206 })().catch((error: unknown) => {
207 // A failed classify (e.g. `fs.exists` threw) drops this file's event —
208 // log it so a missing diff isn't silent (the whole point of the watcher).
209 logger?.warn('sandbox watch: native event classify failed', {
210 path,
211 error,
212 })
213 })
214 })
215​
216 // A failed `subscription.stop()` can leak an OS-level watch — log rather
217 // than swallow it silently.
218 const logStopFailure = (error: unknown): void =>
219 logger?.warn('sandbox watch: native subscription.stop() failed', {
220 root,
221 error,
222 })
223 const onAbort = (): void => void subscription.stop().catch(logStopFailure)
224 options.signal?.addEventListener('abort', onAbort, { once: true })
225 // The signal may have aborted during the awaits above (the once-listener
226 // would have missed it) — tear down now if so.
227 if (options.signal?.aborted) void subscription.stop().catch(logStopFailure)
228​
229 return {
230 stop: async () => {
231 options.signal?.removeEventListener('abort', onAbort)
232 await subscription.stop()
233 },
234 }
236​
237/** Exec-poll path: snapshot `find -printf` on an interval and diff. */
238async function startPollWatch(
239 handle: SandboxHandle,
240 options: WatchOptions & {
241 root: string
242 ignore: Array<string>
243 intervalMs: number
244 },
245): Promise<SandboxWatchHandle> {
246 const { onEvent, root, ignore, intervalMs, logger } = options
247 const command = buildFindCommand(ignore)
248 const controller = new AbortController()
249​
250 // A poll result: the parsed snapshot plus whether `find` completed cleanly.
251 // `null` means the poll produced no usable output at all (thrown exec, or a
252 // non-zero exit with empty stdout) — callers preserve the previous snapshot.
253 // Collapsing a failed poll to `{}` would make the next diff fabricate a
254 // `delete` for every tracked file (and a `create` for each on recovery) —
255 // one transient `find` blip would fan a phantom storm out to hooks/stream.
256 interface Poll {
257 map: Map<string, string>
258 /** `false` when `find` exited non-zero but still printed rows (partial). */
259 complete: boolean
260 }
261 // Escalate a steady-state poll throw to `warn` after this many in a row.
262 const STEADY_STATE_THROW_WARN_AFTER = 3
263 let consecutiveThrows = 0
264 const snapshot = async (isInitial = false): Promise<Poll | null> => {
265 let result
266 try {
267 result = await handle.process.exec(command, {
268 cwd: root,
269 signal: controller.signal,
270 })
271 consecutiveThrows = 0 // exec returned (any exit code) — the seam is alive
272 } catch (error) {
273 // Thrown exec — container not ready, `find` seam rejects, or a
274 // mid-teardown abort. Treat as a failed poll so BOTH the initial seed
275 // and every tick preserve `previous` instead of rejecting setup (which
276 // would crash the run and leak the sandbox) or the interval.
277 if (isInitial) {
278 // The INITIAL poll can't be a teardown (a pre-aborted signal is guarded
279 // in `watchWorkspace`), so a throw here is an unambiguous anomaly (`find`
280 // missing, container never ready) that leaves the watcher dead for the
281 // whole run — surface it at `warn`.
282 logger?.warn('sandbox watch: initial `find` poll threw', {
283 root,
284 error,
285 })
286 } else if (controller.signal.aborted) {
287 // Mid-teardown abort — expected, stay quiet.
288 logger?.sandbox('sandbox watch: `find` poll threw during teardown', {
289 root,
290 error,
291 })
292 } else {
293 // Steady-state throw while NOT tearing down. One is usually a transient
294 // blip (→ `sandbox`), but a run of them means the exec seam is wedged:
295 // every poll returns null and the watcher emits nothing for the rest of
296 // the run. That silent-death case escalates to `warn` (on by default).
297 consecutiveThrows += 1
298 if (consecutiveThrows >= STEADY_STATE_THROW_WARN_AFTER) {
299 logger?.warn('sandbox watch: `find` poll threw repeatedly', {
300 root,
301 error,
302 consecutiveThrows,
303 })
304 } else {
305 logger?.sandbox('sandbox watch: `find` poll threw', { root, error })
306 }
307 }
308 return null
309 }
310 if (result.exitCode === 0) {
311 return { map: parseFindOutput(result.stdout, root), complete: true }
312 }
313 // Non-zero exit doesn't mean "no data": GNU `find` exits >0 on the first
314 // permission-denied entry it hits mid-traversal (common in containers, and
315 // the ignore list is a `-not -path` filter, not `-prune`, so `find` still
316 // descends into unreadable dirs) yet still prints every readable file. Use
317 // that partial output — marked `complete: false` so the tick merges rather
318 // than diffs it — instead of blinding the watcher for the whole run. Only a
319 // non-zero exit with NO output is a truly failed poll.
320 if (result.stdout !== '') {
321 logger?.sandbox(
322 'sandbox watch: `find` non-zero exit with partial output',
323 { root, exitCode: result.exitCode, stderr: result.stderr },
324 )
325 return { map: parseFindOutput(result.stdout, root), complete: false }
326 }
327 logger?.warn('sandbox watch: `find` poll exited non-zero with no output', {
328 root,
329 exitCode: result.exitCode,
330 stderr: result.stderr,
331 })
332 return null
333 }
334​
335 // `null` until the first poll that yields usable output. A failed INITIAL
336 // poll must NOT seed an empty baseline — the first successful poll would then
337 // diff against `{}` and fabricate a `create` for every pre-existing file. So
338 // the first non-null snapshot is adopted as the baseline WITHOUT diffing.
339 let previous: Map<string, string> | null = null
340 // Whether `previous` was established from a COMPLETE poll. A baseline seeded
341 // from a PARTIAL poll is provisional — files unreadable during that poll are
342 // absent from it and would later fabricate `create`s when they recover — so
343 // the first complete poll re-baselines without diffing.
344 let seededFromComplete = false
345 {
346 const poll = await snapshot(true)
347 if (poll) {
348 previous = poll.map
349 seededFromComplete = poll.complete
350 }
351 }
352 const state = { running: true }
353​
354 const tick = async (): Promise<void> => {
355 if (!state.running) return
356 try {
357 const poll = await snapshot()
358 // Failed poll — keep `previous` and retry next tick (see `snapshot`).
359 if (poll === null) return
360 if (previous === null) {
361 // First usable snapshot after a failed initial poll — seed, don't diff.
362 previous = poll.map
363 seededFromComplete = poll.complete
364 return
365 }
366 if (!seededFromComplete && poll.complete) {
367 // First complete poll after a provisional (partial) seed — re-baseline
368 // WITHOUT diffing, so files merely unreadable at seed time don't
369 // fabricate `create`s. (Real creates during this degraded-startup
370 // window are missed — an acceptable trade for not fabricating events.)
371 logger?.sandbox(
372 'sandbox watch: re-baselined after provisional partial seed',
373 { root },
374 )
375 previous = poll.map
376 seededFromComplete = true
377 return
378 }
379 // A partial (non-`complete`) poll can't distinguish "deleted" from
380 // "transiently unreadable this poll", so MERGE it over `previous`: pick
381 // up new/changed files without fabricating a `delete` for a path this
382 // poll simply couldn't see. A real deletion still surfaces on the next
383 // complete poll.
384 const next = poll.complete
385 ? poll.map
386 : new Map([...previous, ...poll.map])
387 for (const event of diffSnapshots(previous, next, Date.now())) {
388 onEvent(event)
389 }
390 previous = next
391 } catch (error) {
392 // Defensive: a throw from diff dispatch — preserve `previous`, retry.
393 logger?.sandbox('sandbox watch: tick failed', { root, error })
394 }
395 }
396​
397 const timer = setInterval(() => void tick(), intervalMs)
398 // Don't keep the event loop alive on the watcher alone.
399 if (typeof timer.unref === 'function') timer.unref()
400​
401 const stop = (): Promise<void> => {
402 if (state.running) {
403 state.running = false
404 clearInterval(timer)
405 controller.abort()
406 options.signal?.removeEventListener('abort', onAbort)
407 }
408 return Promise.resolve()
409 }
410 const onAbort = (): void => void stop()
411 options.signal?.addEventListener('abort', onAbort, { once: true })
412 // The signal may have aborted during the initial `await snapshot()` above
413 // (the once-listener would have missed it) — tear down now if so.
414 if (options.signal?.aborted) void stop()
415​
416 return { stop }
418​
419/**
420 * Recursively collect file paths under `root`, honoring `ignore`. `rootOk` is
421 * `false` when the ROOT `list` itself failed — the seed is then untrustworthy
422 * (empty/partial), which the native watcher uses to trigger a lazy re-seed. A
423 * failed *subdirectory* list is logged but doesn't flip `rootOk` (its files are
424 * simply absent, a smaller misclassification surface).
425 */
426async function collectPaths(
427 handle: SandboxHandle,
428 root: string,
429 ignore: Array<string>,
430 logger?: InternalLogger,
431): Promise<{ files: Set<string>; rootOk: boolean }> {
432 const files = new Set<string>()
433 let rootOk = true
434 const walk = async (dir: string, isRoot: boolean): Promise<void> => {
435 let entries: Awaited<ReturnType<SandboxHandle['fs']['list']>>
436 try {
437 entries = await handle.fs.list(dir)
438 } catch (error) {
439 // A dir we can't list is seeded as empty, so its existing files would
440 // later misclassify as `create` on first edit — log rather than hide it.
441 if (isRoot) rootOk = false
442 logger?.warn('sandbox watch: failed to list directory while seeding', {
443 dir,
444 error,
445 })
446 return
447 }
448 for (const entry of entries) {
449 if (ignore.includes(entry.name)) continue
450 if (entry.type === 'dir') await walk(entry.path, false)
451 else files.add(entry.path)
452 }
453 }
454 await walk(root, true)
455 return { files, rootOk }