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 // The native file calls take no abort signal, so each call checks it first.
385 this.fs = {
386 read: async (p, o) => {
387 o?.signal?.throwIfAborted()
388 const r = await this.exec(`base64 ${q(this.abs(p))}`)
389 if (r.exitCode !== 0) throw new Error(`read failed: ${r.stderr.trim()}`)
390 return Buffer.from(r.stdout, 'base64').toString('utf8')
391 },
392 readBytes: async (p, o) => {
393 o?.signal?.throwIfAborted()
394 const r = await this.exec(`base64 ${q(this.abs(p))}`)
395 if (r.exitCode !== 0) throw new Error(`read failed: ${r.stderr.trim()}`)
396 return new Uint8Array(Buffer.from(r.stdout, 'base64'))
397 },
398 write: async (p, data, o) => {
399 o?.signal?.throwIfAborted()
400 for (const command of fsWriteCommands(this.abs(p), data)) {
401 const r = await this.exec(command)
402 if (r.exitCode !== 0)
403 throw new Error(`write failed: ${r.stderr.trim()}`)
404 }
405 },
406 list: async (p, o) => {
407 o?.signal?.throwIfAborted()
408 const r = await this.exec(`ls -1Ap ${q(this.abs(p))}`)
409 if (r.exitCode !== 0) throw new Error(`list failed: ${r.stderr.trim()}`)
410 return r.stdout
411 .split('\n')
412 .filter((line) => line.trim() !== '')
413 .map((entry) => {
414 const isDir = entry.endsWith('/')
415 const name = isDir ? entry.slice(0, -1) : entry
416 return {
417 name,
418 path: `${p.replace(/\/$/, '')}/${name}`,
419 type: isDir ? ('dir' as const) : ('file' as const),
420 }
421 })
422 },
423 lstat: async (p, o) => {
424 o?.signal?.throwIfAborted()
425 return this.lstat(this.abs(p))
426 },
427 mkdir: async (p, o) => {
428 o?.signal?.throwIfAborted()
429 await this.exec(`mkdir -p ${q(this.abs(p))}`)
430 },
431 remove: async (p, o) => {
432 o?.signal?.throwIfAborted()
433 await this.exec(`rm -rf ${q(this.abs(p))}`)
434 },
435 rename: async (from, to, o) => {
436 o?.signal?.throwIfAborted()
437 await this.exec(`mv ${q(this.abs(from))} ${q(this.abs(to))}`)
438 },
439 exists: async (p, o) => {
440 o?.signal?.throwIfAborted()
441 const r = await this.exec(`test -e ${q(this.abs(p))}`)
442 return r.exitCode === 0
443 },
444 }
445
446 this.git = createExecBackedGit(this.process, this.workdir)
447
448 this.ports = {
449 connect: (port) => this.connectPort(port),
450 }
451
452 this.env = {
453 set: (vars) => {
454 Object.assign(this.envVars, vars)
455 return Promise.resolve()
456 },
457 }
458 }
459
460 /** Map the conventional `/workspace` virtual root to the container workdir. */
461 private abs(p: string): string {
462 if (this.workdir === '/workspace') return p
463 if (p === '/workspace') return this.workdir
464 if (p.startsWith('/workspace/'))
465 return `${this.workdir}/${p.slice('/workspace/'.length)}`
466 return p
467 }
468
469 private async lstat(path: string): Promise<SandboxFsStat | undefined> {
470 const r = await this.exec(lstatCommand(path))
471 if (r.exitCode === 0 && r.stdout.trim() === LSTAT_MISSING) return undefined
472 if (r.exitCode !== 0) {
473 throw new Error(`lstat failed: ${r.stderr.trim()}`)
474 }
475 return parseLstatOutput(r.stdout)
476 }
477
478 private envArray(extra?: Record<string, string>): Array<string> {
479 // Docker `exec` Env replaces the container env. Keep a PATH and HOME so
480 // CLIs still resolve and `~/.claude` has a home when secrets are the only
481 // other vars.
482 return Object.entries({
483 PATH: '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin',
484 HOME: '/root',
485 ...this.envVars,
486 ...extra,
487 }).map(([k, v]) => `${k}=${v}`)
488 }
489
490 /**
491 * Signal the container-side process that recorded its pid to `pidFile`, and
492 * REPORT anything that says the process may still be alive.
493 *
494 * AWAITABLE, and callers on the `kill()` path must await it. It used to be
495 * fire-and-forget (`void this.exec(...)`), which meant `await proc.kill()`
496 * resolved before the container had been asked to do anything — so the
497 * documented ordering of `await proc.kill(); await handle.destroy()` did not
498 * hold, and a caller could not know whether the kill had even been attempted.
499 *
500 * NEVER THROWS. The container may already be stopping — itself a terminal kill
501 * of everything inside it — and this runs from teardown paths where a
502 * rejection would wedge the caller instead of freeing anything. But "does not
503 * throw" is not "cannot be observed to fail": a refusal reported by the shell
504 * (see {@link killRecordedPidCommand}) or a rejected exec both reach the
505 * logger, so an unkillable process is visible rather than silently assumed
506 * dead.
507 *
508 * A NO-OP ONCE THE OWNER HAS EXITED. `state.exited` says the pid file is gone
509 * because we removed it, not because the container-side shell has yet to write
510 * it — see {@link PidFileState}. Without that distinction every clean teardown
511 * (`followJournal` kills in a `finally` on all paths) spent
512 * {@link PID_WAIT_TIMEOUT_MS} waiting for a file nothing would ever write and
513 * then warned about an orphan that did not exist, which is exactly the
514 * cried-wolf channel `killableProcesses: true` cannot be evidenced by.
515 *
516 * ONE KILL PER WRAPPER. Concurrent callers join the first kill's promise
517 * instead of issuing a second `container.exec()` that would arrive after the
518 * first shell's `rm -f` and report the same phantom. The first escalates to
519 * `SIGKILL` unconditionally, so a second adds nothing.
520 */
521 private killRecordedPid(
522 pidFile: string,
523 state: PidFileState,
524 signal?: NodeJS.Signals | number,
525 ): Promise<void> {
526 if (state.exited) return Promise.resolve()
527 state.killRequested = true
528 state.kill ??= this.runRecordedKill(pidFile, signal)
529 return state.kill
530 }
531
532 private async runRecordedKill(
533 pidFile: string,
534 signal?: NodeJS.Signals | number,
535 ): Promise<void> {
536 let result: ExecResult
537 try {
538 result = await this.exec(killRecordedPidCommand(pidFile, signal))
539 } catch (error) {
540 this.logger?.warn('docker: could not run the in-container kill', {
541 pidFile,
542 error: error instanceof Error ? error.message : String(error),
543 })
544 return
545 }
546 if (result.stderr.includes(KILL_FAILED_MARKER)) {
547 this.logger?.warn(
548 'docker: in-container process survived the kill; it may be orphaned',
549 { pidFile, stderr: result.stderr.trim() },
550 )
551 } else if (result.stderr.includes(KILL_NO_PID_MARKER)) {
552 // The pid file never appeared within `PID_WAIT_TIMEOUT_MS`, so NO signal
553 // was sent. Nothing here can fix that; saying so is the whole point.
554 this.logger?.warn(
555 'docker: no pid was recorded for this process, so it could not be signalled',
556 { pidFile, stderr: result.stderr.trim() },
557 )
558 }
559 }
560
561 /**
562 * Remove a pid file whose owner has exited on its own.
563 *
564 * `killRecordedPidCommand` already removes it on the kill path, which covered
565 * only killed processes: every signal-bearing `exec` and every `spawn` wrote
566 * one, and a normally-exiting command left it in `/tmp` for the life of the
567 * container. Being dot-prefixed, `journalListCommand`'s `ls -1` never showed
568 * them, so the accumulation was silent.
569 *
570 * Fire-and-forget on purpose — it runs from stream-completion handlers, races
571 * a container that may already be gone, and a leftover file in a doomed
572 * container's `/tmp` is not worth failing or delaying anything for.
573 */
574 private removePidFile(pidFile: string): void {
575 void this.exec(`rm -f ${q(pidFile)}`).catch(() => {
576 // Container already stopped/removed — its whole `/tmp` went with it.
577 })
578 }
579
580 private async exec(
581 command: string,
582 opts?: ProcessOptions,
583 ): Promise<ExecResult> {
584 // Only pay for the pid-recording wrapper when the caller can actually abort
585 // — `exec` also backs every fs operation, which never needs a kill path.
586 const pidFile = opts?.signal
587 ? `/tmp/.tanstack-sandbox-exec-${randomUUID()}.pid`
588 : undefined
589 const exec = await this.container.exec({
590 Cmd: [
591 'sh',
592 '-c',
593 pidFile ? pidRecordingCommand(command, pidFile) : command,
594 ],
595 AttachStdout: true,
596 AttachStderr: true,
597 WorkingDir: opts?.cwd ? this.abs(opts.cwd) : this.workdir,
598 Env: this.envArray(opts?.env),
599 })
600 const stream = await exec.start({ hijack: true, stdin: false })
601
602 const stdoutChunks: Array<Buffer> = []
603 const stderrChunks: Array<Buffer> = []
604 const outW = new Writable({
605 write(chunk, _enc, cb) {
606 stdoutChunks.push(chunk as Buffer)
607 cb()
608 },
609 })
610 const errW = new Writable({
611 write(chunk, _enc, cb) {
612 stderrChunks.push(chunk as Buffer)
613 cb()
614 },
615 })
616 this.docker.modem.demuxStream(stream, outW, errW)
617
618 const state: PidFileState = { exited: false, killRequested: false }
619 const signal = opts?.signal
620 // Named so it can be DETACHED below. With `{ once: true }` alone the
621 // listener outlives the exec, so an abort fired after the command had
622 // already finished re-entered the kill path for a pid file we had removed —
623 // 2s of waiting and a phantom orphan warning for a process that was long
624 // gone.
625 const onAbort = (): void => {
626 // Kill inside the container FIRST — detaching the stream on its own
627 // leaves the command running (see `pidRecordingCommand`). This one
628 // handler cannot await (an `AbortSignal` listener is synchronous), so
629 // the kill is dispatched and its own reporting is left to
630 // `killRecordedPid`'s logger. `SpawnHandle.kill` — the path a caller
631 // sequences teardown on — DOES await.
632 if (pidFile !== undefined) void this.killRecordedPid(pidFile, state)
633 stream.destroy()
634 }
635 if (signal) signal.addEventListener('abort', onAbort, { once: true })
636
637 try {
638 await new Promise<void>((resolve, reject) => {
639 stream.on('end', resolve)
640 // A destroyed stream (abort) emits only `close`, never `end`, so without
641 // this an aborted exec would never settle at all.
642 stream.on('close', resolve)
643 stream.on('error', reject)
644 })
645 } finally {
646 // `finally`, not a statement after the `await`: `stream.on('error')`
647 // REJECTS, and on that path the straight-line cleanup never ran at all —
648 // so an erroring exec left its pid file in the container's `/tmp` for the
649 // container's whole life, the exact leak this cleanup exists to prevent.
650 if (signal) signal.removeEventListener('abort', onAbort)
651 // The wrapper exited (or failed) on its own, so nothing will ever read its
652 // pid file again. On the kill path `killRecordedPidCommand` removes it
653 // instead — removing it here too would race that kill's `cat`.
654 if (pidFile !== undefined && !state.killRequested) {
655 state.exited = true
656 this.removePidFile(pidFile)
657 }
658 }
659
660 const info = await exec.inspect()
661 return {
662 stdout: Buffer.concat(stdoutChunks).toString('utf8'),
663 stderr: Buffer.concat(stderrChunks).toString('utf8'),
664 exitCode: info.ExitCode ?? 0,
665 }
666 }
667
668 private async spawnProcess(
669 command: string,
670 opts?: ProcessOptions,
671 ): Promise<SpawnHandle> {
672 const pidFile = `/tmp/.tanstack-sandbox-spawn-${randomUUID()}.pid`
673 const exec = await this.container.exec({
674 Cmd: ['sh', '-c', pidRecordingCommand(command, pidFile)],
675 AttachStdin: true,
676 AttachStdout: true,
677 AttachStderr: true,
678 WorkingDir: opts?.cwd ? this.abs(opts.cwd) : this.workdir,
679 Env: this.envArray(opts?.env),
680 })
681 const stream = await exec.start({ hijack: true, stdin: true })
682 const outPT = new PassThrough()
683 const errPT = new PassThrough()
684 this.docker.modem.demuxStream(stream, outPT, errPT)
685 /*
686 * Close the demuxed output streams when the hijacked exec stream finishes,
687 * so consumers iterating `stdout`/`stderr` (for await ... of) terminate.
688 * A normal EOF emits `end`, but a destroyed stream (e.g. from kill()) emits
689 * only `close` and never `end` — so we must also end the PassThroughs on
690 * `close`/`error`, or the consumer hangs forever waiting for the iterator to
691 * complete. `end()` is idempotent, so handling multiple events is safe.
692 */
693 const endOutputs = (): void => {
694 outPT.end()
695 errPT.end()
696 }
697 stream.on('end', endOutputs)
698 stream.on('close', endOutputs)
699 stream.on('error', endOutputs)
700 const state: PidFileState = { exited: false, killRequested: false }
701 /*
702 * The owner exited without anyone killing it, so ITS pid file is ours to
703 * remove — and, just as importantly, its absence from here on means "gone",
704 * not "not written yet" (`state.exited`; see `PidFileState`). `kill()`/abort
705 * own the file instead when they ran, because their shell reads it before
706 * `rm -f`-ing it.
707 *
708 * All three events, not just `end`: `end` fires only on a clean EOF, so a
709 * stream reaching `close` or `error` without one — a broken connection to
710 * the daemon, a container stopping under us — used to leak the file for the
711 * container's whole life. `state.exited` keeps the removal idempotent across
712 * the `end`+`close` pair a clean exit emits.
713 */
714 const ownerExited = (): void => {
715 if (state.killRequested || state.exited) return
716 state.exited = true
717 this.removePidFile(pidFile)
718 }
719 stream.on('end', ownerExited)
720 stream.on('close', ownerExited)
721 stream.on('error', ownerExited)
722 const signal = opts?.signal
723 // Detached once the stream settles — see the twin comment in `exec` for why
724 // a listener outliving its process is a source of phantom orphan warnings.
725 const onAbort = (): void => {
726 // Synchronous listener — cannot await. See the twin comment in `exec`.
727 void this.killRecordedPid(pidFile, state)
728 stream.destroy()
729 }
730 if (signal) {
731 signal.addEventListener('abort', onAbort, { once: true })
732 const detach = (): void => signal.removeEventListener('abort', onAbort)
733 stream.on('end', detach)
734 stream.on('close', detach)
735 stream.on('error', detach)
736 }
737
738 return {
739 pid: -1, // docker exec does not surface a host-visible pid
740 stdout: decodeStream(outPT),
741 stderr: decodeStream(errPT),
742 stdin: {
743 write: (data) =>
744 new Promise<void>((resolve, reject) => {
745 stream.write(data, (err) => (err ? reject(err) : resolve()))
746 }),
747 end: () => {
748 stream.end()
749 return Promise.resolve()
750 },
751 },
752 wait: async () => {
753 await new Promise<void>((resolve) => {
754 if (outPT.readableEnded) {
755 resolve()
756 return
757 }
758 // Resolve on whichever of these fires first. A clean exit emits
759 // `end`; a destroyed/killed stream emits only `close` (never `end`),
760 // so wait on both or this hangs after kill().
761 stream.once('end', resolve)
762 stream.once('close', resolve)
763 stream.once('error', resolve)
764 })
765 const info = await exec.inspect()
766 return info.ExitCode ?? 0
767 },
768 /**
769 * Kill the container-side process, THEN detach. Detaching alone would
770 * leave it running (see `pidRecordingCommand`) — a silent orphan leak.
771 *
772 * AWAITS the in-container kill, so when this resolves the container has
773 * been asked and has answered. It previously returned an
774 * already-resolved promise while the kill was still in flight, which gave
775 * `await proc.kill(); await handle.destroy()` no ordering at all.
776 *
777 * ESCALATES TO `SIGKILL` unconditionally, {@link KILL_ESCALATION_DELAY_MS}
778 * after `signal`. This is a teardown primitive, not a graceful-shutdown
779 * one: a process that ignores `TERM` is a leak, and the container-side pid
780 * is the only handle we have on it. A `signal` argument therefore selects
781 * WHICH signal the process gets a brief chance to handle — NOT whether it
782 * may take its time. A handler needing longer than that must be given its
783 * time before calling this (send the signal yourself and await the
784 * process's own exit via {@link SpawnHandle.wait}).
785 *
786 * Never rejects — see `killRecordedPid`. A kill the container refused is
787 * reported through the handle's `logger`, not thrown.
788 *
789 * CHEAP AND SILENT WHEN THE PROCESS ALREADY EXITED. Callers kill
790 * unconditionally in `finally` blocks — `journal-reader`'s `followJournal`
791 * does so on every exit path, clean ones included — so this is routinely
792 * called on a process that is already gone. That case is not a failed kill:
793 * no wait, no signal, no warning (see `PidFileState`).
794 */
795 kill: async (killSignal) => {
796 await this.killRecordedPid(pidFile, state, killSignal)
797 stream.destroy()
798 },
799 }
800 }
801
802 private async connectPort(port: number): Promise<SandboxChannel> {
803 const info = await this.container.inspect()
804 const mapping = info.NetworkSettings.Ports[`${port}/tcp`]
805 const hostPort = mapping?.[0]?.HostPort
806 if (!hostPort) {
807 throw new Error(
808 `docker: container port ${port} is not published. Pass publishPorts: [${port}] to dockerSandbox() to reach it from the host.`,
809 )
810 }
811 return { url: `http://localhost:${hostPort}` }
812 }
813
814 async snapshot(label?: string): Promise<SnapshotRef> {
815 const tag = `tanstack-ai-sandbox-snapshot:${this.id.slice(0, 12)}-${label ?? 'snap'}`
816 const [repo, tagName] = tag.split(':')
817 await this.container.commit({ repo, tag: tagName })
818 return { id: tag, label }
819 }
820
821 fork = async (): Promise<SandboxHandle> => {
822 if (!this.capabilities.fork) {
823 throw new UnsupportedCapabilityError('docker', 'fork')
824 }
825 return this.deps.forkFactory(this.id)
826 }
827
828 async destroy(): Promise<void> {
829 try {
830 await this.container.stop({ t: 5 })
831 } catch {
832 // already stopped
833 }
834 if (this.deps.removeOnDestroy) {
835 await this.container.remove({ force: true, v: true })
836 }
837 }
838}