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

handle.ts

486 lines17.9 KB

1/**
2 * SandboxHandle backed by an E2B cloud sandbox (via the `e2b` SDK). Real
3 * isolation: fs/exec/git operate inside the remote Firecracker microVM; paths
4 * are real sandbox paths (default workdir `/home/user/workspace`).
5 *
6 * fs uses the native E2B filesystem API. Blocking exec and spawn both go
7 * through `commands.run` with `background: true`, so every command has a real
8 * sandbox pid and `cwd`/`env` are passed natively (never as `export K=V;`
9 * prefixes in the command string). stdout and stderr arrive on separate
10 * streams. envd's own `kill()` is a SIGKILL to that one pid and a backgrounded
11 * child survived it (measured), so every command runs as a `setsid` process
12 * group leader and `kill()` signals the group; `tests/journal.conformance.test.ts`
13 * keeps that claim falsifiable.
14 */
15import { Buffer } from 'node:buffer'
16import { createExecBackedGit } from '@tanstack/ai-sandbox'
17import { CommandExitError } from 'e2b'
18import type { CommandHandle, Sandbox } from 'e2b'
19import type {
20 ExecResult,
21 ProcessOptions,
22 SandboxCapabilities,
23 SandboxChannel,
24 SandboxFsStat,
25 SandboxHandle,
26 SnapshotRef,
27 SpawnHandle,
28} from '@tanstack/ai-sandbox'
29​
30export const E2B_CAPS: SandboxCapabilities = {
31 fs: true,
32 exec: true,
33 env: true,
34 ports: true,
35 backgroundProcesses: true,
36 writableStdin: true,
37 // MEASURED against a real E2B sandbox. envd's own kill is a SIGKILL to the
38 // shell pid and a backgrounded `( … ) & wait` child kept ticking through it;
39 // every command therefore runs as a `setsid` group leader and `kill()`
40 // signals the group (`kill -KILL -- -<pid>`), after which the ticker stopped.
41 // The journal conformance suite re-measures this whenever `E2B_API_KEY` is
42 // present.
43 killableProcesses: true,
44 snapshots: true,
45 networkPolicy: true,
46 // The sandbox filesystem persists across exec calls and pause/resume until
47 // the sandbox is killed or its timeout elapses.
48 durableFilesystem: true,
49 fork: true,
51​
52/** Default working directory. `/workspace` is not writable by the sandbox user. */
53export const DEFAULT_WORKDIR = '/home/user/workspace'
54​
55/**
56 * Request header that authenticates HTTP traffic to a sandbox port when the
57 * sandbox was created with `network.allowPublicTraffic: false`.
58 */
59export const TRAFFIC_TOKEN_HEADER = 'e2b-traffic-access-token'
60​
61/**
62 * `0` disables the SDK's per-command deadline (its default is 60s, far too
63 * short for `setup` steps such as `pnpm install`). The sandbox timeout still
64 * bounds the whole run.
65 */
66const NO_COMMAND_TIMEOUT_MS = 0
67​
68/** Byte cap per spawned stream; exceeding it truncates and kills the process. */
69const MAX_STREAM_BYTES = 8 * 1024 * 1024
70​
71/** POSIX single-quote escape for embedding paths in `sh -c`. */
72function q(value: string): string {
73 return `'${value.replace(/'/g, `'\\''`)}'`
75​
76/**
77 * Run `command` as the leader of its own process group so a kill can reach
78 * every descendant. `setsid` (util-linux) ships in the default E2B template;
79 * an image without it fails loudly (exit 127) instead of silently losing the
80 * advertised `killableProcesses`.
81 */
82export function groupLeaderCommand(command: string): string {
83 return `exec setsid bash -c ${q(command)}`
85​
86const LSTAT_MISSING = '__TANSTACK_LSTAT_MISSING__'
87​
88/** Verify a missing path by listing parent entries. `test -e` also fails for inaccessible parents. */
89function lstatCommand(path: string): string {
90 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`
92​
93function parseLstatOutput(output: string): SandboxFsStat {
94 const fields = /^(?<mode>[0-9a-fA-F]{4}):(?<size>\d+)\n?$/.exec(output)
95 const mode = fields?.groups?.mode
96 const size = fields?.groups?.size
97 if (!mode || !size) throw new Error(`invalid lstat output: ${output}`)
98 const parsedMode = Number.parseInt(mode, 16)
99 const parsedSize = Number(size)
100 if (
101 !Number.isSafeInteger(parsedMode) ||
102 !Number.isSafeInteger(parsedSize) ||
103 parsedSize < 0
104 )
105 throw new Error(`invalid lstat output: ${output}`)
106 const type = parsedMode & 0xf000
107 if (type === 0x8000)
108 return { type: 'file', mode: parsedMode, size: parsedSize }
109 if (type === 0x4000) return { type: 'dir', mode: parsedMode }
110 if (type === 0xa000) return { type: 'symlink', mode: parsedMode }
111 return { type: 'other', mode: parsedMode }
113​
114/**
115 * E2B snapshot names are template names: keep them lower-case, `[a-z0-9-]`, and
116 * unique per sandbox. Reusing a name assigns a new build to the SAME template,
117 * so two sandboxes labelled `after-setup` must not share one.
118 */
119export function snapshotName(
120 sandboxId: string,
121 label: string | undefined,
122): string {
123 const safe = (value: string): string =>
124 value
125 .toLowerCase()
126 .replace(/[^a-z0-9-]+/g, '-')
127 .replace(/-+/g, '-')
128 .replace(/^-|-$/g, '')
129 const suffix = safe(label ?? 'snap') || 'snap'
130 // Truncate the id, never the label: the label is what keeps two snapshots
131 // of one sandbox apart.
132 const room = 63 - 'tanstack-ai-'.length - 1 - suffix.length
133 return `tanstack-ai-${safe(sandboxId).slice(0, Math.max(room, 1))}-${suffix}`
135​
136/**
137 * A push-driven async iterable with a byte cap. The streamer pushes decoded
138 * chunks and calls `end()` once; consumers `for await` over it.
139 */
140class AsyncChunkQueue implements AsyncIterable<string> {
141 private readonly chunks: Array<string> = []
142 private readonly waiters: Array<(r: IteratorResult<string>) => void> = []
143 private ended = false
144 private bytes = 0
145 private truncated = false
146​
147 constructor(
148 private readonly label: string,
149 private readonly onOverflow?: () => void,
150 ) {}
151​
152 push(chunk: string): void {
153 if (chunk === '' || this.ended) return
154 this.bytes += Buffer.byteLength(chunk)
155 if (this.bytes > MAX_STREAM_BYTES) {
156 this.truncated = true
157 this.emit(
158 `\n[e2b] ${this.label} exceeded ${MAX_STREAM_BYTES} bytes; output truncated\n`,
159 )
160 this.end()
161 this.onOverflow?.()
162 return
163 }
164 this.emit(chunk)
165 }
166​
167 get overflowed(): boolean {
168 return this.truncated
169 }
170​
171 private emit(chunk: string): void {
172 const waiter = this.waiters.shift()
173 if (waiter) waiter({ value: chunk, done: false })
174 else this.chunks.push(chunk)
175 }
176​
177 end(): void {
178 this.ended = true
179 let waiter = this.waiters.shift()
180 while (waiter) {
181 waiter({ value: undefined, done: true })
182 waiter = this.waiters.shift()
183 }
184 }
185​
186 [Symbol.asyncIterator](): AsyncIterator<string> {
187 return {
188 next: () => {
189 const chunk = this.chunks.shift()
190 if (chunk !== undefined) {
191 return Promise.resolve({ value: chunk, done: false })
192 }
193 if (this.ended) {
194 return Promise.resolve({ value: undefined, done: true })
195 }
196 return new Promise((resolve) => this.waiters.push(resolve))
197 },
198 }
199 }
201​
202export interface E2BHandleDeps {
203 /** The live E2B sandbox object. */
204 sandbox: Sandbox
205 /** Working directory inside the sandbox (the `/workspace` virtual root maps here). */
206 workdir: string
207 /**
208 * Sandbox timeout in milliseconds, forwarded to forks so a branched sandbox
209 * gets the same lifetime as its parent.
210 */
211 timeoutMs?: number
213​
214export class E2BHandle implements SandboxHandle {
215 readonly id: string
216 readonly provider = 'e2b'
217 readonly workspaceRoot: string
218 readonly capabilities = E2B_CAPS
219 readonly fs: SandboxHandle['fs']
220 readonly git: SandboxHandle['git']
221 readonly process: SandboxHandle['process']
222 readonly ports: SandboxHandle['ports']
223 readonly env: SandboxHandle['env']
224​
225 private readonly sandbox: Sandbox
226 private readonly workdir: string
227 private readonly timeoutMs: number | undefined
228 private readonly envVars: Record<string, string> = {}
229​
230 constructor(deps: E2BHandleDeps) {
231 this.sandbox = deps.sandbox
232 this.workdir = deps.workdir
233 this.timeoutMs = deps.timeoutMs
234 this.workspaceRoot = deps.workdir
235 this.id = deps.sandbox.sandboxId
236​
237 this.process = {
238 exec: (command, opts) => this.exec(command, opts),
239 spawn: (command, opts) => this.spawnProcess(command, opts),
240 }
241​
242 this.fs = {
243 read: (p) => this.sandbox.files.read(this.abs(p), { format: 'text' }),
244 readBytes: (p) =>
245 this.sandbox.files.read(this.abs(p), { format: 'bytes' }),
246 write: async (p, data) => {
247 const abs = this.abs(p)
248 // envd creates missing parents on write; a Blob carries bytes verbatim.
249 if (typeof data === 'string') {
250 await this.sandbox.files.write(abs, data)
251 } else {
252 // `Blob` wants an ArrayBuffer-backed view; a caller's Uint8Array may
253 // sit on a SharedArrayBuffer, so copy into a fresh one.
254 const bytes = new Uint8Array(data.byteLength)
255 bytes.set(data)
256 await this.sandbox.files.write(abs, new Blob([bytes]))
257 }
258 },
259 list: async (p) => {
260 const entries = await this.sandbox.files.list(this.abs(p))
261 const base = p.replace(/\/$/, '')
262 return entries.map((entry) => ({
263 name: entry.name,
264 path: `${base}/${entry.name}`,
265 type: entry.type === 'dir' ? ('dir' as const) : ('file' as const),
266 }))
267 },
268 lstat: (p) => this.lstat(this.abs(p)),
269 mkdir: async (p) => {
270 // Resolves false when the directory already exists; both are success.
271 await this.sandbox.files.makeDir(this.abs(p))
272 },
273 remove: (p) => this.sandbox.files.remove(this.abs(p)),
274 rename: async (from, to) => {
275 await this.sandbox.files.rename(this.abs(from), this.abs(to))
276 },
277 exists: (p) => this.sandbox.files.exists(this.abs(p)),
278 }
279​
280 this.git = createExecBackedGit(this.process, this.workspaceRoot)
281​
282 this.ports = {
283 connect: (port) => Promise.resolve(this.connectPort(port)),
284 }
285​
286 this.env = {
287 set: (vars) => {
288 Object.assign(this.envVars, vars)
289 return Promise.resolve()
290 },
291 }
292 }
293​
294 /** Map the conventional `/workspace` virtual root to the sandbox workdir. */
295 private abs(p: string): string {
296 if (this.workdir === '/workspace') return p
297 if (p === '/workspace') return this.workdir
298 if (p.startsWith('/workspace/'))
299 return `${this.workdir}/${p.slice('/workspace/'.length)}`
300 return p
301 }
302​
303 private mergedEnv(extra?: Record<string, string>): Record<string, string> {
304 return { ...this.envVars, ...extra }
305 }
306​
307 private async lstat(path: string): Promise<SandboxFsStat | undefined> {
308 const r = await this.exec(lstatCommand(path))
309 if (r.exitCode === 0 && r.stdout.trim() === LSTAT_MISSING) return undefined
310 if (r.exitCode !== 0) {
311 const output = `${r.stdout}\n${r.stderr}`
312 throw new Error(`lstat failed: ${output.trim()}`)
313 }
314 return parseLstatOutput(r.stdout)
315 }
316​
317 /**
318 * Start a command with a real sandbox pid. Both `exec` and `spawn` go through
319 * here so an abort can kill the sandbox-side process: the SDK's own `signal`
320 * only cancels the client request and leaves the process running (measured).
321 *
322 * envd runs `bash -l -c <cmd>` and its `kill()` is a SIGKILL to that one pid,
323 * which orphans a backgrounded child (`( … ) & wait` kept ticking, measured).
324 * So the command is wrapped in `setsid`: the shell keeps envd's pid (it is not
325 * a group leader, so `setsid` execs in place) and becomes the leader of a
326 * fresh process group that {@link killGroup} can signal as a whole.
327 */
328 private async start(
329 command: string,
330 opts: ProcessOptions | undefined,
331 io: {
332 stdin: boolean
333 onStdout?: (data: string) => void
334 onStderr?: (data: string) => void
335 },
336 ): Promise<CommandHandle> {
337 opts?.signal?.throwIfAborted()
338 const env = this.mergedEnv(opts?.env)
339 return this.sandbox.commands.run(groupLeaderCommand(command), {
340 background: true,
341 cwd: opts?.cwd ? this.abs(opts.cwd) : this.workdir,
342 ...(Object.keys(env).length > 0 ? { envs: env } : {}),
343 stdin: io.stdin,
344 timeoutMs: NO_COMMAND_TIMEOUT_MS,
345 ...(io.onStdout ? { onStdout: io.onStdout } : {}),
346 ...(io.onStderr ? { onStderr: io.onStderr } : {}),
347 })
348 }
349​
350 /**
351 * SIGKILL the whole process group a {@link start}ed command leads, then the
352 * pid itself. The group kill is a second command because envd's `sendSignal`
353 * addresses a single pid; `handle.kill()` afterwards also ends the SDK's
354 * event stream so `wait()` settles.
355 */
356 private async killGroup(handle: CommandHandle): Promise<void> {
357 await this.sandbox.commands
358 .run(`kill -KILL -- -${handle.pid}`)
359 .catch(() => undefined) // exit 1 when the group is already gone
360 await handle.kill().catch(() => undefined)
361 }
362​
363 /**
364 * Resolve the exit code; a non-zero exit is a result here, not an error.
365 * Anything else (the event stream dropped, envd restarted) says nothing
366 * about the process, which may still be running, so it is killed before
367 * the error surfaces rather than left to run until the sandbox expires.
368 */
369 private async exitCodeOf(handle: CommandHandle): Promise<number> {
370 try {
371 const result = await handle.wait()
372 return result.exitCode
373 } catch (error) {
374 if (error instanceof CommandExitError) return error.exitCode
375 await this.killGroup(handle)
376 throw error
377 }
378 }
379​
380 private async exec(
381 command: string,
382 opts?: ProcessOptions,
383 ): Promise<ExecResult> {
384 const handle = await this.start(command, opts, { stdin: false })
385 const onAbort = (): void => {
386 void this.killGroup(handle)
387 }
388 opts?.signal?.addEventListener('abort', onAbort, { once: true })
389 // An abort that landed during the start round trip has no listener yet.
390 if (opts?.signal?.aborted === true) onAbort()
391 try {
392 const exitCode = await this.exitCodeOf(handle)
393 return { stdout: handle.stdout, stderr: handle.stderr, exitCode }
394 } finally {
395 opts?.signal?.removeEventListener('abort', onAbort)
396 }
397 }
398​
399 private async spawnProcess(
400 command: string,
401 opts?: ProcessOptions,
402 ): Promise<SpawnHandle> {
403 const started: { handle?: CommandHandle } = {}
404 const onOverflow = (): void => {
405 if (started.handle) void this.killGroup(started.handle)
406 }
407 const stdoutQ = new AsyncChunkQueue('stdout', onOverflow)
408 const stderrQ = new AsyncChunkQueue('stderr', onOverflow)
409​
410 const handle = await this.start(command, opts, {
411 stdin: true,
412 onStdout: (data) => stdoutQ.push(data),
413 onStderr: (data) => stderrQ.push(data),
414 })
415 started.handle = handle
416 if (stdoutQ.overflowed || stderrQ.overflowed) onOverflow()
417​
418 const onAbort = (): void => {
419 void this.killGroup(handle)
420 }
421 opts?.signal?.addEventListener('abort', onAbort, { once: true })
422​
423 const exit = this.exitCodeOf(handle).finally(() => {
424 opts?.signal?.removeEventListener('abort', onAbort)
425 stdoutQ.end()
426 stderrQ.end()
427 })
428 exit.catch(() => undefined)
429​
430 if (opts?.signal?.aborted === true) {
431 onAbort()
432 opts.signal.throwIfAborted()
433 }
434​
435 return {
436 pid: handle.pid,
437 stdout: stdoutQ,
438 stderr: stderrQ,
439 stdin: {
440 write: (data) => handle.sendStdin(data),
441 end: () => handle.closeStdin(),
442 },
443 wait: () => exit,
444 // Always SIGKILL, to the whole group; the requested signal is not honoured.
445 kill: () => this.killGroup(handle),
446 }
447 }
448​
449 private connectPort(port: number): SandboxChannel {
450 const url = `https://${this.sandbox.getHost(port)}`
451 const token = this.sandbox.trafficAccessToken
452 if (!token) return { url }
453 // Ports of a sandbox with public traffic disabled are gated by this
454 // header; browsers cannot send it, HTTP consumers attach it verbatim.
455 return { url, token, headers: { [TRAFFIC_TOKEN_HEADER]: token } }
456 }
457​
458 snapshot = async (label?: string): Promise<SnapshotRef> => {
459 // E2B pauses the sandbox briefly while it is captured, then resumes it.
460 const snap = await this.sandbox.createSnapshot({
461 name: snapshotName(this.id, label),
462 })
463 return { id: snap.snapshotId, ...(label !== undefined ? { label } : {}) }
464 }
465​
466 fork = async (): Promise<SandboxHandle> => {
467 const [forked] = await this.sandbox.fork(
468 this.timeoutMs !== undefined ? { timeoutMs: this.timeoutMs } : {},
469 )
470 if (forked === undefined) throw new Error('e2b: fork returned no sandbox')
471 if (forked instanceof Error) throw forked
472 const handle = new E2BHandle({
473 sandbox: forked,
474 workdir: this.workdir,
475 ...(this.timeoutMs !== undefined ? { timeoutMs: this.timeoutMs } : {}),
476 })
477 // The fork carries the parent's process env only for what envd stored at
478 // create; mirror the overlay so per-command merging stays identical.
479 await handle.env.set(this.envVars)
480 return handle
481 }
482​
483 async destroy(): Promise<void> {
484 await this.sandbox.kill()
485 }