Open History to see the last commit
1/**
2 * SandboxHandle backed by the host machine — no isolation. The "sandbox" is a
3 * real host directory; fs/exec/git operate directly on it.
4 *
5 * TRUST BOUNDARY: local-process runs commands and file writes on the HOST with
6 * the privileges of the current process. It provides NO isolation, NO network
7 * policy, and `exec` runs through a shell. Use it only in trusted/dev contexts
8 * (the fast no-Docker dev loop); never expose it to untrusted prompts in a
9 * context where host compromise matters. For isolation use the Docker or
10 * Cloudflare providers.
11 */
12import { spawn, spawnSync } from 'node:child_process'
13import { existsSync, watch as watchFs } from 'node:fs'
14import * as fsp from 'node:fs/promises'
15import * as path from 'node:path'
16import {
17 DEFAULT_WORKSPACE_ROOT,
18 UnsupportedCapabilityError,
19 createExecBackedGit,
20} from '@tanstack/ai-sandbox'
21import type { ChildProcess } from 'node:child_process'
22import type { Readable } from 'node:stream'
23import type {
24 ExecResult,
25 ProcessOptions,
26 SandboxCapabilities,
27 SandboxHandle,
28 SpawnHandle,
29} from '@tanstack/ai-sandbox'
30
31/**
32 * Resolve a POSIX `sh` to run commands through. Commands are built with POSIX
33 * single-quote quoting (e.g. `--permission-mode 'bypassPermissions'`), so they
34 * must run under a POSIX shell on EVERY platform — on native Windows, `cmd.exe`
35 * (what Node's `shell: true` uses) does not strip single quotes and breaks them.
36 *
37 * - Unix: `sh` resolves via PATH (`/bin/sh`).
38 * - Windows: no POSIX shell on the default PATH, so locate git-bash / WSL's
39 * `sh.exe` — from the `TANSTACK_SANDBOX_SH` override, derived from `git` on
40 * PATH (`…\Git\cmd` → `…\Git\usr\bin\sh.exe`), or common install dirs.
41 * Cached after first resolution.
42 */
43let cachedShell: string | undefined
44function posixShell(): string {
45 if (cachedShell !== undefined) return cachedShell
46 if (process.platform !== 'win32') return (cachedShell = 'sh')
47
48 const candidates: Array<string> = []
49 if (process.env.TANSTACK_SANDBOX_SH) {
50 candidates.push(process.env.TANSTACK_SANDBOX_SH)
51 }
52 for (const dir of (process.env.PATH ?? '').split(path.delimiter)) {
53 if (/\\git\\cmd\\?$/i.test(dir)) {
54 candidates.push(path.join(dir, '..', 'usr', 'bin', 'sh.exe'))
55 candidates.push(path.join(dir, '..', 'bin', 'sh.exe'))
56 }
57 }
58 candidates.push(
59 'C:\\Program Files\\Git\\usr\\bin\\sh.exe',
60 'C:\\Program Files\\Git\\bin\\sh.exe',
61 )
62 for (const candidate of candidates) {
63 if (candidate && existsSync(candidate)) return (cachedShell = candidate)
64 }
65 // Last resort: rely on PATH (a clear ENOENT if no POSIX sh is installed).
66 return (cachedShell = 'sh')
67}
68
69/**
70 * Extra PATH dirs so a Windows git-bash `sh` can find its Unix tools (`sed`,
71 * `dirname`, `uname`, `git`, …). Node spawns `sh.exe` with the bare Windows PATH,
72 * which omits git-bash's `usr/bin`/`mingw64/bin` — so npm CLI shims that are
73 * POSIX shell scripts (e.g. `codex`) fail with "command not found". Empty on
74 * non-Windows or when no real git-bash sh was resolved.
75 */
76let cachedShellPathDirs: Array<string> | undefined
77function posixShellPathDirs(): Array<string> {
78 if (cachedShellPathDirs !== undefined) return cachedShellPathDirs
79 const sh = posixShell()
80 if (process.platform !== 'win32' || sh === 'sh') {
81 return (cachedShellPathDirs = [])
82 }
83 const dirs = [path.dirname(sh)] // …\Git\usr\bin — holds sed/dirname/uname/sh
84 let dir = path.dirname(sh)
85 for (let i = 0; i < 3; i += 1) {
86 if (/\\git$/i.test(dir)) {
87 for (const sub of ['usr\\bin', 'bin', 'mingw64\\bin']) {
88 dirs.push(path.join(dir, sub))
89 }
90 break
91 }
92 dir = path.dirname(dir)
93 }
94 return (cachedShellPathDirs = [...new Set(dirs)].filter((d) => existsSync(d)))
95}
96
97/**
98 * Prepend {@link posixShellPathDirs} to `env`'s PATH in place, respecting the
99 * existing key's casing (Windows uses `Path`) so we never create a duplicate,
100 * ignored variable. No-op off Windows / without a resolved git-bash `sh`.
101 */
102function prependShellPath(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
103 const extraPaths = posixShellPathDirs()
104 if (extraPaths.length > 0) {
105 const pathKey =
106 Object.keys(env).find((k) => k.toUpperCase() === 'PATH') ?? 'PATH'
107 env[pathKey] = [...extraPaths, env[pathKey] ?? '']
108 .filter(Boolean)
109 .join(path.delimiter)
110 }
111 return env
112}
113
114export const LOCAL_PROCESS_CAPS: SandboxCapabilities = {
115 fs: true,
116 exec: true,
117 env: true,
118 ports: true,
119 backgroundProcesses: true,
120 writableStdin: true,
121 // `killTree` forcibly kills the spawned `sh` wrapper AND its descendants — on
122 // POSIX by signalling the whole process GROUP (the wrapper is spawned
123 // `detached`, so a negative pid reaches every descendant), on Windows by
124 // `taskkill /T` plus a verified sweep of the MSYS descendants `/T` cannot
125 // reach. The same `killTree` runs on `signal` abort in both `exec` and
126 // `spawn`, so a spawned process is always forcibly terminable by the caller.
127 //
128 // Signalling the wrapper alone is NOT enough on either platform and this must
129 // not be "simplified" back to that: `sh -c '<cmd>'` does not reliably exec its
130 // command, so killing the `sh` leaves the command running (see `killTree`).
131 killableProcesses: true,
132 snapshots: false,
133 networkPolicy: false,
134 durableFilesystem: true,
135 fork: true,
136}
137
138/**
139 * Decode spawn stdout/stderr as a byte stream, not chunk-by-chunk. A naive
140 * per-chunk `Buffer.toString('utf8')` corrupts any multi-byte UTF-8 character
141 * that a Node stream happens to split across two `data` events — each half
142 * decodes independently into a replacement character. A streaming
143 * `TextDecoder` retains a partial trailing sequence across `decode()` calls
144 * (`{ stream: true }`) and only emits it once the full character has
145 * arrived. We flush (`decoder.decode()` with no args) once the stream ends
146 * so a genuinely truncated trailing sequence is still surfaced (as U+FFFD)
147 * rather than silently dropped — matching the pattern already used in
148 * `ai-sandbox-sprites`'s `client.ts`.
149 */
150async function* decodeStream(stream: Readable | null): AsyncIterable<string> {
151 if (!stream) return
152 const decoder = new TextDecoder('utf-8')
153 for await (const chunk of stream) {
154 yield typeof chunk === 'string'
155 ? chunk
156 : decoder.decode(chunk as Buffer, { stream: true })
157 }
158 const tail = decoder.decode()
159 if (tail !== '') yield tail
160}
161
162/**
163 * Sink for non-fatal teardown diagnostics. Structural on purpose: `@tanstack/ai`'s
164 * `InternalLogger` satisfies it as-is (its `warn` is gated by the `errors`
165 * category, on by default), so a consumer can pass the logger it already has
166 * without this package taking a runtime dependency on it.
167 */
168export interface LocalProcessLogger {
169 warn: (message: string, meta?: Record<string, unknown>) => void
170}
171
172/** Sleep helper for the bounded teardown backoffs below. */
173function delay(ms: number): Promise<void> {
174 return new Promise((resolve) => {
175 setTimeout(resolve, ms)
176 })
177}
178
179/**
180 * Filesystem error codes that mean "something still holds this path", as
181 * opposed to "this removal can never work".
182 *
183 * On Windows a directory cannot be removed while any process holds it open —
184 * most commonly as its CWD, which is exactly what `exec`/`spawn` give the `sh`
185 * wrapper — and the handle is released by the OS *asynchronously*, after the
186 * process has already exited. POSIX has no such rule (`rmdir` tolerates open
187 * handles), which is why this only ever bit on Windows.
188 */
189const BUSY_ERROR_CODES = new Set(['EBUSY', 'EPERM', 'EACCES', 'ENOTEMPTY'])
190
191/** Bounded backoff for {@link removeDirWithRetry}: 10 attempts, ~2.75s total. */
192const REMOVE_MAX_ATTEMPTS = 10
193const REMOVE_RETRY_DELAY_MS = 50
194
195/** How long {@link LocalProcessHandle.destroy} waits for a killed child to exit. */
196const CHILD_EXIT_TIMEOUT_MS = 5_000
197
198/**
199 * `rm -rf` a directory, retrying while the OS still reports it busy.
200 *
201 * Killing a process is not the same as the OS having released what it held —
202 * the same "verify, don't assume" gap {@link killTree} closes for the process
203 * tree. Even after the child is confirmed gone, Windows can take a few more
204 * milliseconds to drop its CWD handle, so a bounded retry is the only way
205 * through the residual race.
206 *
207 * A busy path that NEVER releases is worth knowing about, so a persistent
208 * failure is reported through the logger seam rather than swallowed. It is not
209 * thrown: `destroy` is a teardown path, and wedging a caller's cleanup over an
210 * undeletable temp dir is worse than a warning. Any NON-busy error (a genuinely
211 * broken removal) still throws, as it always did.
212 *
213 * Exported for tests: the retry is the half of the fix that survives a child
214 * outliving our kill.
215 */
216export async function removeDirWithRetry(
217 dir: string,
218 logger?: LocalProcessLogger,
219): Promise<void> {
220 let lastError: unknown
221 for (let attempt = 1; attempt <= REMOVE_MAX_ATTEMPTS; attempt += 1) {
222 try {
223 await fsp.rm(dir, { recursive: true, force: true })
224 return
225 } catch (error) {
226 const code = (error as NodeJS.ErrnoException).code
227 if (code === undefined || !BUSY_ERROR_CODES.has(code)) throw error
228 lastError = error
229 if (attempt < REMOVE_MAX_ATTEMPTS) {
230 await delay(REMOVE_RETRY_DELAY_MS * attempt)
231 }
232 }
233 }
234 logger?.warn('local-process: could not remove the sandbox dir; still busy', {
235 dir,
236 attempts: REMOVE_MAX_ATTEMPTS,
237 error: lastError instanceof Error ? lastError.message : String(lastError),
238 })
239}
240
241/**
242 * Resolve once `child` has actually exited, or `false` if it is still running
243 * after `timeoutMs`. A `kill` only *requests* termination; the child holds its
244 * CWD until it is really gone, so teardown must confirm rather than assume.
245 */
246function waitForExit(child: ChildProcess, timeoutMs: number): Promise<boolean> {
247 if (child.exitCode !== null || child.signalCode !== null) {
248 return Promise.resolve(true)
249 }
250 return new Promise<boolean>((resolve) => {
251 const onExit = (): void => resolve(true)
252 child.once('exit', onExit)
253 // `unref` so a child that exits promptly does not hold the event loop open
254 // for the rest of the timeout. Promise resolution is once-only, so whichever
255 // of the two paths fires first wins and the other becomes a no-op.
256 setTimeout(() => {
257 child.off('exit', onExit)
258 resolve(false)
259 }, timeoutMs).unref()
260 })
261}
262
263/** One row of MSYS `ps`: the MSYS-side pid table, keyed to Windows by `winpid`. */
264interface MsysProcess {
265 pid: number
266 ppid: number
267 winpid: number
268}
269
270/**
271 * Parse MSYS/git-bash `ps` output. Columns are
272 * `PID PPID PGID WINPID TTY UID STIME COMMAND`; the header and any
273 * non-numeric row are skipped, as is any row with a `PPID` of `0` — that is how
274 * `ps -W` renders the native Windows processes it appends, and they are not part
275 * of any MSYS tree. (We call plain `ps`; the filter keeps a stray `-W` from ever
276 * widening the sweep.) Every genuine MSYS row has a `PPID` of at least `1`.
277 *
278 * Exported for tests — parsing fixed text is the portable half of the
279 * orphan-sweep logic.
280 */
281export function parseMsysProcessTable(stdout: string): Array<MsysProcess> {
282 const rows: Array<MsysProcess> = []
283 for (const line of stdout.split('\n')) {
284 const cols = line.trim().split(/\s+/)
285 if (cols.length < 4) continue
286 const pid = Number(cols[0])
287 const ppid = Number(cols[1])
288 const winpid = Number(cols[3])
289 if (
290 !Number.isInteger(pid) ||
291 !Number.isInteger(ppid) ||
292 !Number.isInteger(winpid) ||
293 pid <= 0 ||
294 ppid <= 0 ||
295 winpid <= 0
296 ) {
297 continue
298 }
299 rows.push({ pid, ppid, winpid })
300 }
301 return rows
302}
303
304/**
305 * Windows pids of every MSYS descendant of the process whose Windows pid is
306 * `rootWinPid`, excluding the root itself. Returns `[]` when the root is not an
307 * MSYS process (nothing to sweep beyond what `taskkill /T` already covers).
308 *
309 * Exported for tests alongside {@link parseMsysProcessTable}.
310 */
311export function msysDescendantWinPids(
312 rows: Array<MsysProcess>,
313 rootWinPid: number,
314): Array<number> {
315 const root = rows.find((r) => r.winpid === rootWinPid)
316 if (!root) return []
317 const byPpid = new Map<number, Array<MsysProcess>>()
318 for (const row of rows) {
319 const siblings = byPpid.get(row.ppid)
320 if (siblings) siblings.push(row)
321 else byPpid.set(row.ppid, [row])
322 }
323 const winPids: Array<number> = []
324 const seen = new Set<number>([root.pid])
325 const queue = [root.pid]
326 while (queue.length > 0) {
327 // Non-null: `queue.length > 0` was just checked, and nothing else shifts it.
328 const next = queue.shift() ?? 0
329 for (const child of byPpid.get(next) ?? []) {
330 if (seen.has(child.pid)) continue // cycle guard
331 seen.add(child.pid)
332 queue.push(child.pid)
333 if (child.winpid !== rootWinPid) winPids.push(child.winpid)
334 }
335 }
336 return winPids
337}
338
339/** Snapshot the MSYS process table via the resolved POSIX `sh`. `[]` if unavailable. */
340function msysProcessTable(logger?: LocalProcessLogger): Array<MsysProcess> {
341 const res = spawnSync(posixShell(), ['-c', 'ps'], {
342 encoding: 'utf8',
343 env: prependShellPath({ ...process.env }),
344 })
345 if (res.error !== undefined || res.status !== 0) {
346 logger?.warn('local-process: could not snapshot the MSYS process table', {
347 error: res.error?.message,
348 status: res.status,
349 })
350 return []
351 }
352 return parseMsysProcessTable(res.stdout)
353}
354
355/** Whether `pid` is still running. `process.kill(pid, 0)` sends no signal. */
356function isAlive(pid: number): boolean {
357 try {
358 process.kill(pid, 0)
359 return true
360 } catch {
361 return false
362 }
363}
364
365/**
366 * What a finished `taskkill` invocation actually means.
367 *
368 * - `killed` — it exited `0`; the pid it was given is gone.
369 * - `already-exited` — the process was gone before we asked. This is SUCCESS:
370 * nothing leaked, and retrying or reporting it would make every normal
371 * teardown look like a failure. taskkill says this three different ways, all
372 * of which must be recognized (see {@link ALREADY_EXITED_STDERR}).
373 * - `failed` — any other nonzero status: a real refusal (access denied, a
374 * protected process). Worth reporting.
375 *
376 * Exported for tests: `spawnSync` reporting no `error` only means taskkill was
377 * *launched*, and conflating "I successfully asked" with "it died" is exactly the
378 * bug this file used to have.
379 */
380export type TaskkillOutcome = 'killed' | 'already-exited' | 'failed'
381
382/**
383 * taskkill wordings that all mean "it was already gone".
384 *
385 * Status `128` with `The process "<pid>" not found.` is the overwhelmingly
386 * common one (verified against a pid whose process had already exited). The
387 * others come out of `/T`, which reports per tree member and can hit a child
388 * that exits mid-walk:
389 *
390 * - `… could not be terminated. Reason: There is no running instance of the
391 * task.` — status `1`, matching NEITHER of the two wordings this regex
392 * originally covered, so it was classified `failed` and logged a warning on
393 * what is a completely normal teardown. That misclassification is the known
394 * suspect for the intermittent single-warning failure of the
395 * "a normal kill neither throws nor reports a failure" case below.
396 * - `does not exist` — the older wording.
397 *
398 * A refusal (`Access is denied.`, `This is critical system process.`) must NOT
399 * match: those mean the process is still running and the caller has leaked it.
400 */
401const ALREADY_EXITED_STDERR =
402 /not found|does not exist|no running instance of the task/i
403
404export function classifyTaskkillResult(
405 status: number | null,
406 stderr: string,
407): TaskkillOutcome {
408 if (status === 0) return 'killed'
409 if (status === 128 || ALREADY_EXITED_STDERR.test(stderr)) {
410 return 'already-exited'
411 }
412 return 'failed'
413}
414
415/**
416 * `taskkill` one pid. Returns whether the process is gone afterwards.
417 *
418 * Exported for tests alongside {@link classifyTaskkillResult}: the classifier
419 * can be unit-tested on fixed strings, but only driving the real binary proves
420 * the warning channel actually fires — and that the raw stderr reaches the log,
421 * without which an intermittent misclassification is undiagnosable.
422 */
423export function taskkillPid(
424 pid: number,
425 tree: boolean,
426 logger?: LocalProcessLogger,
427): boolean {
428 const args = ['/PID', String(pid), ...(tree ? ['/T'] : []), '/F']
429 const res = spawnSync('taskkill', args, { encoding: 'utf8' })
430 if (res.error !== undefined) {
431 logger?.warn('local-process: taskkill could not be launched', {
432 pid,
433 error: res.error.message,
434 })
435 return false
436 }
437 const outcome = classifyTaskkillResult(res.status, res.stderr ?? '')
438 if (outcome === 'failed') {
439 logger?.warn('local-process: taskkill failed to kill a process', {
440 pid,
441 status: res.status,
442 stderr: (res.stderr ?? '').trim(),
443 })
444 return false
445 }
446 return true
447}
448
449/**
450 * Kill a spawned child AND all its descendants.
451 *
452 * We spawn every command through `sh -c <command>`, so `child` is the `sh`
453 * wrapper. `child.kill()` signals only that wrapper — its grandchildren (e.g.
454 * `node` → a harness binary like `opencode serve`) keep running and hold their
455 * ports, orphaning a server that then blocks the next run's port.
456 *
457 * ON POSIX we signal the process GROUP (`process.kill(-pid, …)`), which is why
458 * `spawn` passes `detached: true` (see {@link spawnDetached}) to make the
459 * wrapper its own group leader. Signalling the bare wrapper is NOT enough, and
460 * the comment that used to sit here — "sh forwards on exec" — was wrong: `sh -c
461 * '<cmd>'` does not reliably exec its command. Measured on Linux (node:22,
462 * `/bin/sh` → dash): `sh -c 'sleep 987654321'` shows BOTH `sh` and `sleep` in
463 * `ps`, and `child.kill('SIGKILL')` leaves `sleep` running. That is the POSIX
464 * twin of the Windows `tail.exe` leak below, and it made
465 * `killableProcesses: true` false on every platform.
466 *
467 * ON WINDOWS there are no process groups, so we walk the tree with
468 * `taskkill /T` and then sweep what `/T` cannot reach.
469 *
470 * WHY `taskkill /T` IS NOT ENOUGH (measured, git-bash `sh` on Windows 11). For a
471 * multi-statement command — e.g. `journalFollowCommand`'s
472 * `mkdir -p …; : >> …; tail -c +1 -f …` — MSYS's fork emulation runs the final
473 * `tail` under an intermediate `sh.exe` that then exits. Windows does not
474 * reparent, so `tail.exe`'s `ParentProcessId` stays pointing at that dead pid and
475 * `taskkill /T` — which walks only LIVE parent links from the pid it is given —
476 * never reaches it. Worse, taskkill still exits `0` ("SUCCESS: … PID <sh> has
477 * been terminated"), so checking the exit status alone does not catch this: the
478 * shipped journal conformance suite leaked 2 `tail.exe` per run, accumulating
479 * for the life of the machine.
480 *
481 * MSYS's own pid table does keep the logical parentage (`ps` reports `tail`'s
482 * PPID as our `sh`), so we snapshot it, resolve the descendants' Windows pids,
483 * and kill the survivors directly. The snapshot MUST be taken BEFORE the
484 * `taskkill`: once our `sh` is gone, its `winpid` is no longer in the table and
485 * the attribution is lost.
486 *
487 * TOTAL BY CONSTRUCTION: every failure is logged, never thrown. Callers are
488 * teardown paths (`SpawnHandle.kill`, `signal` abort handlers, `pipeToRunLog`)
489 * where a throw would wedge a run at `'running'` with its tailers parked.
490 */
491function killTree(
492 child: ChildProcess,
493 signal?: NodeJS.Signals | number,
494 logger?: LocalProcessLogger,
495 /**
496 * A process table already snapshotted by the caller, for tearing down several
497 * children at once. `msysProcessTable` costs a full `sh -c ps` spawn, so
498 * taking it once per teardown instead of once per child keeps `destroy` from
499 * blowing a caller's test timeout. It must still have been taken BEFORE any
500 * `taskkill` in the batch — which is exactly what one up-front snapshot gives.
501 */
502 rows?: Array<MsysProcess>,
503): void {
504 const pid = child.pid
505 if (pid === undefined) return
506 if (process.platform !== 'win32') {
507 try {
508 // Negative pid = "the whole group", reaching the descendants that
509 // signalling `pid` alone would orphan.
510 process.kill(-pid, signal ?? 'SIGTERM')
511 } catch (error) {
512 // ESRCH means the group is already gone — the ordinary "it exited on its
513 // own" teardown, not a failure, and must stay silent (see the
514 // already-exited reasoning on `classifyTaskkillResult`). Anything else and
515 // we still try the wrapper alone: worse than a group kill, better than
516 // giving up.
517 if ((error as NodeJS.ErrnoException).code !== 'ESRCH') {
518 logger?.warn('local-process: could not signal the process group', {
519 pid,
520 error: error instanceof Error ? error.message : String(error),
521 })
522 child.kill(signal)
523 }
524 }
525 return
526 }
527
528 // Attribute the tree first — taskkill destroys the evidence (see above).
529 const strays = msysDescendantWinPids(rows ?? msysProcessTable(logger), pid)
530
531 if (!taskkillPid(pid, true, logger)) {
532 // taskkill unusable or refused → best-effort signal, as before.
533 child.kill(signal)
534 }
535
536 // Verify and escalate: anything `/T` could not reach gets killed directly.
537 const survivors = strays.filter((strayPid) => isAlive(strayPid))
538 for (const strayPid of survivors) taskkillPid(strayPid, true, logger)
539
540 const leaked = survivors.filter((strayPid) => isAlive(strayPid))
541 if (leaked.length > 0) {
542 logger?.warn('local-process: killTree left descendants running', {
543 pid,
544 leaked,
545 })
546 }
547}
548
549/**
550 * `spawn` options that make {@link killTree}'s POSIX branch able to do its job.
551 *
552 * `detached: true` puts the `sh` wrapper in its own process group, so
553 * `process.kill(-pid, …)` reaches the command and its descendants. Without it
554 * the wrapper shares OUR group and the negative pid would signal the test
555 * runner / host process itself — so this flag and that kill are a single
556 * mechanism and must not be separated.
557 *
558 * WINDOWS IS DELIBERATELY EXCLUDED: `detached` there means "give the child its
559 * own console", which can flash a console window, and the Windows branch of
560 * `killTree` uses `taskkill /T` instead and has no use for a group.
561 *
562 * ACCEPTED TRADE-OFF ON POSIX — the children no longer die with a host Ctrl-C.
563 * A terminal delivers `SIGINT` to the FOREGROUND PROCESS GROUP, so while the
564 * wrapper shared our group it was interrupted alongside the host. Its own group
565 * is outside that delivery set, and Ctrl-C on e.g. a `pnpm dev` running this
566 * provider now kills the host and leaves the agent tree behind. This is the
567 * price of being able to kill the tree deliberately, and the deliberate path is
568 * strictly more reliable than the incidental one it replaces (the incidental
569 * `SIGINT` never reached a non-interactive host, nor a `kill` from a script, and
570 * a wrapper that ignored `SIGINT` shrugged it off entirely). Hosts that want the
571 * old ergonomics must own it explicitly: install a `SIGINT`/`SIGTERM` handler
572 * and `await handle.destroy()` (or `killTree` via `SpawnHandle.kill`) from it —
573 * which is what `withSandbox`'s `onAbort` already does.
574 */
575const spawnDetached = process.platform !== 'win32'
576
577export interface LocalProcessHandleOptions {
578 /** Real host directory backing this sandbox (its workspace root). */
579 root: string
580 /** Remove the backing dir on destroy. */
581 removeOnDestroy: boolean
582 /** Create a fork by copying this sandbox's dir to a new root. */
583 forkFactory: (sourceRoot: string) => Promise<SandboxHandle>
584 /** Env vars to delete from the inherited `process.env` before spawning. */
585 scrubEnv?: Array<string>
586 /**
587 * Sink for non-fatal teardown diagnostics — currently a `killTree` that could
588 * not confirm the process tree is gone. Teardown never throws, so without a
589 * logger these conditions are silent.
590 */
591 logger?: LocalProcessLogger
592}
593
594export class LocalProcessHandle implements SandboxHandle {
595 readonly id: string
596 readonly provider = 'local-process'
597 readonly capabilities = LOCAL_PROCESS_CAPS
598 readonly fs: SandboxHandle['fs']
599 readonly git: SandboxHandle['git']
600 readonly process: SandboxHandle['process']
601 readonly ports: SandboxHandle['ports']
602 readonly env: SandboxHandle['env']
603
604 private readonly root: string
605 private readonly options: LocalProcessHandleOptions
606 private readonly envVars: Record<string, string> = {}
607 /**
608 * Every child we spawned that has not yet exited. `destroy` needs this to
609 * kill and then CONFIRM the tree is gone before removing the backing dir —
610 * each child's CWD is that dir, and on Windows an open CWD makes the removal
611 * fail with `EBUSY`. Entries are dropped on `close`, so this stays bounded.
612 */
613 private readonly liveChildren = new Set<ChildProcess>()
614
615 constructor(options: LocalProcessHandleOptions) {
616 this.root = options.root
617 this.id = options.root
618 this.options = options
619
620 this.fs = {
621 read: async (p) => fsp.readFile(this.resolve(p), 'utf8'),
622 readBytes: async (p) =>
623 new Uint8Array(await fsp.readFile(this.resolve(p))),
624 write: async (p, data) => {
625 const target = this.resolve(p)
626 await fsp.mkdir(path.dirname(target), { recursive: true })
627 await fsp.writeFile(
628 target,
629 typeof data === 'string' ? data : Buffer.from(data),
630 )
631 },
632 list: async (p) => {
633 const entries = await fsp.readdir(this.resolve(p), {
634 withFileTypes: true,
635 })
636 return entries.map((e) => ({
637 name: e.name,
638 path: `${p.replace(/\/$/, '')}/${e.name}`,
639 type: e.isDirectory() ? ('dir' as const) : ('file' as const),
640 }))
641 },
642 lstat: async (p) => {
643 let stat: Awaited<ReturnType<typeof fsp.lstat>>
644 try {
645 stat = await fsp.lstat(this.resolve(p))
646 } catch (error) {
647 if (
648 error !== null &&
649 typeof error === 'object' &&
650 'code' in error &&
651 error.code === 'ENOENT'
652 )
653 return undefined
654 throw error
655 }
656 const type = stat.isFile()
657 ? 'file'
658 : stat.isDirectory()
659 ? 'dir'
660 : stat.isSymbolicLink()
661 ? 'symlink'
662 : 'other'
663 return type === 'file'
664 ? { type, mode: stat.mode, size: stat.size }
665 : { type, mode: stat.mode }
666 },
667 mkdir: async (p) => {
668 await fsp.mkdir(this.resolve(p), { recursive: true })
669 },
670 remove: async (p) => {
671 await fsp.rm(this.resolve(p), { recursive: true, force: true })
672 },
673 rename: async (from, to) => {
674 await fsp.rename(this.resolve(from), this.resolve(to))
675 },
676 exists: async (p) => {
677 try {
678 await fsp.access(this.resolve(p))
679 return true
680 } catch {
681 return false
682 }
683 },
684 }
685
686 // Native recursive file watching is supported on Windows/macOS but not
687 // Linux (Node throws ERR_FEATURE_UNAVAILABLE_ON_PLATFORM). Expose the
688 // optional `fs.watch` seam only where it works; on Linux it stays
689 // undefined so `watchWorkspace` falls back to the portable exec-poll path.
690 if (process.platform !== 'linux') {
691 this.fs.watch = (p, onEvent) => {
692 const dir = this.resolve(p)
693 // Emit paths under the requested watch root `p` (not a hardcoded
694 // `/workspace`), so callers watching a sub-path get consistent paths.
695 const base = p.replace(/\/+$/, '')
696 const watcher = watchFs(
697 dir,
698 { recursive: true },
699 (eventType, filename) => {
700 if (filename === null) return
701 const rel = filename.toString().split(path.sep).join('/')
702 onEvent({ type: eventType, path: `${base}/${rel}` })
703 },
704 )
705 return Promise.resolve({
706 stop: () => {
707 watcher.close()
708 return Promise.resolve()
709 },
710 })
711 }
712 }
713
714 this.process = {
715 exec: (command, opts) => this.exec(command, opts),
716 spawn: (command, opts) => this.spawnProcess(command, opts),
717 }
718
719 this.git = createExecBackedGit(this.process, this.root)
720
721 this.ports = {
722 // The host can always reach the process directly on localhost.
723 connect: (port) => Promise.resolve({ url: `http://127.0.0.1:${port}` }),
724 }
725
726 this.env = {
727 set: (vars) => {
728 Object.assign(this.envVars, vars)
729 return Promise.resolve()
730 },
731 }
732 }
733
734 /** Map a virtual `/workspace` (or other absolute/relative) path onto the host root. */
735 private resolve(p: string): string {
736 let rel: string
737 if (p === DEFAULT_WORKSPACE_ROOT) rel = ''
738 else if (p.startsWith(`${DEFAULT_WORKSPACE_ROOT}/`)) {
739 rel = p.slice(DEFAULT_WORKSPACE_ROOT.length + 1)
740 } else if (p.startsWith('/')) rel = p.slice(1)
741 else rel = p
742 const resolved = path.resolve(this.root, rel)
743 // Containment: never let an agent's path escape the sandbox dir.
744 const rootWithSep = this.root.endsWith(path.sep)
745 ? this.root
746 : this.root + path.sep
747 if (resolved !== this.root && !resolved.startsWith(rootWithSep)) {
748 throw new Error(
749 `local-process: path "${p}" resolves outside the sandbox root "${this.root}".`,
750 )
751 }
752 return resolved
753 }
754
755 private resolveCwd(cwd: string | undefined): string {
756 return cwd ? this.resolve(cwd) : this.root
757 }
758
759 /**
760 * Remember a freshly spawned child until it exits, so `destroy` can tear it
761 * down first. `close` (not `exit`) is the drop point: it fires once the stdio
762 * streams are done too, and a still-draining pipe is another handle on the
763 * dir.
764 */
765 private track(child: ChildProcess): void {
766 this.liveChildren.add(child)
767 child.once('close', () => this.liveChildren.delete(child))
768 }
769
770 /**
771 * Kill every child we spawned and wait for the OS to confirm each is gone.
772 * Only then may the backing dir be removed — the child's CWD *is* that dir.
773 * A child that outlives the wait is logged, not thrown: teardown is total by
774 * construction, and {@link removeDirWithRetry} still gets its chance.
775 */
776 private async terminateChildren(): Promise<void> {
777 const children = [...this.liveChildren]
778 this.liveChildren.clear()
779 const live = children.filter(
780 (child) => child.exitCode === null && child.signalCode === null,
781 )
782 if (live.length === 0) return
783 // ONE process-table snapshot for the whole batch, taken before any kill.
784 // The snapshot is not free — measured on Windows 11, `sh -c ps` costs
785 // ~1.9s and `taskkill /T` another ~1.9-3.0s, so a teardown that must
786 // actually kill a live child costs seconds. Taking the snapshot once per
787 // teardown rather than once per child is what keeps that from multiplying.
788 // It cannot be skipped: `taskkill /T` alone cannot reach an MSYS stray
789 // (see `killTree`), and such a stray holds files INSIDE the dir we are
790 // about to remove.
791 const rows =
792 process.platform === 'win32'
793 ? msysProcessTable(this.options.logger)
794 : undefined
795 for (const child of live) {
796 killTree(child, undefined, this.options.logger, rows)
797 }
798 const exited = await Promise.all(
799 live.map((child) => waitForExit(child, CHILD_EXIT_TIMEOUT_MS)),
800 )
801
802 // ESCALATE to SIGKILL on POSIX for anything that survived the first signal.
803 // `killTree` sends `signal ?? 'SIGTERM'` exactly once, which a child may
804 // ignore or block — and `LOCAL_PROCESS_CAPS.killableProcesses: true` promises
805 // forcible termination, not a polite request. The Windows branch already
806 // escalates (`taskkill /F`, then per-stray) and the Docker handle escalates to
807 // SIGKILL unconditionally, so without this POSIX is the weak half of one
808 // contract. It matters beyond the promise: a survivor keeps its CWD handle on
809 // the very directory `removeDirWithRetry` is about to delete.
810 //
811 // Escalation lives HERE and not in `killTree` on purpose, so an explicit
812 // `SpawnHandle.kill('SIGTERM')` keeps its single-signal meaning for callers
813 // who chose that signal deliberately. Only teardown, which must be total,
814 // upgrades.
815 const survivors = live.filter((_, i) => exited[i] === false)
816 if (survivors.length > 0 && process.platform !== 'win32') {
817 for (const child of survivors) {
818 killTree(child, 'SIGKILL', this.options.logger)
819 }
820 const killedAfterEscalation = await Promise.all(
821 survivors.map((child) => waitForExit(child, CHILD_EXIT_TIMEOUT_MS)),
822 )
823 const leaked = survivors
824 .filter((_, i) => killedAfterEscalation[i] === false)
825 .map((child) => child.pid)
826 if (leaked.length > 0) {
827 this.options.logger?.warn(
828 'local-process: children survived SIGKILL; teardown continues',
829 { root: this.root, pids: leaked },
830 )
831 }
832 return
833 }
834
835 const stragglers = survivors.map((child) => child.pid)
836 if (stragglers.length > 0) {
837 this.options.logger?.warn(
838 'local-process: children still running after kill; teardown continues',
839 { root: this.root, pids: stragglers },
840 )
841 }
842 }
843
844 private mergedEnv(extra?: Record<string, string>): NodeJS.ProcessEnv {
845 const env: NodeJS.ProcessEnv = { ...process.env, ...this.envVars, ...extra }
846 // Drop scrubbed vars so a host CLI falls back to its own stored auth
847 // (e.g. remove ANTHROPIC_API_KEY → Claude Code uses the logged-in
848 // subscription instead of billing the API). Delete (not blank) so the var
849 // is truly absent, not present-but-empty.
850 for (const key of this.options.scrubEnv ?? []) delete env[key]
851 // Prepend git-bash's tool dirs (Windows) so the POSIX `sh` can find sed/uname/
852 // git/etc. that npm CLI shims depend on.
853 return prependShellPath(env)
854 }
855
856 private exec(command: string, opts?: ProcessOptions): Promise<ExecResult> {
857 return new Promise<ExecResult>((resolve, reject) => {
858 // Run via a POSIX `sh` on every platform (see posixShell) so the adapter's
859 // single-quote-quoted commands work identically — including native Windows,
860 // where `shell: true` would be cmd.exe and mangle the quoting.
861 const child = spawn(posixShell(), ['-c', command], {
862 cwd: this.resolveCwd(opts?.cwd),
863 env: this.mergedEnv(opts?.env),
864 detached: spawnDetached,
865 })
866 this.track(child)
867 let stdout = ''
868 let stderr = ''
869 child.stdout.on('data', (d: Buffer) => (stdout += d.toString('utf8')))
870 child.stderr.on('data', (d: Buffer) => (stderr += d.toString('utf8')))
871 const onAbort = (): void => {
872 killTree(child, undefined, this.options.logger)
873 }
874 opts?.signal?.addEventListener('abort', onAbort, { once: true })
875 child.on('error', reject)
876 child.on('close', (code) => {
877 opts?.signal?.removeEventListener('abort', onAbort)
878 resolve({ stdout, stderr, exitCode: code ?? 0 })
879 })
880 })
881 }
882
883 private spawnProcess(
884 command: string,
885 opts?: ProcessOptions,
886 ): Promise<SpawnHandle> {
887 // Via POSIX `sh` on every platform (see posixShell / exec above).
888 const child = spawn(posixShell(), ['-c', command], {
889 cwd: this.resolveCwd(opts?.cwd),
890 env: this.mergedEnv(opts?.env),
891 detached: spawnDetached,
892 })
893 this.track(child)
894 // Node reports a failed write twice: to the `write` callback below, and
895 // as an `error` event on this socket. An unhandled `error` event throws
896 // and stops the host process. `stdin.write` still rejects with the same
897 // error.
898 child.stdin.on('error', () => {})
899 if (opts?.signal) {
900 opts.signal.addEventListener(
901 'abort',
902 () => killTree(child, undefined, this.options.logger),
903 {
904 once: true,
905 },
906 )
907 }
908 const closed = new Promise<number>((resolve, reject) => {
909 child.once('error', reject)
910 child.once('close', (code) => resolve(code ?? 0))
911 })
912 // The child can close while stdout is still being drained. Keep the
913 // rejection handled until the caller asks for the result via wait().
914 closed.catch(() => {})
915 const handle: SpawnHandle = {
916 pid: child.pid ?? -1,
917 stdout: decodeStream(child.stdout),
918 stderr: decodeStream(child.stderr),
919 stdin: {
920 write: (data) =>
921 new Promise<void>((resolve, reject) => {
922 child.stdin.write(data, (err) => (err ? reject(err) : resolve()))
923 }),
924 end: () =>
925 new Promise<void>((resolve) => {
926 child.stdin.end(() => resolve())
927 }),
928 },
929 wait: () => closed,
930 kill: (signal) => {
931 killTree(child, signal, this.options.logger)
932 return Promise.resolve()
933 },
934 }
935 return Promise.resolve(handle)
936 }
937
938 // local-process has no snapshot primitive; fork copies the dir instead.
939 snapshot = undefined
940
941 fork = (): Promise<SandboxHandle> => {
942 if (!this.capabilities.fork) {
943 throw new UnsupportedCapabilityError('local-process', 'fork')
944 }
945 return this.options.forkFactory(this.root)
946 }
947
948 /**
949 * Tear the sandbox down: kill the process tree we own, then (only if the dir
950 * is ours) remove it.
951 *
952 * THE KILL IS UNCONDITIONAL, and must stay that way. `removeOnDestroy` is a
953 * statement about the DIRECTORY — "this root is mine to delete" — and says
954 * nothing about the processes. Gating {@link terminateChildren} behind it made
955 * `destroy()` return immediately for the natural configuration of an app
956 * pointed at its own checkout (`dir` set ⇒ `removeOnDestroy` defaults false),
957 * leaving the whole spawned tree alive and holding its ports. Closing an IO
958 * stream does not kill an in-sandbox process — that premise is stated
959 * explicitly by `withSandbox`'s `onAbort` — so `terminateChildren` IS the only
960 * thing that ends them, and it is exactly the leak the `killTree` work exists
961 * to close.
962 *
963 * When the backing dir IS ours to remove, the children must additionally go
964 * first and their exit MUST be confirmed: their CWD is that dir, and a `rm`
965 * that races the OS releasing the handle fails with `EBUSY` on Windows. That
966 * race was observable — `ai-acp` and `ai-grok-build` both lost tests per run
967 * to `EBUSY … rmdir` — and it is the same failure shape as the `killTree`
968 * work: a teardown that returned before the OS had caught up.
969 *
970 * COST, measured on Windows 11 and deliberately accepted: when a child really
971 * is still alive this takes SECONDS (`sh -c ps` ~1.9s plus `taskkill /T`
972 * ~1.9-3.0s), because `taskkill /T` is the only thing that reaches a native
973 * grandchild — MSYS `ps` does not even list one. When every child has already
974 * exited — the common case, since `close` drops them from `liveChildren` — the
975 * kill is skipped entirely and this costs ~1ms. A caller that destroys a
976 * sandbox whose agent is STILL RUNNING inside a tight per-test timeout will
977 * feel those seconds, and `@tanstack/ai-acp`'s 5s-budget stdio tests do. The
978 * alternatives are worse: the `EBUSY` rejection this removes, plus a leaked
979 * process tree that outlives the run.
980 */
981 async destroy(): Promise<void> {
982 await this.terminateChildren()
983 if (!this.options.removeOnDestroy) return
984 await removeDirWithRetry(this.root, this.options.logger)
985 }
986}