Open History to see the last commit
1/**
2 * SandboxHandle backed by a Docker container (via dockerode). Real isolation:
3 * fs/exec/git operate inside the container; paths are real container paths
4 * (default workdir `/workspace`).
5 *
6 * fs is implemented over `exec` with chunked base64 piping (binary-safe, no
7 * tar dependency). Large writes are split so no single `sh -c` argument hits
8 * Linux `MAX_ARG_STRLEN`. The container image must provide `sh`, `base64`, and
9 * coreutils (true for node:* / debian-based images).
10 */
11import { randomUUID } from 'node:crypto'
12import { PassThrough, Writable } from 'node:stream'
13import {
14 UnsupportedCapabilityError,
15 createExecBackedGit,
16} from '@tanstack/ai-sandbox'
17import { fsWriteCommands } from './fs-write'
18import type Dockerode from 'dockerode'
19import type { Readable } from 'node:stream'
20import type {
21 ExecResult,
22 ProcessOptions,
23 SandboxCapabilities,
24 SandboxChannel,
25 SandboxHandle,
26 SnapshotRef,
27 SpawnHandle,
28 SandboxFsStat,
29} from '@tanstack/ai-sandbox'
30
31export const DOCKER_CAPS: SandboxCapabilities = {
32 fs: true,
33 exec: true,
34 env: true,
35 ports: true,
36 backgroundProcesses: true,
37 // Docker's exec runs over a single hijacked duplex stream; signalling stdin
38 // EOF (`stream.end()`) also tears down stdout, so a process fed its prompt
39 // over stdin loses its streamed output. Declare stdin non-writable so adapters
40 // use the file-redirect path (`cmd < promptfile`) instead — reliable here.
41 writableStdin: false,
42 // `spawnProcess.kill()` and `signal` abort signal the container-side process
43 // INSIDE the container, by the pid it recorded for itself on startup (see
44 // `pidRecordingCommand`), and only then destroy the hijacked exec stream —
45 // so a spawned process is genuinely, forcibly terminable.
46 //
47 // Destroying the stream is NOT sufficient on its own and must never be the
48 // whole story here: it detaches the client from the exec session while Docker
49 // leaves the exec's process running (measured — a `sleep` spawned through
50 // this handle survived `kill()` and was still in the container's `ps` until
51 // the container itself was removed). That is precisely the orphan leak this
52 // capability promises callers is impossible, and `journal-reader` reads it to
53 // choose its `'follow'` (killable) vs `'poll'` strategy.
54 //
55 // WHY `true` IS EARNED HERE, when the same audit flipped Vercel and Daytona
56 // to `false`. Those two could not distinguish a refused kill from a successful
57 // one, so their `true` was a claim no observation could contradict. This one
58 // is falsifiable in three independent ways, and each is exercised by a test:
59 // 1. `kill()` AWAITS the in-container kill, so its resolution means the
60 // container was asked and answered — not that a request was queued.
61 // 2. `killRecordedPidCommand` VERIFIES with `kill -0` after escalating to
62 // `SIGKILL` and prints a marker on stderr when the process is still
63 // there; `killRecordedPid` turns that into a `logger.warn`. A kill this
64 // handle could not perform is therefore reported, not assumed.
65 // 3. `docker.test.ts` asks the container's own `ps` whether the probe is
66 // gone — evidence from the kernel, not from this constant.
67 // Point 2 only counts while the channel STAYS QUIET on healthy teardowns. It
68 // did not: `followJournal` kills in a `finally` on every exit path, so once the
69 // pid file was removed on clean exit, "absent" meant both "not written yet" and
70 // "the owner exited and we cleaned up" — and every ordinary teardown warned
71 // about an orphan that did not exist (and blocked ~2s doing so). A warning that
72 // fires when nothing is wrong is not evidence of anything, so the handle now
73 // tracks WHICH of the two happened (`PidFileState`) instead of guessing from
74 // the file. `docker.test.ts` pins both directions: silence after a clean exit,
75 // and a warning — with the survivor still in `ps` — after a real refusal.
76 //
77 // If the pid was never recorded (the process died before its `echo $$`, or the
78 // exec never started) that too is reported, via `KILL_NO_PID_MARKER`. The
79 // residual gap is honest and narrow: a kill can still be refused, and then
80 // this flag is optimistic — but the refusal is visible in the log rather than
81 // silent, which is exactly the property the other two providers lacked.
82 killableProcesses: true,
83 snapshots: true,
84 networkPolicy: false,
85 durableFilesystem: true, // container fs persists across stop/start (not removal)
86 fork: true,
87}
88
89/**
90 * Sink for non-fatal teardown diagnostics — currently a kill the container
91 * refused or could not confirm. Structurally identical to
92 * `ai-sandbox-local-process`'s `LocalProcessLogger` and satisfied as-is by
93 * `@tanstack/ai`'s `InternalLogger`, so a consumer can pass the logger it
94 * already has without this package depending on it.
95 */
96export interface DockerLogger {
97 warn: (message: string, meta?: Record<string, unknown>) => void
98}
99
100/** POSIX single-quote escape for embedding paths in `sh -c`. */
101function q(value: string): string {
102 return `'${value.replace(/'/g, `'\\''`)}'`
103}
104const LSTAT_MISSING = '__TANSTACK_LSTAT_MISSING__'
105
106/** Verify a missing path by listing parent entries. `test -e` also fails for inaccessible parents. */
107function lstatCommand(path: string): string {
108 return `tanstack_lstat_path=${q(path)}; tanstack_lstat_output=$(stat -c '%f:%s' -- "$tanstack_lstat_path" 2>&1); tanstack_lstat_status=$?; if [ "$tanstack_lstat_status" -eq 0 ]; then printf '%s\n' "$tanstack_lstat_output"; else tanstack_lstat_missing() { tanstack_missing_path=$1; case "$tanstack_missing_path" in /|.) return 1 ;; */*) tanstack_parent=${'$'}{tanstack_missing_path%/*}; tanstack_name=${'$'}{tanstack_missing_path##*/}; [ -n "$tanstack_parent" ] || tanstack_parent=/ ;; *) tanstack_parent=.; tanstack_name=$tanstack_missing_path ;; esac; tanstack_parent_mode=$(stat -L -c '%f' -- "$tanstack_parent" 2>/dev/null); tanstack_parent_status=$?; if [ "$tanstack_parent_status" -ne 0 ]; then tanstack_lstat_missing "$tanstack_parent"; else case "$tanstack_parent_mode" in 4[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]) case "$tanstack_parent" in /*) tanstack_find_parent=$tanstack_parent ;; *) tanstack_find_parent=./$tanstack_parent ;; esac; tanstack_match=$(find -H "$tanstack_find_parent" -mindepth 1 -maxdepth 1 -exec sh -c 'tanstack_target=$1; shift; for tanstack_candidate do [ "${'$'}{tanstack_candidate##*/}" = "$tanstack_target" ] && { printf 1; exit 0; }; done; exit 0' sh "$tanstack_name" '{}' + 2>/dev/null); tanstack_find_status=$?; [ "$tanstack_find_status" -eq 0 ] && [ -z "$tanstack_match" ] ;; *) return 1 ;; esac; fi; }; if tanstack_lstat_missing "$tanstack_lstat_path"; then printf '%s' '${LSTAT_MISSING}'; else printf '%s\n' "$tanstack_lstat_output" >&2; exit "$tanstack_lstat_status"; fi; fi`
109}
110function parseLstatOutput(output: string): SandboxFsStat {
111 const fields = /^(?<mode>[0-9a-fA-F]{4}):(?<size>\d+)\n?$/.exec(output)
112 const mode = fields?.groups?.mode
113 const size = fields?.groups?.size
114 if (!mode || !size) throw new Error(`invalid lstat output: ${output}`)
115 const parsedMode = Number.parseInt(mode, 16)
116 const parsedSize = Number(size)
117 if (
118 !Number.isSafeInteger(parsedMode) ||
119 !Number.isSafeInteger(parsedSize) ||
120 parsedSize < 0
121 )
122 throw new Error(`invalid lstat output: ${output}`)
123 const type = parsedMode & 0xf000
124 if (type === 0x8000)
125 return { type: 'file', mode: parsedMode, size: parsedSize }
126 if (type === 0x4000) return { type: 'dir', mode: parsedMode }
127 if (type === 0xa000) return { type: 'symlink', mode: parsedMode }
128 return { type: 'other', mode: parsedMode }
129}
130
131/**
132 * Marker the kill shell prints on stderr when it could not signal the process.
133 *
134 * The kill shell must never FAIL (see {@link killRecordedPidCommand}), so its
135 * exit code carries no information — a refusal has to be reported in-band or it
136 * is invisible. This is the token {@link DockerHandle.killRecordedPid} greps for
137 * in order to warn.
138 */
139const KILL_FAILED_MARKER = 'tanstack-sandbox-kill-failed'
140
141/** Marker printed when the pid file never materialised (see the race note). */
142const KILL_NO_PID_MARKER = 'tanstack-sandbox-kill-no-pid'
143
144/**
145 * Wrap `command` so the container-side process records its own pid to
146 * `pidFile` before becoming the command, and removes that file when it exits.
147 *
148 * This is what makes killing possible at all. `stream.destroy()` on the
149 * hijacked exec stream only detaches the CLIENT; the exec's process keeps
150 * running inside the container, and `docker` exposes no "signal this exec" API
151 * (`container.kill` signals PID 1, killing the whole sandbox). The pid the
152 * process reports for itself is the only handle we get on it.
153 *
154 * `exec` matters: without it the recorded pid would be a wrapper shell, and
155 * killing that shell would leave the real command behind — the exact leak shape
156 * this is here to prevent. It is also why the file cannot be cleaned up from
157 * inside: `exec` replaces this shell, so no `trap` of ours can ever run. The
158 * wrapper's owner removes the file from the host instead, on whichever of its
159 * two exits happens — see {@link DockerHandle.removePidFile}.
160 */
161function pidRecordingCommand(command: string, pidFile: string): string {
162 return `echo $$ > ${q(pidFile)}; exec sh -c ${q(command)}`
163}
164
165/**
166 * A `kill -<sig>` argument for a Node signal name or number. Anything
167 * unrecognized degrades to `TERM` rather than interpolating attacker-influenced
168 * text into a shell command.
169 */
170function killSignalArg(signal?: NodeJS.Signals | number): string {
171 if (typeof signal === 'number' && Number.isInteger(signal) && signal > 0) {
172 return String(signal)
173 }
174 if (typeof signal === 'string') {
175 const name = signal.replace(/^SIG/, '')
176 if (/^[A-Z][A-Z0-9]*$/.test(name)) return name
177 }
178 return 'TERM'
179}
180
181/**
182 * How long the kill shell will wait for the pid file to appear, and how often it
183 * re-checks. `container.exec()`/`exec.start()` resolve as soon as the DAEMON has
184 * accepted the exec — the container-side shell has not necessarily run its first
185 * statement yet, so `pidRecordingCommand`'s `echo $$ > file` may not have
186 * happened when a prompt `kill()` arrives.
187 *
188 * That window is not hypothetical: `journal-reader` kills its follower the
189 * instant its abort fires, which can be within a millisecond of the spawn. With
190 * a bare `cat`, `$pid` came back empty, `[ -n "$pid" ]` was false, NOTHING was
191 * signalled, and `stream.destroy()` merely detached the client — restoring
192 * exactly the silent-orphan leak this whole mechanism exists to remove, for the
193 * fast-abort case only (which is the common one).
194 *
195 * 2s at 50ms is ~40 attempts: generous next to the milliseconds a shell needs to
196 * run one `echo`, and bounded so a genuinely-never-written file (the exec failed
197 * to start at all) still reports rather than hanging teardown.
198 */
199const PID_WAIT_TIMEOUT_MS = 2000
200const PID_WAIT_INTERVAL_MS = 50
201
202/** Grace period between the requested signal and the unconditional `KILL`. */
203const KILL_ESCALATION_DELAY_MS = 200
204
205/**
206 * Shell that signals the pid recorded in `pidFile`, then removes the file.
207 *
208 * The process GROUP is signalled first (`kill -SIG -<pid>`): a docker-exec
209 * process is its own group leader, so the negative form also reaches background
210 * grandchildren (`cmd & …`) that signalling the bare pid would orphan. If it is
211 * not a group leader the negative form fails harmlessly and the bare pid is
212 * signalled instead. Either way we escalate to `KILL`, because a process
213 * ignoring `TERM` is still a leak.
214 *
215 * IT WAITS FOR THE PID FILE. See {@link PID_WAIT_TIMEOUT_MS} — a prompt kill
216 * races the container-side `echo $$`, and losing that race used to mean sending
217 * no signal at all.
218 *
219 * IT STILL CANNOT FAIL, BUT IT DOES REPORT. Every step stays `|| true`-shaped
220 * (`2>/dev/null`, trailing `:`) because callers are `kill()` and abort handlers,
221 * where a throw would wedge the caller instead of freeing anything — so the exit
222 * code is uninformative BY DESIGN and must not be the only evidence. That was
223 * the previous version's real defect: a refused kill (no `kill` builtin,
224 * permissions, a pid that was never recorded) was indistinguishable from
225 * success, which is precisely the unfalsifiability that flipped Vercel and
226 * Daytona to `killableProcesses: false`. So the shell now:
227 *
228 * - prints {@link KILL_NO_PID_MARKER} when the pid file never appeared;
229 * - VERIFIES with `kill -0` after the escalation and prints
230 * {@link KILL_FAILED_MARKER} if the process is still there.
231 *
232 * `kill -0` is what makes the success claim falsifiable: it answers "is it gone"
233 * from the container's own kernel rather than from the exit status of a command
234 * that was built never to fail. {@link DockerHandle.killRecordedPid} turns either
235 * marker into a logger warning.
236 */
237function killRecordedPidCommand(
238 pidFile: string,
239 signal?: NodeJS.Signals | number,
240): string {
241 const sig = killSignalArg(signal)
242 const f = q(pidFile)
243 const attempts = Math.ceil(PID_WAIT_TIMEOUT_MS / PID_WAIT_INTERVAL_MS)
244 const sleepStep = (PID_WAIT_INTERVAL_MS / 1000).toFixed(3)
245 return [
246 // Bounded wait for `pidRecordingCommand`'s `echo $$ > file` to land.
247 `pid=''`,
248 `i=0`,
249 `while [ "$i" -lt ${attempts} ]; do`,
250 ` pid=$(cat ${f} 2>/dev/null)`,
251 ` [ -n "$pid" ] && break`,
252 ` sleep ${sleepStep}`,
253 ` i=$((i+1))`,
254 `done`,
255 `if [ -n "$pid" ]; then`,
256 ` kill -${sig} -"$pid" 2>/dev/null || kill -${sig} "$pid" 2>/dev/null`,
257 ` sleep ${(KILL_ESCALATION_DELAY_MS / 1000).toFixed(3)}`,
258 ` kill -KILL -"$pid" 2>/dev/null || kill -KILL "$pid" 2>/dev/null`,
259 // Verify, do not assume: ask the kernel whether the pid is still there.
260 ` if kill -0 "$pid" 2>/dev/null; then`,
261 ` echo ${KILL_FAILED_MARKER} pid="$pid" >&2`,
262 ` fi`,
263 `else`,
264 ` echo ${KILL_NO_PID_MARKER} file=${f} >&2`,
265 `fi`,
266 `rm -f ${f}`,
267 `:`,
268 ].join('\n')
269}
270
271/**
272 * Lifecycle of ONE pid file, shared between the wrapper's exit handlers and its
273 * kill path.
274 *
275 * It exists because "the pid file is absent" answers two different questions and
276 * the kill shell can only see one of them. To that shell an absent file means
277 * "not written YET", so it waits {@link PID_WAIT_TIMEOUT_MS} and then reports a
278 * possible orphan — correct for the fast-abort race it was added for, and wrong
279 * for the far more common case where the container-side process exited on its own
280 * and {@link DockerHandle.removePidFile} deleted the file. In that case there is
281 * nothing to signal, so waiting 2s inside `await proc.kill()` and then warning
282 * about an orphan is a lie plus a delay.
283 *
284 * `followJournal` makes it the norm, not an edge case: its `finally` calls
285 * `proc.kill()` on EVERY exit path, including the clean ones. Since that warning
286 * is the only in-band evidence for `killableProcesses: true`, a channel that
287 * fires on every ordinary teardown cannot support the claim.
288 */
289interface PidFileState {
290 /**
291 * The wrapper exited on its own and WE removed its pid file, so the file's
292 * absence is not evidence about any live process. Makes a subsequent
293 * `killRecordedPid` a no-op.
294 */
295 exited: boolean
296 /**
297 * A kill was requested, so the kill shell owns the pid file (it reads, then
298 * `rm -f`s it) and the exit handlers must not remove it out from under the
299 * `cat`.
300 */
301 killRequested: boolean
302 /**
303 * The in-flight kill, memoised so concurrent kills JOIN it rather than issue a
304 * second one. Both the abort listener and `followJournal`'s `finally` fire on
305 * the abort path; without this the second kill is a `container.exec()` round
306 * trip behind the first, arrives after that shell's `rm -f`, and pays the full
307 * wait before reporting the same false orphan. The first kill escalates to
308 * `SIGKILL` unconditionally, so a second one has nothing to add anyway.
309 */
310 kill?: Promise<void>
311}
312
313/**
314 * Decode spawn stdout/stderr as a byte stream, not chunk-by-chunk. A naive
315 * per-chunk `Buffer.toString('utf8')` corrupts any multi-byte UTF-8 character
316 * that a Node stream happens to split across two `data` events — each half
317 * decodes independently into a replacement character. A streaming
318 * `TextDecoder` retains a partial trailing sequence across `decode()` calls
319 * (`{ stream: true }`) and only emits it once the full character has
320 * arrived. We flush (`decoder.decode()` with no args) once the stream ends
321 * so a genuinely truncated trailing sequence is still surfaced (as U+FFFD)
322 * rather than silently dropped — matching the pattern already used in
323 * `ai-sandbox-sprites`'s `client.ts`.
324 */
325async function* decodeStream(stream: Readable): AsyncIterable<string> {
326 const decoder = new TextDecoder('utf-8')
327 for await (const chunk of stream) {
328 yield typeof chunk === 'string'
329 ? chunk
330 : decoder.decode(chunk as Buffer, { stream: true })
331 }
332 const tail = decoder.decode()
333 if (tail !== '') yield tail
334}
335
336export interface DockerHandleDeps {
337 docker: Dockerode
338 container: Dockerode.Container
339 workdir: string
340 /** Factory used by fork: commit + create a new container from the image. */
341 forkFactory: (sourceContainerId: string) => Promise<SandboxHandle>
342 /** Remove the container on destroy (vs. just stop). */
343 removeOnDestroy: boolean
344 /**
345 * Sink for non-fatal teardown diagnostics — a kill the container refused or
346 * could not confirm. Teardown never throws, so without a logger those are
347 * silent and `killableProcesses: true` becomes unfalsifiable.
348 */
349 logger?: DockerLogger
350}
351
352export class DockerHandle implements SandboxHandle {
353 readonly id: string
354 readonly provider = 'docker'
355 readonly workspaceRoot: string
356 readonly capabilities = DOCKER_CAPS
357 readonly fs: SandboxHandle['fs']
358 readonly git: SandboxHandle['git']
359 readonly process: SandboxHandle['process']
360 readonly ports: SandboxHandle['ports']
361 readonly env: SandboxHandle['env']
362
363 private readonly docker: Dockerode
364 private readonly container: Dockerode.Container
365 private readonly workdir: string
366 private readonly deps: DockerHandleDeps
367 private readonly logger: DockerLogger | undefined
368 private readonly envVars: Record<string, string> = {}
369
370 constructor(deps: DockerHandleDeps) {
371 this.docker = deps.docker
372 this.container = deps.container
373 this.workdir = deps.workdir
374 this.logger = deps.logger
375 this.workspaceRoot = deps.workdir
376 this.deps = deps
377 this.id = deps.container.id
378
379 this.process = {
380 exec: (command, opts) => this.exec(command, opts),
381 spawn: (command, opts) => this.spawnProcess(command, opts),
382 }
383
384 this.fs = {
385 read: async (p) => {
386 const r = await this.exec(`base64 ${q(this.abs(p))}`)
387 if (r.exitCode !== 0) throw new Error(`read failed: ${r.stderr.trim()}`)
388 return Buffer.from(r.stdout, 'base64').toString('utf8')
389 },
390 readBytes: async (p) => {
391 const r = await this.exec(`base64 ${q(this.abs(p))}`)
392 if (r.exitCode !== 0) throw new Error(`read failed: ${r.stderr.trim()}`)
393 return new Uint8Array(Buffer.from(r.stdout, 'base64'))
394 },
395 write: async (p, data) => {
396 for (const command of fsWriteCommands(this.abs(p), data)) {
397 const r = await this.exec(command)
398 if (r.exitCode !== 0)
399 throw new Error(`write failed: ${r.stderr.trim()}`)
400 }
401 },
402 list: async (p) => {
403 const r = await this.exec(`ls -1Ap ${q(this.abs(p))}`)
404 if (r.exitCode !== 0) throw new Error(`list failed: ${r.stderr.trim()}`)
405 return r.stdout
406 .split('\n')
407 .filter((line) => line.trim() !== '')
408 .map((entry) => {
409 const isDir = entry.endsWith('/')
410 const name = isDir ? entry.slice(0, -1) : entry
411 return {
412 name,
413 path: `${p.replace(/\/$/, '')}/${name}`,
414 type: isDir ? ('dir' as const) : ('file' as const),
415 }
416 })
417 },
418 lstat: async (p) => this.lstat(this.abs(p)),
419 mkdir: async (p) => {
420 await this.exec(`mkdir -p ${q(this.abs(p))}`)
421 },
422 remove: async (p) => {
423 await this.exec(`rm -rf ${q(this.abs(p))}`)
424 },
425 rename: async (from, to) => {
426 await this.exec(`mv ${q(this.abs(from))} ${q(this.abs(to))}`)
427 },
428 exists: async (p) => {
429 const r = await this.exec(`test -e ${q(this.abs(p))}`)
430 return r.exitCode === 0
431 },
432 }
433
434 this.git = createExecBackedGit(this.process, this.workdir)
435
436 this.ports = {
437 connect: (port) => this.connectPort(port),
438 }
439
440 this.env = {
441 set: (vars) => {
442 Object.assign(this.envVars, vars)
443 return Promise.resolve()
444 },
445 }
446 }
447
448 /** Map the conventional `/workspace` virtual root to the container workdir. */
449 private abs(p: string): string {
450 if (this.workdir === '/workspace') return p
451 if (p === '/workspace') return this.workdir
452 if (p.startsWith('/workspace/'))
453 return `${this.workdir}/${p.slice('/workspace/'.length)}`
454 return p
455 }
456
457 private async lstat(path: string): Promise<SandboxFsStat | undefined> {
458 const r = await this.exec(lstatCommand(path))
459 if (r.exitCode === 0 && r.stdout.trim() === LSTAT_MISSING) return undefined
460 if (r.exitCode !== 0) {
461 throw new Error(`lstat failed: ${r.stderr.trim()}`)
462 }
463 return parseLstatOutput(r.stdout)
464 }
465
466 private envArray(extra?: Record<string, string>): Array<string> {
467 // Docker `exec` Env replaces the container env. Keep a PATH and HOME so
468 // CLIs still resolve and `~/.claude` has a home when secrets are the only
469 // other vars.
470 return Object.entries({
471 PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
472 HOME: '/root',
473 ...this.envVars,
474 ...extra,
475 }).map(([k, v]) => `${k}=${v}`)
476 }
477
478 /**
479 * Signal the container-side process that recorded its pid to `pidFile`, and
480 * REPORT anything that says the process may still be alive.
481 *
482 * AWAITABLE, and callers on the `kill()` path must await it. It used to be
483 * fire-and-forget (`void this.exec(...)`), which meant `await proc.kill()`
484 * resolved before the container had been asked to do anything — so the
485 * documented ordering of `await proc.kill(); await handle.destroy()` did not
486 * hold, and a caller could not know whether the kill had even been attempted.
487 *
488 * NEVER THROWS. The container may already be stopping — itself a terminal kill
489 * of everything inside it — and this runs from teardown paths where a
490 * rejection would wedge the caller instead of freeing anything. But "does not
491 * throw" is not "cannot be observed to fail": a refusal reported by the shell
492 * (see {@link killRecordedPidCommand}) or a rejected exec both reach the
493 * logger, so an unkillable process is visible rather than silently assumed
494 * dead.
495 *
496 * A NO-OP ONCE THE OWNER HAS EXITED. `state.exited` says the pid file is gone
497 * because we removed it, not because the container-side shell has yet to write
498 * it — see {@link PidFileState}. Without that distinction every clean teardown
499 * (`followJournal` kills in a `finally` on all paths) spent
500 * {@link PID_WAIT_TIMEOUT_MS} waiting for a file nothing would ever write and
501 * then warned about an orphan that did not exist, which is exactly the
502 * cried-wolf channel `killableProcesses: true` cannot be evidenced by.
503 *
504 * ONE KILL PER WRAPPER. Concurrent callers join the first kill's promise
505 * instead of issuing a second `container.exec()` that would arrive after the
506 * first shell's `rm -f` and report the same phantom. The first escalates to
507 * `SIGKILL` unconditionally, so a second adds nothing.
508 */
509 private killRecordedPid(
510 pidFile: string,
511 state: PidFileState,
512 signal?: NodeJS.Signals | number,
513 ): Promise<void> {
514 if (state.exited) return Promise.resolve()
515 state.killRequested = true
516 state.kill ??= this.runRecordedKill(pidFile, signal)
517 return state.kill
518 }
519
520 private async runRecordedKill(
521 pidFile: string,
522 signal?: NodeJS.Signals | number,
523 ): Promise<void> {
524 let result: ExecResult
525 try {
526 result = await this.exec(killRecordedPidCommand(pidFile, signal))
527 } catch (error) {
528 this.logger?.warn('docker: could not run the in-container kill', {
529 pidFile,
530 error: error instanceof Error ? error.message : String(error),
531 })
532 return
533 }
534 if (result.stderr.includes(KILL_FAILED_MARKER)) {
535 this.logger?.warn(
536 'docker: in-container process survived the kill; it may be orphaned',
537 { pidFile, stderr: result.stderr.trim() },
538 )
539 } else if (result.stderr.includes(KILL_NO_PID_MARKER)) {
540 // The pid file never appeared within `PID_WAIT_TIMEOUT_MS`, so NO signal
541 // was sent. Nothing here can fix that; saying so is the whole point.
542 this.logger?.warn(
543 'docker: no pid was recorded for this process, so it could not be signalled',
544 { pidFile, stderr: result.stderr.trim() },
545 )
546 }
547 }
548
549 /**
550 * Remove a pid file whose owner has exited on its own.
551 *
552 * `killRecordedPidCommand` already removes it on the kill path, which covered
553 * only killed processes: every signal-bearing `exec` and every `spawn` wrote
554 * one, and a normally-exiting command left it in `/tmp` for the life of the
555 * container. Being dot-prefixed, `journalListCommand`'s `ls -1` never showed
556 * them, so the accumulation was silent.
557 *
558 * Fire-and-forget on purpose — it runs from stream-completion handlers, races
559 * a container that may already be gone, and a leftover file in a doomed
560 * container's `/tmp` is not worth failing or delaying anything for.
561 */
562 private removePidFile(pidFile: string): void {
563 void this.exec(`rm -f ${q(pidFile)}`).catch(() => {
564 // Container already stopped/removed — its whole `/tmp` went with it.
565 })
566 }
567
568 private async exec(
569 command: string,
570 opts?: ProcessOptions,
571 ): Promise<ExecResult> {
572 // Only pay for the pid-recording wrapper when the caller can actually abort
573 // — `exec` also backs every fs operation, which never needs a kill path.
574 const pidFile = opts?.signal
575 ? `/tmp/.tanstack-sandbox-exec-${randomUUID()}.pid`
576 : undefined
577 const exec = await this.container.exec({
578 Cmd: [
579 'sh',
580 '-c',
581 pidFile ? pidRecordingCommand(command, pidFile) : command,
582 ],
583 AttachStdout: true,
584 AttachStderr: true,
585 WorkingDir: opts?.cwd ? this.abs(opts.cwd) : this.workdir,
586 Env: this.envArray(opts?.env),
587 })
588 const stream = await exec.start({ hijack: true, stdin: false })
589
590 const stdoutChunks: Array<Buffer> = []
591 const stderrChunks: Array<Buffer> = []
592 const outW = new Writable({
593 write(chunk, _enc, cb) {
594 stdoutChunks.push(chunk as Buffer)
595 cb()
596 },
597 })
598 const errW = new Writable({
599 write(chunk, _enc, cb) {
600 stderrChunks.push(chunk as Buffer)
601 cb()
602 },
603 })
604 this.docker.modem.demuxStream(stream, outW, errW)
605
606 const state: PidFileState = { exited: false, killRequested: false }
607 const signal = opts?.signal
608 // Named so it can be DETACHED below. With `{ once: true }` alone the
609 // listener outlives the exec, so an abort fired after the command had
610 // already finished re-entered the kill path for a pid file we had removed —
611 // 2s of waiting and a phantom orphan warning for a process that was long
612 // gone.
613 const onAbort = (): void => {
614 // Kill inside the container FIRST — detaching the stream on its own
615 // leaves the command running (see `pidRecordingCommand`). This one
616 // handler cannot await (an `AbortSignal` listener is synchronous), so
617 // the kill is dispatched and its own reporting is left to
618 // `killRecordedPid`'s logger. `SpawnHandle.kill` — the path a caller
619 // sequences teardown on — DOES await.
620 if (pidFile !== undefined) void this.killRecordedPid(pidFile, state)
621 stream.destroy()
622 }
623 if (signal) signal.addEventListener('abort', onAbort, { once: true })
624
625 try {
626 await new Promise<void>((resolve, reject) => {
627 stream.on('end', resolve)
628 // A destroyed stream (abort) emits only `close`, never `end`, so without
629 // this an aborted exec would never settle at all.
630 stream.on('close', resolve)
631 stream.on('error', reject)
632 })
633 } finally {
634 // `finally`, not a statement after the `await`: `stream.on('error')`
635 // REJECTS, and on that path the straight-line cleanup never ran at all —
636 // so an erroring exec left its pid file in the container's `/tmp` for the
637 // container's whole life, the exact leak this cleanup exists to prevent.
638 if (signal) signal.removeEventListener('abort', onAbort)
639 // The wrapper exited (or failed) on its own, so nothing will ever read its
640 // pid file again. On the kill path `killRecordedPidCommand` removes it
641 // instead — removing it here too would race that kill's `cat`.
642 if (pidFile !== undefined && !state.killRequested) {
643 state.exited = true
644 this.removePidFile(pidFile)
645 }
646 }
647
648 const info = await exec.inspect()
649 return {
650 stdout: Buffer.concat(stdoutChunks).toString('utf8'),
651 stderr: Buffer.concat(stderrChunks).toString('utf8'),
652 exitCode: info.ExitCode ?? 0,
653 }
654 }
655
656 private async spawnProcess(
657 command: string,
658 opts?: ProcessOptions,
659 ): Promise<SpawnHandle> {
660 const pidFile = `/tmp/.tanstack-sandbox-spawn-${randomUUID()}.pid`
661 const exec = await this.container.exec({
662 Cmd: ['sh', '-c', pidRecordingCommand(command, pidFile)],
663 AttachStdin: true,
664 AttachStdout: true,
665 AttachStderr: true,
666 WorkingDir: opts?.cwd ? this.abs(opts.cwd) : this.workdir,
667 Env: this.envArray(opts?.env),
668 })
669 const stream = await exec.start({ hijack: true, stdin: true })
670 const outPT = new PassThrough()
671 const errPT = new PassThrough()
672 this.docker.modem.demuxStream(stream, outPT, errPT)
673 /*
674 * Close the demuxed output streams when the hijacked exec stream finishes,
675 * so consumers iterating `stdout`/`stderr` (for await ... of) terminate.
676 * A normal EOF emits `end`, but a destroyed stream (e.g. from kill()) emits
677 * only `close` and never `end` — so we must also end the PassThroughs on
678 * `close`/`error`, or the consumer hangs forever waiting for the iterator to
679 * complete. `end()` is idempotent, so handling multiple events is safe.
680 */
681 const endOutputs = (): void => {
682 outPT.end()
683 errPT.end()
684 }
685 stream.on('end', endOutputs)
686 stream.on('close', endOutputs)
687 stream.on('error', endOutputs)
688 const state: PidFileState = { exited: false, killRequested: false }
689 /*
690 * The owner exited without anyone killing it, so ITS pid file is ours to
691 * remove — and, just as importantly, its absence from here on means "gone",
692 * not "not written yet" (`state.exited`; see `PidFileState`). `kill()`/abort
693 * own the file instead when they ran, because their shell reads it before
694 * `rm -f`-ing it.
695 *
696 * All three events, not just `end`: `end` fires only on a clean EOF, so a
697 * stream reaching `close` or `error` without one — a broken connection to
698 * the daemon, a container stopping under us — used to leak the file for the
699 * container's whole life. `state.exited` keeps the removal idempotent across
700 * the `end`+`close` pair a clean exit emits.
701 */
702 const ownerExited = (): void => {
703 if (state.killRequested || state.exited) return
704 state.exited = true
705 this.removePidFile(pidFile)
706 }
707 stream.on('end', ownerExited)
708 stream.on('close', ownerExited)
709 stream.on('error', ownerExited)
710 const signal = opts?.signal
711 // Detached once the stream settles — see the twin comment in `exec` for why
712 // a listener outliving its process is a source of phantom orphan warnings.
713 const onAbort = (): void => {
714 // Synchronous listener — cannot await. See the twin comment in `exec`.
715 void this.killRecordedPid(pidFile, state)
716 stream.destroy()
717 }
718 if (signal) {
719 signal.addEventListener('abort', onAbort, { once: true })
720 const detach = (): void => signal.removeEventListener('abort', onAbort)
721 stream.on('end', detach)
722 stream.on('close', detach)
723 stream.on('error', detach)
724 }
725
726 return {
727 pid: -1, // docker exec does not surface a host-visible pid
728 stdout: decodeStream(outPT),
729 stderr: decodeStream(errPT),
730 stdin: {
731 write: (data) =>
732 new Promise<void>((resolve, reject) => {
733 stream.write(data, (err) => (err ? reject(err) : resolve()))
734 }),
735 end: () => {
736 stream.end()
737 return Promise.resolve()
738 },
739 },
740 wait: async () => {
741 await new Promise<void>((resolve) => {
742 if (outPT.readableEnded) {
743 resolve()
744 return
745 }
746 // Resolve on whichever of these fires first. A clean exit emits
747 // `end`; a destroyed/killed stream emits only `close` (never `end`),
748 // so wait on both or this hangs after kill().
749 stream.once('end', resolve)
750 stream.once('close', resolve)
751 stream.once('error', resolve)
752 })
753 const info = await exec.inspect()
754 return info.ExitCode ?? 0
755 },
756 /**
757 * Kill the container-side process, THEN detach. Detaching alone would
758 * leave it running (see `pidRecordingCommand`) — a silent orphan leak.
759 *
760 * AWAITS the in-container kill, so when this resolves the container has
761 * been asked and has answered. It previously returned an
762 * already-resolved promise while the kill was still in flight, which gave
763 * `await proc.kill(); await handle.destroy()` no ordering at all.
764 *
765 * ESCALATES TO `SIGKILL` unconditionally, {@link KILL_ESCALATION_DELAY_MS}
766 * after `signal`. This is a teardown primitive, not a graceful-shutdown
767 * one: a process that ignores `TERM` is a leak, and the container-side pid
768 * is the only handle we have on it. A `signal` argument therefore selects
769 * WHICH signal the process gets a brief chance to handle — NOT whether it
770 * may take its time. A handler needing longer than that must be given its
771 * time before calling this (send the signal yourself and await the
772 * process's own exit via {@link SpawnHandle.wait}).
773 *
774 * Never rejects — see `killRecordedPid`. A kill the container refused is
775 * reported through the handle's `logger`, not thrown.
776 *
777 * CHEAP AND SILENT WHEN THE PROCESS ALREADY EXITED. Callers kill
778 * unconditionally in `finally` blocks — `journal-reader`'s `followJournal`
779 * does so on every exit path, clean ones included — so this is routinely
780 * called on a process that is already gone. That case is not a failed kill:
781 * no wait, no signal, no warning (see `PidFileState`).
782 */
783 kill: async (killSignal) => {
784 await this.killRecordedPid(pidFile, state, killSignal)
785 stream.destroy()
786 },
787 }
788 }
789
790 private async connectPort(port: number): Promise<SandboxChannel> {
791 const info = await this.container.inspect()
792 const mapping = info.NetworkSettings.Ports[`${port}/tcp`]
793 const hostPort = mapping?.[0]?.HostPort
794 if (!hostPort) {
795 throw new Error(
796 `docker: container port ${port} is not published. Pass publishPorts: [${port}] to dockerSandbox() to reach it from the host.`,
797 )
798 }
799 return { url: `http://localhost:${hostPort}` }
800 }
801
802 async snapshot(label?: string): Promise<SnapshotRef> {
803 const tag = `tanstack-ai-sandbox-snapshot:${this.id.slice(0, 12)}-${label ?? 'snap'}`
804 const [repo, tagName] = tag.split(':')
805 await this.container.commit({ repo, tag: tagName })
806 return { id: tag, label }
807 }
808
809 fork = async (): Promise<SandboxHandle> => {
810 if (!this.capabilities.fork) {
811 throw new UnsupportedCapabilityError('docker', 'fork')
812 }
813 return this.deps.forkFactory(this.id)
814 }
815
816 async destroy(): Promise<void> {
817 try {
818 await this.container.stop({ t: 5 })
819 } catch {
820 // already stopped
821 }
822 if (this.deps.removeOnDestroy) {
823 await this.container.remove({ force: true, v: true })
824 }
825 }
826}