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