Open History to see the last commit
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,
50}
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, `'\\''`)}'`
74}
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)}`
84}
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`
91}
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 }
112}
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}`
134}
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 }
200}
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
212}
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 // The SDK takes the signal of each file call (`o`).
243 this.fs = {
244 read: (p, o) =>
245 this.sandbox.files.read(this.abs(p), { format: 'text', ...o }),
246 readBytes: (p, o) =>
247 this.sandbox.files.read(this.abs(p), { format: 'bytes', ...o }),
248 write: async (p, data, o) => {
249 const abs = this.abs(p)
250 // envd creates missing parents on write; a Blob carries bytes verbatim.
251 if (typeof data === 'string') {
252 await this.sandbox.files.write(abs, data, o)
253 } else {
254 // `Blob` wants an ArrayBuffer-backed view; a caller's Uint8Array may
255 // sit on a SharedArrayBuffer, so copy into a fresh one.
256 const bytes = new Uint8Array(data.byteLength)
257 bytes.set(data)
258 await this.sandbox.files.write(abs, new Blob([bytes]), o)
259 }
260 },
261 list: async (p, o) => {
262 const entries = await this.sandbox.files.list(this.abs(p), o)
263 const base = p.replace(/\/$/, '')
264 return entries.map((entry) => ({
265 name: entry.name,
266 path: `${base}/${entry.name}`,
267 type: entry.type === 'dir' ? ('dir' as const) : ('file' as const),
268 }))
269 },
270 lstat: async (p, o) => {
271 o?.signal?.throwIfAborted()
272 return this.lstat(this.abs(p))
273 },
274 mkdir: async (p, o) => {
275 // Resolves false when the directory already exists; both are success.
276 await this.sandbox.files.makeDir(this.abs(p), o)
277 },
278 remove: (p, o) => this.sandbox.files.remove(this.abs(p), o),
279 rename: async (from, to, o) => {
280 await this.sandbox.files.rename(this.abs(from), this.abs(to), o)
281 },
282 exists: (p, o) => this.sandbox.files.exists(this.abs(p), o),
283 }
284
285 this.git = createExecBackedGit(this.process, this.workspaceRoot)
286
287 this.ports = {
288 connect: (port) => Promise.resolve(this.connectPort(port)),
289 }
290
291 this.env = {
292 set: (vars) => {
293 Object.assign(this.envVars, vars)
294 return Promise.resolve()
295 },
296 }
297 }
298
299 /** Map the conventional `/workspace` virtual root to the sandbox workdir. */
300 private abs(p: string): string {
301 if (this.workdir === '/workspace') return p
302 if (p === '/workspace') return this.workdir
303 if (p.startsWith('/workspace/'))
304 return `${this.workdir}/${p.slice('/workspace/'.length)}`
305 return p
306 }
307
308 private mergedEnv(extra?: Record<string, string>): Record<string, string> {
309 return { ...this.envVars, ...extra }
310 }
311
312 private async lstat(path: string): Promise<SandboxFsStat | undefined> {
313 const r = await this.exec(lstatCommand(path))
314 if (r.exitCode === 0 && r.stdout.trim() === LSTAT_MISSING) return undefined
315 if (r.exitCode !== 0) {
316 const output = `${r.stdout}\n${r.stderr}`
317 throw new Error(`lstat failed: ${output.trim()}`)
318 }
319 return parseLstatOutput(r.stdout)
320 }
321
322 /**
323 * Start a command with a real sandbox pid. Both `exec` and `spawn` go through
324 * here so an abort can kill the sandbox-side process: the SDK's own `signal`
325 * only cancels the client request and leaves the process running (measured).
326 *
327 * envd runs `bash -l -c <cmd>` and its `kill()` is a SIGKILL to that one pid,
328 * which orphans a backgrounded child (`( … ) & wait` kept ticking, measured).
329 * So the command is wrapped in `setsid`: the shell keeps envd's pid (it is not
330 * a group leader, so `setsid` execs in place) and becomes the leader of a
331 * fresh process group that {@link killGroup} can signal as a whole.
332 */
333 private async start(
334 command: string,
335 opts: ProcessOptions | undefined,
336 io: {
337 stdin: boolean
338 onStdout?: (data: string) => void
339 onStderr?: (data: string) => void
340 },
341 ): Promise<CommandHandle> {
342 opts?.signal?.throwIfAborted()
343 const env = this.mergedEnv(opts?.env)
344 return this.sandbox.commands.run(groupLeaderCommand(command), {
345 background: true,
346 cwd: opts?.cwd ? this.abs(opts.cwd) : this.workdir,
347 ...(Object.keys(env).length > 0 ? { envs: env } : {}),
348 stdin: io.stdin,
349 timeoutMs: NO_COMMAND_TIMEOUT_MS,
350 ...(io.onStdout ? { onStdout: io.onStdout } : {}),
351 ...(io.onStderr ? { onStderr: io.onStderr } : {}),
352 })
353 }
354
355 /**
356 * SIGKILL the whole process group a {@link start}ed command leads, then the
357 * pid itself. The group kill is a second command because envd's `sendSignal`
358 * addresses a single pid; `handle.kill()` afterwards also ends the SDK's
359 * event stream so `wait()` settles.
360 */
361 private async killGroup(handle: CommandHandle): Promise<void> {
362 await this.sandbox.commands
363 .run(`kill -KILL -- -${handle.pid}`)
364 .catch(() => undefined) // exit 1 when the group is already gone
365 await handle.kill().catch(() => undefined)
366 }
367
368 /**
369 * Resolve the exit code; a non-zero exit is a result here, not an error.
370 * Anything else (the event stream dropped, envd restarted) says nothing
371 * about the process, which may still be running, so it is killed before
372 * the error surfaces rather than left to run until the sandbox expires.
373 */
374 private async exitCodeOf(handle: CommandHandle): Promise<number> {
375 try {
376 const result = await handle.wait()
377 return result.exitCode
378 } catch (error) {
379 if (error instanceof CommandExitError) return error.exitCode
380 await this.killGroup(handle)
381 throw error
382 }
383 }
384
385 private async exec(
386 command: string,
387 opts?: ProcessOptions,
388 ): Promise<ExecResult> {
389 const handle = await this.start(command, opts, { stdin: false })
390 const onAbort = (): void => {
391 void this.killGroup(handle)
392 }
393 opts?.signal?.addEventListener('abort', onAbort, { once: true })
394 // An abort that landed during the start round trip has no listener yet.
395 if (opts?.signal?.aborted === true) onAbort()
396 try {
397 const exitCode = await this.exitCodeOf(handle)
398 return { stdout: handle.stdout, stderr: handle.stderr, exitCode }
399 } finally {
400 opts?.signal?.removeEventListener('abort', onAbort)
401 }
402 }
403
404 private async spawnProcess(
405 command: string,
406 opts?: ProcessOptions,
407 ): Promise<SpawnHandle> {
408 const started: { handle?: CommandHandle } = {}
409 const onOverflow = (): void => {
410 if (started.handle) void this.killGroup(started.handle)
411 }
412 const stdoutQ = new AsyncChunkQueue('stdout', onOverflow)
413 const stderrQ = new AsyncChunkQueue('stderr', onOverflow)
414
415 const handle = await this.start(command, opts, {
416 stdin: true,
417 onStdout: (data) => stdoutQ.push(data),
418 onStderr: (data) => stderrQ.push(data),
419 })
420 started.handle = handle
421 if (stdoutQ.overflowed || stderrQ.overflowed) onOverflow()
422
423 const onAbort = (): void => {
424 void this.killGroup(handle)
425 }
426 opts?.signal?.addEventListener('abort', onAbort, { once: true })
427
428 const exit = this.exitCodeOf(handle).finally(() => {
429 opts?.signal?.removeEventListener('abort', onAbort)
430 stdoutQ.end()
431 stderrQ.end()
432 })
433 exit.catch(() => undefined)
434
435 if (opts?.signal?.aborted === true) {
436 onAbort()
437 opts.signal.throwIfAborted()
438 }
439
440 return {
441 pid: handle.pid,
442 stdout: stdoutQ,
443 stderr: stderrQ,
444 stdin: {
445 write: (data) => handle.sendStdin(data),
446 end: () => handle.closeStdin(),
447 },
448 wait: () => exit,
449 // Always SIGKILL, to the whole group; the requested signal is not honoured.
450 kill: () => this.killGroup(handle),
451 }
452 }
453
454 private connectPort(port: number): SandboxChannel {
455 const url = `https://${this.sandbox.getHost(port)}`
456 const token = this.sandbox.trafficAccessToken
457 if (!token) return { url }
458 // Ports of a sandbox with public traffic disabled are gated by this
459 // header; browsers cannot send it, HTTP consumers attach it verbatim.
460 return { url, token, headers: { [TRAFFIC_TOKEN_HEADER]: token } }
461 }
462
463 snapshot = async (label?: string): Promise<SnapshotRef> => {
464 // E2B pauses the sandbox briefly while it is captured, then resumes it.
465 const snap = await this.sandbox.createSnapshot({
466 name: snapshotName(this.id, label),
467 })
468 return { id: snap.snapshotId, ...(label !== undefined ? { label } : {}) }
469 }
470
471 fork = async (): Promise<SandboxHandle> => {
472 const [forked] = await this.sandbox.fork(
473 this.timeoutMs !== undefined ? { timeoutMs: this.timeoutMs } : {},
474 )
475 if (forked === undefined) throw new Error('e2b: fork returned no sandbox')
476 if (forked instanceof Error) throw forked
477 const handle = new E2BHandle({
478 sandbox: forked,
479 workdir: this.workdir,
480 ...(this.timeoutMs !== undefined ? { timeoutMs: this.timeoutMs } : {}),
481 })
482 // The fork carries the parent's process env only for what envd stored at
483 // create; mirror the overlay so per-command merging stays identical.
484 await handle.env.set(this.envVars)
485 return handle
486 }
487
488 async destroy(): Promise<void> {
489 await this.sandbox.kill()
490 }
491}