Open History to see the last commit
1import { randomUUID } from 'node:crypto'
2import { runnerSource } from './runner'
3import type {
4 ExecutionResult,
5 IsolateConfig,
6 IsolateContext,
7 IsolateDriver,
8 ToolBinding,
9} from '@tanstack/ai-code-mode'
10import type { RunnerMessage, ToolReply } from './runner'
11
12/** The slice of an E2B `CommandHandle` the driver uses. */
13export interface E2BCommandHandleLike {
14 readonly pid: number
15 wait: () => Promise<{ exitCode: number }>
16 kill: () => Promise<boolean>
17 sendStdin: (data: string) => Promise<void>
18}
19
20/**
21 * The slice of an E2B `Sandbox` (from `e2b` or `@e2b/code-interpreter`) the
22 * driver uses. The template must provide `node`, `setsid` and `timeout`; the
23 * default E2B templates do.
24 */
25export interface E2BSandboxLike {
26 files: {
27 write: (path: string, data: string) => Promise<unknown>
28 }
29 commands: {
30 run: {
31 (
32 cmd: string,
33 opts: {
34 background: true
35 stdin: true
36 timeoutMs: number
37 onStdout: (data: string) => void
38 onStderr: (data: string) => void
39 },
40 ): Promise<E2BCommandHandleLike>
41 (cmd: string): Promise<unknown>
42 }
43 }
44}
45
46export interface E2BIsolateDriverConfig {
47 /**
48 * Caller-owned E2B sandbox. Each execution runs as its own `node` process
49 * in it; the driver never creates, pauses or kills the sandbox itself.
50 */
51 sandbox: E2BSandboxLike
52
53 /**
54 * Default execution timeout in milliseconds, including tool calls
55 * (default: 30000). A per-context `timeout` overrides it.
56 */
57 timeout?: number
58}
59
60/** Stdout plus stderr a single execution may produce before it is killed. */
61const MAX_OUTPUT_BYTES = 8 * 1024 * 1024
62const STDERR_TAIL = 2048
63
64function validateTimeout(timeout: number): number {
65 if (!Number.isFinite(timeout) || timeout <= 0) {
66 throw new Error('timeout must be a finite positive number')
67 }
68 return timeout
69}
70
71// The limit goes into a shell command, so only a plain integer may pass.
72function validateMemoryLimit(memoryLimit: number): number {
73 if (!Number.isSafeInteger(memoryLimit) || memoryLimit <= 0) {
74 throw new Error('memoryLimit must be a positive integer (MB)')
75 }
76 return memoryLimit
77}
78
79function failure(
80 name: string,
81 message: string,
82 logs: Array<string>,
83): ExecutionResult<never> {
84 return { success: false, error: { name, message }, logs }
85}
86
87function errorMessage(error: unknown): string {
88 return error instanceof Error ? error.message : String(error)
89}
90
91/**
92 * A killed, expired or paused sandbox. Measured on e2b 2.51: `commands.run`
93 * throws `SandboxNotFoundError`, `files.write` a `TimeoutError` whose message
94 * says the sandbox was not found.
95 */
96function isSandboxGone(error: unknown): boolean {
97 if (!(error instanceof Error)) return false
98 return (
99 error.name === 'SandboxNotFoundError' ||
100 (error.name === 'TimeoutError' &&
101 error.message.includes('sandbox was not found'))
102 )
103}
104
105const UNCONFIRMED_STOP =
106 'The process could not be confirmed stopped and may still be running in the sandbox.'
107
108function noteUnconfirmed<T>(result: ExecutionResult<T>): ExecutionResult<T> {
109 const logs = [...(result.logs ?? []), UNCONFIRMED_STOP]
110 const error = result.error
111 if (result.success || error === undefined) return { ...result, logs }
112 return {
113 ...result,
114 logs,
115 error: {
116 ...error,
117 message: `${error.message} ${UNCONFIRMED_STOP}`,
118 },
119 }
120}
121
122function exitCodeOf(value: unknown): number | undefined {
123 if (typeof value !== 'object' || value === null || !('exitCode' in value)) {
124 return undefined
125 }
126 return typeof value.exitCode === 'number' ? value.exitCode : undefined
127}
128
129/** `kill` exits non-zero when the group is already gone. That is a confirmed stop. */
130function groupAlreadyGone(value: unknown): boolean {
131 const stderr =
132 typeof value === 'object' &&
133 value !== null &&
134 'stderr' in value &&
135 typeof value.stderr === 'string'
136 ? value.stderr
137 : ''
138 const message = value instanceof Error ? value.message : ''
139 return /no such process/i.test(`${stderr}\n${message}`)
140}
141
142/**
143 * Code in the sandbox can reach the runner's stdout, so every message is
144 * checked before the host acts on it.
145 */
146function isRunnerMessage(value: unknown): value is RunnerMessage {
147 if (typeof value !== 'object' || value === null) return false
148 const m = value as Record<string, unknown>
149 if (m.type === 'log') return typeof m.line === 'string'
150 if (m.type === 'tool')
151 return typeof m.id === 'string' && typeof m.name === 'string'
152 if (m.type !== 'done' || typeof m.success !== 'boolean') return false
153 if (m.success) return true
154 const error = m.error as Record<string, unknown> | null | undefined
155 return (
156 typeof error === 'object' &&
157 error !== null &&
158 typeof error.name === 'string' &&
159 typeof error.message === 'string'
160 )
161}
162
163async function runTool(
164 bindings: Record<string, ToolBinding>,
165 id: string,
166 name: string,
167 args: unknown,
168): Promise<ToolReply> {
169 const binding = Object.hasOwn(bindings, name) ? bindings[name] : undefined
170 if (!binding) return { id, success: false, error: `Unknown tool: ${name}` }
171 try {
172 return { id, success: true, value: await binding.execute(args) }
173 } catch (error) {
174 return { id, success: false, error: errorMessage(error) }
175 }
176}
177
178type KillOutcome = 'killed' | 'gone' | 'unconfirmed'
179
180class E2BIsolateContext implements IsolateContext {
181 private disposed = false
182 /** Stops each in-flight execution; used by `dispose`. */
183 private readonly running = new Set<() => Promise<void>>()
184
185 constructor(
186 private readonly sandbox: E2BSandboxLike,
187 private readonly bindings: Record<string, ToolBinding>,
188 private readonly timeoutMs: number,
189 private readonly memoryLimitMb: number,
190 ) {}
191
192 /**
193 * SIGKILL the process group the execution leads (`setsid`). This reaches
194 * processes the code spawned, unless they moved to a group of their own
195 * (`detached`). A non-zero kill is unconfirmed, except when the group is
196 * already gone.
197 */
198 private async killGroup(handle: E2BCommandHandleLike): Promise<KillOutcome> {
199 let outcome: KillOutcome = 'killed'
200 try {
201 const result = await this.sandbox.commands.run(
202 `kill -KILL -- -${handle.pid}`,
203 )
204 const code = exitCodeOf(result)
205 if (code !== undefined && code !== 0 && !groupAlreadyGone(result)) {
206 outcome = 'unconfirmed'
207 }
208 } catch (error: unknown) {
209 if (isSandboxGone(error)) outcome = 'gone'
210 else if (!groupAlreadyGone(error)) outcome = 'unconfirmed'
211 }
212 // Also ends the SDK's event stream for this command.
213 try {
214 await handle.kill()
215 } catch (error: unknown) {
216 if (isSandboxGone(error)) outcome = 'gone'
217 else outcome = 'unconfirmed'
218 }
219 return outcome
220 }
221
222 /** Best effort: the runner deletes its own file once it starts. */
223 private removeFile(file: string): void {
224 void this.sandbox.commands.run(`rm -f ${file}`).catch(() => undefined)
225 }
226
227 async execute<T = unknown>(code: string): Promise<ExecutionResult<T>> {
228 if (this.disposed) {
229 return failure('DisposedError', 'Context has been disposed', [])
230 }
231 const deadline = Date.now() + this.timeoutMs
232 const logs: Array<string> = []
233 const marker = `__TANSTACK_CODE_MODE_${randomUUID()}__:`
234 const file = `/tmp/tanstack-code-mode-${randomUUID()}.js`
235
236 let source: string
237 try {
238 source = runnerSource(code, Object.keys(this.bindings), marker)
239 } catch (error) {
240 return failure('E2BExecutionError', errorMessage(error), logs)
241 }
242
243 // The first outcome wins: the program's result, or the host stopping it.
244 let finished = false
245 let resolveOutcome!: (result: ExecutionResult<T>) => void
246 const outcome = new Promise<ExecutionResult<T>>((r) => (resolveOutcome = r))
247 const finish = (result: ExecutionResult<T>): void => {
248 if (finished) return
249 finished = true
250 resolveOutcome(result)
251 }
252 // Stdout events can arrive before `commands.run` resolves.
253 let started!: (h: E2BCommandHandleLike | undefined) => void
254 const handle = new Promise<E2BCommandHandleLike | undefined>(
255 (r) => (started = r),
256 )
257
258 let halting: Promise<void> | undefined
259 let commandStarted = false
260 /**
261 * Stop the run. If the process has not started, report at once so a hung
262 * `files.write` or `commands.run` cannot hold the caller. If it has
263 * started, kill first: a dead sandbox replaces the reason.
264 */
265 const halt = (name: string, message: string): Promise<void> => {
266 if (finished) return halting ?? Promise.resolve()
267 finished = true
268 halting = (async () => {
269 if (!commandStarted) {
270 resolveOutcome(failure(name, message, logs))
271 const h = await handle
272 if (h && (await this.killGroup(h)) === 'unconfirmed') {
273 logs.push(UNCONFIRMED_STOP)
274 }
275 return
276 }
277 const h = await handle
278 const killed = h ? await this.killGroup(h) : 'killed'
279 resolveOutcome(
280 killed === 'gone'
281 ? failure(
282 'E2BSandboxUnavailableError',
283 'The E2B sandbox stopped during execution (killed, expired or paused).',
284 logs,
285 )
286 : failure(
287 name,
288 killed === 'unconfirmed'
289 ? `${message} ${UNCONFIRMED_STOP}`
290 : message,
291 logs,
292 ),
293 )
294 })()
295 return halting
296 }
297 const stopHere = (): Promise<void> =>
298 halt('DisposedError', 'Context was disposed during execution.')
299 this.running.add(stopHere)
300
301 let outputBytes = 0
302 let stderrTail = ''
303 let outOfMemory = false
304 const countOutput = (data: string): void => {
305 outputBytes += Buffer.byteLength(data)
306 if (outputBytes > MAX_OUTPUT_BYTES) {
307 void halt(
308 'OutputLimitError',
309 `Execution produced more than ${MAX_OUTPUT_BYTES} bytes of output.`,
310 )
311 }
312 }
313 const reply = async (name: string, answer: ToolReply): Promise<void> => {
314 let line: string
315 try {
316 line = JSON.stringify(answer)
317 } catch (error) {
318 line = JSON.stringify({
319 id: answer.id,
320 success: false,
321 error: `${name} returned a value that is not JSON-serializable: ${errorMessage(error)}`,
322 })
323 }
324 try {
325 await (await handle)?.sendStdin(`${line}\n`)
326 } catch (error) {
327 await halt(
328 'E2BExecutionError',
329 `Could not deliver the result of ${name} to the sandbox: ${errorMessage(error)}.`,
330 )
331 }
332 }
333 const onMessage = (message: RunnerMessage): void => {
334 if (finished) return
335 if (message.type === 'log') {
336 logs.push(message.line)
337 } else if (message.type === 'done') {
338 finish(
339 message.success
340 ? { success: true, value: message.value as T, logs }
341 : { success: false, error: message.error, logs },
342 )
343 } else {
344 const { id, name, args } = message
345 void runTool(this.bindings, id, name, args).then((answer) =>
346 finished ? undefined : reply(name, answer),
347 )
348 }
349 }
350 let buffered = ''
351 const onStdout = (data: string): void => {
352 countOutput(data)
353 buffered += data
354 let newline
355 while ((newline = buffered.indexOf('\n')) !== -1) {
356 const line = buffered.slice(0, newline)
357 buffered = buffered.slice(newline + 1)
358 if (!line.startsWith(marker)) continue
359 let message: unknown
360 try {
361 message = JSON.parse(line.slice(marker.length))
362 } catch {
363 message = undefined
364 }
365 if (isRunnerMessage(message)) onMessage(message)
366 else
367 void halt(
368 'E2BExecutionError',
369 'Malformed protocol line from sandbox.',
370 )
371 }
372 }
373 const onStderr = (data: string): void => {
374 countOutput(data)
375 const recent = stderrTail + data
376 // V8 prints this before a long stack trace that would push it out of the tail.
377 if (recent.includes('heap out of memory')) outOfMemory = true
378 stderrTail = recent.slice(-STDERR_TAIL)
379 }
380
381 // The budget starts now: writing the file and starting the process count.
382 const timer = setTimeout(() => {
383 void halt(
384 'TimeoutError',
385 `Exceeded E2B execution timeout (${this.timeoutMs}ms).`,
386 )
387 }, this.timeoutMs)
388 // Start in the background so a deadline resolves while write or run is open.
389 void (async () => {
390 let command: E2BCommandHandleLike
391 try {
392 await this.sandbox.files.write(file, source)
393 if (finished) {
394 started(undefined)
395 this.removeFile(file)
396 return
397 }
398 const budgetSeconds = Math.ceil((deadline - Date.now()) / 1000) + 1
399 command = await this.sandbox.commands.run(
400 // `setsid` makes the process a group leader so a kill reaches its
401 // children; `timeout` bounds an orphan if this host goes away.
402 `exec setsid timeout -s KILL ${budgetSeconds} node --max-old-space-size=${this.memoryLimitMb} ${file}`,
403 { background: true, stdin: true, timeoutMs: 0, onStdout, onStderr },
404 )
405 } catch (error) {
406 started(undefined)
407 this.removeFile(file)
408 finish(this.startFailure(error, logs))
409 return
410 }
411 commandStarted = true
412 started(command)
413 if (finished) return
414 void command.wait().then(
415 (result) =>
416 this.exited(result.exitCode, finish, outOfMemory, stderrTail, logs),
417 (error: unknown) => {
418 const exit = exitCodeOf(error)
419 if (exit !== undefined) {
420 this.exited(exit, finish, outOfMemory, stderrTail, logs)
421 return
422 }
423 void halt(
424 'E2BExecutionError',
425 `Lost the connection to the sandbox process; its outcome is unknown: ${errorMessage(error)}.`,
426 )
427 },
428 )
429 })()
430 try {
431 const result = await outcome
432 // A halt already owns the kill. A normal finish kills here, before return,
433 // so an unconfirmed stop is part of the result and `dispose` does not throw.
434 if (!halting) {
435 const h = await handle
436 if (h) {
437 const killed = await this.killGroup(h)
438 if (killed === 'unconfirmed') return noteUnconfirmed(result)
439 }
440 }
441 return result
442 } finally {
443 clearTimeout(timer)
444 this.running.delete(stopHere)
445 }
446 }
447
448 /** The process exited on its own, without sending a result. */
449 private exited<T>(
450 exitCode: number,
451 finish: (result: ExecutionResult<T>) => void,
452 outOfMemory: boolean,
453 stderrTail: string,
454 logs: Array<string>,
455 ): void {
456 finish(
457 outOfMemory
458 ? failure(
459 'MemoryLimitError',
460 `Execution exceeded the memory limit (${this.memoryLimitMb}MB).`,
461 logs,
462 )
463 : failure(
464 'E2BExecutionError',
465 `Sandbox process exited with code ${exitCode} before returning a result.${stderrTail ? ` stderr: ${stderrTail}` : ''}`,
466 logs,
467 ),
468 )
469 }
470
471 /** Writing the file or starting the process failed. */
472 private startFailure(error: unknown, logs: Array<string>) {
473 if (isSandboxGone(error)) {
474 return failure(
475 'E2BSandboxUnavailableError',
476 `The E2B sandbox is not running (killed, expired or paused): ${errorMessage(error)}`,
477 logs,
478 )
479 }
480 return failure(
481 'E2BExecutionError',
482 `Could not confirm that the program started in the E2B sandbox: ${errorMessage(error)}`,
483 logs,
484 )
485 }
486
487 async dispose(): Promise<void> {
488 this.disposed = true
489 await Promise.all([...this.running].map((stopRun) => stopRun()))
490 }
491}
492
493/**
494 * Code Mode isolate driver that runs generated code in a caller-owned E2B
495 * sandbox and keeps tool implementations on the host.
496 */
497export function createE2BIsolateDriver(
498 config: E2BIsolateDriverConfig,
499): IsolateDriver {
500 const defaultTimeout = validateTimeout(config.timeout ?? 30_000)
501 return {
502 // Async so a bad per-context option rejects instead of throwing.
503 async createContext(isolateConfig: IsolateConfig): Promise<IsolateContext> {
504 return new E2BIsolateContext(
505 config.sandbox,
506 isolateConfig.bindings,
507 validateTimeout(isolateConfig.timeout ?? defaultTimeout),
508 validateMemoryLimit(isolateConfig.memoryLimit ?? 128),
509 )
510 },
511 }
512}