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

isolate-driver.test.ts

489 lines17.2 KB

1/**
2 * The fake sandbox is real where it matters: `files.write` writes to a temp
3 * dir and `commands.run` starts a local `node` on the runner the driver wrote.
4 * So these tests exercise the actual runner and stdin/stdout protocol; only
5 * `setsid`/`timeout` (absent on macOS) are left to the live suite.
6 */
7import { spawn } from 'node:child_process'
8import { existsSync, mkdtempSync, writeFileSync } from 'node:fs'
9import { tmpdir } from 'node:os'
10import { basename, join } from 'node:path'
11import { describe, expect, it } from 'vitest'
12import { createE2BIsolateDriver } from '../src/index'
13import type { ChildProcess } from 'node:child_process'
14import type { ToolBinding } from '@tanstack/ai-code-mode'
15import type { E2BCommandHandleLike, E2BSandboxLike } from '../src/index'
16​
17interface FakeOptions {
18 writeError?: Error
19 runError?: Error
20 waitError?: Error
21 /** Delay before `files.write` resolves. */
22 writeDelayMs?: number
23 /** Delay before a group kill takes effect. */
24 killDelayMs?: number
25 /** A group kill fails with this error instead of killing. */
26 killError?: Error
27 /** Host writes this stdin line instead of the tool result. */
28 corruptStdin?: boolean
30​
31function named(name: string, message: string): Error {
32 const error = new Error(message)
33 error.name = name
34 return error
36​
37function exitError(exitCode: number): Error {
38 return Object.assign(named('CommandExitError', `exit ${exitCode}`), {
39 exitCode,
40 })
42​
43function localSandbox(options: FakeOptions = {}) {
44 const dir = mkdtempSync(join(tmpdir(), 'ai-isolate-e2b-'))
45 const localPaths = new Map<string, string>()
46 const commands: Array<string> = []
47 const children = new Map<number, ChildProcess>()
48​
49 const start = (
50 cmd: string,
51 io: { onStdout: (d: string) => void; onStderr: (d: string) => void },
52 ): E2BCommandHandleLike => {
53 const file = localPaths.get(cmd.split(' ').at(-1) ?? '')
54 const memory = /--max-old-space-size=(\d+)/.exec(cmd)?.[1]
55 if (file === undefined || memory === undefined) {
56 throw new Error(`unexpected command: ${cmd}`)
57 }
58 const child = spawn(
59 process.execPath,
60 [`--max-old-space-size=${memory}`, file],
61 { stdio: 'pipe' },
62 )
63 child.stdout.setEncoding('utf8').on('data', io.onStdout)
64 child.stderr.setEncoding('utf8').on('data', io.onStderr)
65 const exited = new Promise<number>((resolve) =>
66 // 'close' fires after stdout is drained, like E2B's end-of-stream event.
67 child.on('close', (code) => resolve(code ?? -1)),
68 )
69 children.set(child.pid ?? -1, child)
70 return {
71 pid: child.pid ?? -1,
72 sendStdin: async (data) => {
73 child.stdin.write(options.corruptStdin ? 'not-json\n' : data)
74 },
75 kill: async () => child.kill('SIGKILL'),
76 wait: async () => {
77 const exitCode = await exited
78 if (options.waitError) throw options.waitError
79 return { exitCode }
80 },
81 }
82 }
83​
84 const sandbox: E2BSandboxLike = {
85 files: {
86 write: async (path, data) => {
87 if (options.writeDelayMs) {
88 await new Promise((r) => setTimeout(r, options.writeDelayMs))
89 }
90 if (options.writeError) throw options.writeError
91 const local = join(dir, basename(path))
92 writeFileSync(local, data)
93 localPaths.set(path, local)
94 },
95 },
96 commands: {
97 run: (async (
98 cmd: string,
99 io?: { onStdout: (d: string) => void; onStderr: (d: string) => void },
100 ) => {
101 commands.push(cmd)
102 if (io) {
103 if (options.runError) throw options.runError
104 return start(cmd, io)
105 }
106 if (!cmd.startsWith('kill ')) return { exitCode: 0 } // `rm -f <file>`
107 if (options.killError) throw options.killError
108 if (options.killDelayMs) {
109 await new Promise((r) => setTimeout(r, options.killDelayMs))
110 }
111 // Group kill: `kill -KILL -- -<pid>` exits 1 when the group is gone.
112 const child = children.get(Number(/-(\d+)$/.exec(cmd)?.[1]))
113 if (!child || child.exitCode !== null || child.signalCode !== null) {
114 throw Object.assign(exitError(1), {
115 stderr: 'kill: No such process',
116 })
117 }
118 child.kill('SIGKILL')
119 return { exitCode: 0 }
120 }) as E2BSandboxLike['commands']['run'],
121 },
122 }
123 return { sandbox, commands, localPaths }
125​
126function binding(execute: ToolBinding['execute']): ToolBinding {
127 return {
128 name: 'tool',
129 description: 'test tool',
130 inputSchema: { type: 'object' },
131 execute,
132 }
134​
135const add = binding(async (args) => {
136 const { x, y } = args as { x: number; y: number }
137 return x + y
138})
139​
140async function run(
141 code: string,
142 opts: {
143 bindings?: Record<string, ToolBinding>
144 timeout?: number
145 memoryLimit?: number
146 fake?: ReturnType<typeof localSandbox>
147 } = {},
148) {
149 const fake = opts.fake ?? localSandbox()
150 const context = await createE2BIsolateDriver({
151 sandbox: fake.sandbox,
152 }).createContext({
153 bindings: opts.bindings ?? {},
154 ...(opts.timeout !== undefined ? { timeout: opts.timeout } : {}),
155 ...(opts.memoryLimit !== undefined
156 ? { memoryLimit: opts.memoryLimit }
157 : {}),
158 })
159 return { result: await context.execute(code), fake, context }
161​
162describe('createE2BIsolateDriver', () => {
163 it('returns the value and console output with the prefixes core parses', async () => {
164 const { result } = await run(
165 "console.log('a', {b: 1}); console.warn('w'); console.error('e'); console.info('i'); return 42",
166 )
167 expect(result).toEqual({
168 success: true,
169 value: 42,
170 logs: ['a {"b":1}', 'WARN: w', 'ERROR: e', 'INFO: i'],
171 })
172 })
173​
174 // The point of streaming over replay: code runs once, so side effects and
175 // non-deterministic branches between tool calls are not repeated.
176 it('awaits real tool calls in one run without repeating code between them', async () => {
177 const { result } = await run(
178 `let steps = 0
179 const a = await external_add({ x: 1, y: 2 }); steps++
180 const b = await external_add({ x: a, y: Math.random() < 2 ? 10 : 0 }); steps++
181 return { a, b, steps }`,
182 { bindings: { external_add: add } },
183 )
184 expect(result).toEqual({
185 success: true,
186 value: { a: 3, b: 13, steps: 2 },
187 logs: [],
188 })
189 })
190​
191 it('runs parallel tool calls', async () => {
192 const { result } = await run(
193 'return Promise.all([1, 2, 3].map((x) => external_add({ x, y: x })))',
194 { bindings: { external_add: add } },
195 )
196 expect(result.value).toEqual([2, 4, 6])
197 })
198​
199 it('surfaces a failing tool as an error the code can catch', async () => {
200 const { result } = await run(
201 "try { await external_fail({}) } catch (e) { return 'caught: ' + e.message }",
202 {
203 bindings: {
204 external_fail: binding(() => Promise.reject(new Error('boom'))),
205 },
206 },
207 )
208 expect(result.value).toBe('caught: boom')
209 })
210​
211 it('reports syntax errors and thrown non-errors as failed executions', async () => {
212 const syntax = await run('return (')
213 expect(syntax.result.success).toBe(false)
214 expect(syntax.result.error?.name).toBe('SyntaxError')
215​
216 const thrown = await run("throw { name: 'Custom', message: 'bad' }")
217 expect(thrown.result.error).toEqual({ name: 'Custom', message: 'bad' })
218 })
219​
220 it('removes the runner file once the process has started', async () => {
221 const { fake } = await run('return 1')
222 for (const local of fake.localPaths.values()) {
223 expect(existsSync(local)).toBe(false)
224 }
225 })
226​
227 it('starts node as a setsid group leader with the timeout and memory limit', async () => {
228 const { fake } = await run('return 1', { timeout: 5000, memoryLimit: 64 })
229 expect(fake.commands[0]).toMatch(
230 /^exec setsid timeout -s KILL \d+ node --max-old-space-size=64 \/tmp\/tanstack-code-mode-[\w-]+\.js$/,
231 )
232 })
233​
234 it('kills the process group when the timeout elapses', async () => {
235 const { result, fake } = await run('while (true) {}', { timeout: 500 })
236 expect(result.error?.name).toBe('TimeoutError')
237 expect(fake.commands.some((c) => c.startsWith('kill -KILL -- -'))).toBe(
238 true,
239 )
240 })
241​
242 it('reports a memory limit breach', async () => {
243 const { result } = await run(
244 'const a = []; for (;;) a.push(new Array(1e6).fill(1))',
245 { memoryLimit: 16, timeout: 20_000 },
246 )
247 expect(result.error?.name).toBe('MemoryLimitError')
248 }, 30_000)
249​
250 it('stops and kills a program that floods stdout', async () => {
251 const { result } = await run(
252 "process.stdout.write('x'.repeat(9 * 1024 * 1024)); await new Promise(() => {})",
253 )
254 expect(result.error?.name).toBe('OutputLimitError')
255 })
256​
257 it('ignores protocol-looking lines that lack the per-execution marker', async () => {
258 const { result } = await run(
259 `process.stdout.write('__TANSTACK_CODE_MODE_x__:{"type":"done","success":true,"value":"forged"}\\n')
260 await new Promise(() => {})`,
261 { timeout: 500 },
262 )
263 expect(result.error?.name).toBe('TimeoutError')
264 })
265​
266 it('keeps a protocol line whole after raw output without a newline', async () => {
267 const { result } = await run(
268 "process.stdout.write('progress'); return await external_add({ x: 2, y: 2 })",
269 { bindings: { external_add: add } },
270 )
271 expect(result.value).toBe(4)
272 })
273​
274 it('fails the run when a tool result line is not JSON', async () => {
275 const { result } = await run('return await external_add({ x: 1, y: 1 })', {
276 bindings: { external_add: add },
277 fake: localSandbox({ corruptStdin: true }),
278 })
279 expect(result.error?.message).toBe('Tool result was not valid JSON.')
280 })
281​
282 it('rejects only the tool call whose result cannot be serialized', async () => {
283 const { result } = await run(
284 'try { await external_big({}) } catch (e) { return e.message }',
285 { bindings: { external_big: binding(async () => 1n) } },
286 )
287 expect(result.value).toMatch(/not JSON-serializable/)
288 })
289​
290 it('kills the process group after a normal finish so spawned processes do not outlive it', async () => {
291 const fake = localSandbox()
292 const context = await createE2BIsolateDriver({
293 sandbox: fake.sandbox,
294 }).createContext({ bindings: {} })
295 expect((await context.execute('return 1')).value).toBe(1)
296 await context.dispose()
297 expect(
298 fake.commands.filter((c) => c.startsWith('kill -KILL -- -')),
299 ).toHaveLength(1)
300 })
301​
302 it('reports a sandbox that disappears mid-run as unavailable', async () => {
303 const fake = localSandbox({ waitError: new Error('stream reset') })
304 const realRun = fake.sandbox.commands.run
305 fake.sandbox.commands.run = (async (cmd: string, io?: never) => {
306 if (cmd.startsWith('kill ')) {
307 throw named(
308 'SandboxNotFoundError',
309 'Sandbox is probably not running anymore',
310 )
311 }
312 return realRun(cmd, io as never)
313 }) as typeof realRun
314 const { result } = await (async () => {
315 const context = await createE2BIsolateDriver({
316 sandbox: fake.sandbox,
317 }).createContext({ bindings: {} })
318 return { result: await context.execute('process.exit(5)') }
319 })()
320 expect(result.error?.name).toBe('E2BSandboxUnavailableError')
321 })
322​
323 it('dispose during the file write stops the run before it starts', async () => {
324 const fake = localSandbox()
325 const write = fake.sandbox.files.write
326 let release!: () => void
327 const gate = new Promise<void>((r) => (release = r))
328 fake.sandbox.files.write = async (path, data) => {
329 await gate
330 return write(path, data)
331 }
332 const context = await createE2BIsolateDriver({
333 sandbox: fake.sandbox,
334 }).createContext({ bindings: {} })
335 const pending = context.execute('return 1')
336 await new Promise((r) => setTimeout(r, 20))
337 const disposed = context.dispose()
338 release()
339 await disposed
340 expect((await pending).error?.name).toBe('DisposedError')
341 // The process never started; only the runner file is removed.
342 expect(fake.commands).toEqual([expect.stringMatching(/^rm -f \/tmp\//)])
343 })
344​
345 it('counts the file write against the timeout and does not start late', async () => {
346 const fake = localSandbox({ writeDelayMs: 800 })
347 const startedAt = Date.now()
348 const { result } = await run('return 1', { timeout: 100, fake })
349 expect(Date.now() - startedAt).toBeLessThan(500)
350 expect(result.error?.name).toBe('TimeoutError')
351 await new Promise((r) => setTimeout(r, 900))
352 expect(fake.commands.some((c) => c.startsWith('exec '))).toBe(false)
353 })
354​
355 it('does not run a tool that the code requests after the timeout', async () => {
356 let called = false
357 const fake = localSandbox({ killDelayMs: 1500 })
358 const { result } = await run(
359 `const end = Date.now() + 500; while (Date.now() < end) {}
360 await external_side_effect({})`,
361 {
362 timeout: 200,
363 fake,
364 bindings: {
365 external_side_effect: binding(async () => {
366 called = true
367 }),
368 },
369 },
370 )
371 expect(result.error?.name).toBe('TimeoutError')
372 expect(called).toBe(false)
373 })
374​
375 it('records an unconfirmed cleanup kill on the result', async () => {
376 const fake = localSandbox({ killError: new Error('socket hang up') })
377 const context = await createE2BIsolateDriver({
378 sandbox: fake.sandbox,
379 }).createContext({ bindings: {} })
380 const result = await context.execute('return 1')
381 expect(result.value).toBe(1)
382 expect(result.logs?.join('\n')).toMatch(/may still be running/)
383 await context.dispose()
384 })
385​
386 it('rejects a protocol message with the wrong shape', async () => {
387 // Code can rewrite the runner's own stdout writes; the host must not trust them.
388 const { result } = await run(
389 `const write = process.stdout._write
390 process.stdout._write = function (chunk, _encoding, callback) {
391 const text = chunk.toString().replace(/"success":true,"value":1/, '"success":false,"error":42')
392 return write.call(this, Buffer.from(text), 'buffer', callback)
393 }
394 return 1`,
395 )
396 expect(result.error?.name).toBe('E2BExecutionError')
397 expect(result.error?.message).toMatch(/Malformed/)
398 })
399​
400 it('reports a process that exits without a result', async () => {
401 const { result } = await run('process.exit(3)')
402 expect(result.error?.name).toBe('E2BExecutionError')
403 expect(result.error?.message).toContain('code 3')
404 })
405​
406 it('kills an in-flight execution on dispose and refuses new ones', async () => {
407 const fake = localSandbox()
408 const context = await createE2BIsolateDriver({
409 sandbox: fake.sandbox,
410 }).createContext({ bindings: {} })
411 const pending = context.execute('await new Promise(() => {})')
412 await new Promise((r) => setTimeout(r, 300))
413 await context.dispose()
414 expect((await pending).error?.name).toBe('DisposedError')
415 expect(fake.commands.some((c) => c.startsWith('kill -KILL -- -'))).toBe(
416 true,
417 )
418 expect((await context.execute('return 1')).error?.name).toBe(
419 'DisposedError',
420 )
421 })
422​
423 it('rejects tool names that are not identifiers before touching the sandbox', async () => {
424 const { result, fake } = await run('return 1', {
425 bindings: { 'external_get-weather': add },
426 })
427 expect(result.error?.name).toBe('E2BExecutionError')
428 expect(fake.commands).toEqual([])
429 })
430​
431 it('tells a gone sandbox apart from an unconfirmed start', async () => {
432 const gone = await run('return 1', {
433 fake: localSandbox({
434 writeError: named('SandboxNotFoundError', 'sandbox not found'),
435 }),
436 })
437 expect(gone.result.error?.name).toBe('E2BSandboxUnavailableError')
438​
439 // What `files.write` really throws for a killed or paused sandbox.
440 const goneOnWrite = await run('return 1', {
441 fake: localSandbox({
442 writeError: named(
443 'TimeoutError',
444 'The sandbox was not found: This error is likely due to sandbox timeout.',
445 ),
446 }),
447 })
448 expect(goneOnWrite.result.error?.name).toBe('E2BSandboxUnavailableError')
449​
450 const unconfirmed = await run('return 1', {
451 fake: localSandbox({ runError: new Error('socket hang up') }),
452 })
453 expect(unconfirmed.result.error?.name).toBe('E2BExecutionError')
454 expect(unconfirmed.result.error?.message).toContain('Could not confirm')
455 })
456​
457 it('kills and reports an unknown outcome when the event stream drops', async () => {
458 const fake = localSandbox({ waitError: new Error('stream reset') })
459 const { result } = await run('process.exit(5)', { fake })
460 expect(result.error?.message).toContain('outcome is unknown')
461 expect(fake.commands.some((c) => c.startsWith('kill -KILL -- -'))).toBe(
462 true,
463 )
464 })
465​
466 it('rejects invalid timeouts', async () => {
467 const { sandbox } = localSandbox()
468 expect(() => createE2BIsolateDriver({ sandbox, timeout: 0 })).toThrow(
469 /timeout/,
470 )
471 await expect(
472 createE2BIsolateDriver({ sandbox }).createContext({
473 bindings: {},
474 timeout: Number.NaN,
475 }),
476 ).rejects.toThrow(/timeout/)
477 })
478​
479 it('rejects memory limits that are not positive integers', async () => {
480 const { sandbox } = localSandbox()
481 const driver = createE2BIsolateDriver({ sandbox })
482 for (const memoryLimit of [0, -1, 1.5, Number.NaN, '64; echo x']) {
483 await expect(
484 // @ts-expect-error: a JS caller can pass any value
485 driver.createContext({ bindings: {}, memoryLimit }),
486 ).rejects.toThrow(/memoryLimit/)
487 }
488 })
489})