Open History to see the last commit
1import { wrapCode } from '@tanstack/ai-code-mode'
2import {
3 isFatalQuickJSLimitError,
4 memoryLimitError,
5 normalizeError,
6} from './error-normalizer'
7import type {
8 ExecutionResult,
9 IsolateContext,
10 NormalizedError,
11 ToolBinding,
12} from '@tanstack/ai-code-mode'
13import type * as QuickJSBun from 'quickjs-bun'
14import type { Deferred, JSContext, JSRuntime, JSValue } from 'quickjs-bun'
15
16/**
17 * The `quickjs-bun` module namespace. The module is imported dynamically by
18 * the driver (it only loads under the Bun runtime), so the classes and enums
19 * it exports are threaded through here instead of being imported statically.
20 */
21export type QuickJSBunModule = typeof QuickJSBun
22
23/**
24 * An in-flight host tool call. The sandbox holds a QuickJS promise that is
25 * resolved from the host once the binding's `execute` settles; `settled`
26 * lets the execution loop wait for host work without polling.
27 */
28interface HostTask {
29 deferred: Deferred
30 settle: () => void
31 settled: Promise<void>
32}
33
34/**
35 * Result envelope passed across the sandbox boundary as a JSON string.
36 */
37interface ToolResultEnvelope {
38 success: boolean
39 value?: unknown
40 error?: string
41}
42
43/**
44 * Caps on captured console output. Logs are held on the host and flow back
45 * to the model, so an unbounded `while (true) console.log(...)` loop in
46 * untrusted code could grow host memory without ever tripping the sandbox
47 * heap limit (the sandbox only holds one string at a time). Once either cap
48 * is reached a single truncation marker is appended and further output is
49 * dropped for the rest of the execution.
50 */
51const MAX_LOG_ENTRIES = 10_000
52// Measured in UTF-16 code units (`String.length`), not bytes: a cheap, bounded
53// proxy for output size. Worst-case multi-byte content can reach ~3-4x this in
54// real bytes, which is still safely bounded.
55const MAX_LOG_CHARS = 1_000_000
56
57/** Default ceiling on host tool-call invocations per execution. */
58export const DEFAULT_MAX_TOOL_CALLS = 1000
59
60/**
61 * Safety cap on how many stale promise reactions to flush before a run. A
62 * bounded loop guards against a pathological job that perpetually reschedules
63 * itself; a healthy queue drains in far fewer iterations.
64 */
65const MAX_STALE_JOB_DRAIN = 10_000
66
67/** Placeholder used when a console argument cannot be coerced to a string. */
68const UNPRINTABLE_LOG_VALUE = '[unprintable]'
69
70/**
71 * Rebuild a throwable carrying a normalized error's name/message/stack so it
72 * round-trips through `normalizeError` (which preserves the name, keeping
73 * fatal-limit classification intact).
74 */
75function normalizedErrorToThrowable(error: NormalizedError): Error {
76 const throwable = new Error(error.message)
77 throwable.name = error.name
78 if (error.stack !== undefined) throwable.stack = error.stack
79 return throwable
80}
81
82/**
83 * Generic wrapper factory evaluated once per context. Tool functions are
84 * created by calling it with the host implementation and installed on the
85 * global object with `setGlobal`, so binding names are never interpolated
86 * into evaluated source code.
87 */
88const TOOL_WRAPPER_FACTORY = `(function (impl) {
89 return async function (input) {
90 const resultJson = await impl(JSON.stringify(input ?? {}));
91 const result = JSON.parse(resultJson);
92 if (!result.success) {
93 throw new Error(result.error);
94 }
95 return result.value;
96 };
97})`
98
99/**
100 * IsolateContext implementation backed by a dedicated native QuickJS
101 * runtime + context pair (via `quickjs-bun`).
102 */
103export class QuickJSBunIsolateContext implements IsolateContext {
104 private readonly quickjs: QuickJSBunModule
105 private readonly runtime: JSRuntime
106 private readonly vm: JSContext
107 private readonly timeout: number
108 private readonly maxToolCalls: number
109 private readonly logs: Array<string> = []
110 private logChars = 0
111 private logTruncated = false
112 private readonly tasks = new Set<HostTask>()
113 private toolCallsUsed = 0
114 private disposed = false
115 /**
116 * A VM-level failure raised while settling a host tool call (e.g. the
117 * sandbox heap was exhausted when allocating the result string). It is
118 * surfaced through the execution loop rather than left to escape the
119 * floating settle callback as an unhandled rejection.
120 */
121 private hostSettleError: NormalizedError | undefined
122 /**
123 * Serializes executions on this context. A context only ever runs one
124 * program at a time; QuickJS contexts are single-threaded and the
125 * execution loop drives the runtime's job queue.
126 */
127 private execQueue: Promise<void> = Promise.resolve()
128
129 /**
130 * Wrap a live `quickjs-bun` runtime + context pair, then install the captured
131 * `console` and the host tool bindings on the sandbox global before the first
132 * `execute`. Takes ownership of `runtime`/`vm`; `dispose()` frees them.
133 */
134 constructor(options: {
135 quickjs: QuickJSBunModule
136 runtime: JSRuntime
137 vm: JSContext
138 timeout: number
139 maxToolCalls: number
140 bindings: Record<string, ToolBinding>
141 }) {
142 this.quickjs = options.quickjs
143 this.runtime = options.runtime
144 this.vm = options.vm
145 this.timeout = options.timeout
146 this.maxToolCalls = options.maxToolCalls
147 this.installConsole()
148 this.installBindings(options.bindings)
149 }
150
151 /**
152 * Run `code` to completion inside the sandbox and return its result.
153 * Executions are serialized through a per-context queue, so a second
154 * `execute` (or a concurrent `dispose`) waits for the in-flight run rather
155 * than interleaving. Console output produced during the run is captured and
156 * returned in `logs`. Never throws: tool errors, timeouts, and limit
157 * violations come back as a failed `ExecutionResult` with a normalized error.
158 */
159 async execute<T = unknown>(code: string): Promise<ExecutionResult<T>> {
160 if (this.disposed) {
161 return this.disposedResult()
162 }
163
164 // Serialize through the per-context queue so a second execute (or a
165 // concurrent dispose) never interleaves with an in-flight run.
166 let release!: () => void
167 const myTurn = new Promise<void>((resolve) => {
168 release = resolve
169 })
170 const waitForPrev = this.execQueue
171 this.execQueue = myTurn
172
173 await waitForPrev
174
175 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- dispose() may run while awaiting the queue
176 if (this.disposed) {
177 release()
178 return this.disposedResult()
179 }
180
181 // A prior aborted or timed-out execution can leave promise reactions queued
182 // in the VM. Left in place, the loop in runToCompletion would run them
183 // first and attribute their console output, tool-call budget, and
184 // wall-clock to this run. Flush them now — and abandon any host tool calls
185 // a flushed reaction kicked off — before installing this run's state.
186 this.drainStaleJobs()
187 this.abortTasks()
188
189 this.logs.length = 0
190 this.logChars = 0
191 this.logTruncated = false
192 this.toolCallsUsed = 0
193 this.hostSettleError = undefined
194
195 try {
196 const value = await this.runToCompletion(wrapCode(code))
197 return {
198 success: true,
199 value: value as T,
200 logs: [...this.logs],
201 }
202 } catch (error) {
203 return this.fail(error)
204 } finally {
205 // Abandon host tool calls that are still in flight (e.g. after a
206 // timeout) so a late completion cannot touch the VM.
207 this.abortTasks()
208 release()
209 }
210 }
211
212 /**
213 * Release the underlying QuickJS runtime and abandon any in-flight host tool
214 * calls. Waits for a running execution to finish first (the execution loop
215 * touches native handles throughout). Idempotent.
216 */
217 async dispose(): Promise<void> {
218 if (this.disposed) return
219
220 // Wait for any in-flight execution to finish before freeing the
221 // runtime; the execution loop touches native handles throughout.
222 await this.execQueue
223
224 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- a fatal limit error may dispose the VM while awaiting the queue
225 if (this.disposed) return
226 this.disposed = true
227 this.abortTasks()
228 this.runtime.dispose()
229 }
230
231 /**
232 * Evaluate the wrapped program and drive the QuickJS job queue (and any
233 * in-flight host tool calls) until the program's promise settles or the
234 * deadline passes. Returns the parsed result value.
235 */
236 private async runToCompletion(wrappedCode: string): Promise<unknown> {
237 const { QuickJSPromiseState, JSException } = this.quickjs
238 const deadline = performance.now() + this.timeout
239
240 // The synchronous portion of the program is bounded by the QuickJS
241 // interrupt handler; async continuations are bounded by the deadline
242 // checks in the loop below.
243 const resultHandle = this.vm.evalCode(wrappedCode, {
244 filename: '<code-mode>',
245 timeoutMs: this.timeout,
246 })
247
248 let settledHandle: JSValue
249 try {
250 if (resultHandle.promiseState === QuickJSPromiseState.NOT_PROMISE) {
251 // wrapCode always produces an async IIFE, but stay defensive.
252 settledHandle = resultHandle.dup()
253 } else {
254 for (;;) {
255 const state = resultHandle.promiseState
256 if (state === QuickJSPromiseState.FULFILLED) {
257 settledHandle = resultHandle.promiseResult()
258 break
259 }
260 if (state === QuickJSPromiseState.REJECTED) {
261 throw new JSException(resultHandle.promiseResult())
262 }
263
264 // A host tool call failed to settle the sandbox promise because
265 // the VM itself errored (e.g. OOM allocating the result string).
266 // Surface it here so fail() can classify it and release the VM if
267 // it was fatal, rather than letting it escape as an unhandled
268 // rejection from the floating settle callback.
269 if (this.hostSettleError !== undefined) {
270 throw normalizedErrorToThrowable(this.hostSettleError)
271 }
272
273 const remainingMs = deadline - performance.now()
274 if (remainingMs <= 0) {
275 throw this.timeoutError()
276 }
277
278 // Run one queued microtask (promise reaction) if there is one...
279 if (this.runtime.executePendingJob(Math.max(1, remainingMs))) {
280 continue
281 }
282
283 // ...otherwise the program is waiting on host work. A settle
284 // failure raised while draining the last task is caught by the
285 // hostSettleError check at the top of the next iteration before we
286 // ever reach this branch.
287 if (this.tasks.size === 0) {
288 throw new Error(
289 'Code execution is pending on a promise that no host work will ever resolve',
290 )
291 }
292 await this.waitForAnyTask(remainingMs)
293 }
294 }
295 } finally {
296 resultHandle.dispose()
297 }
298
299 try {
300 const dumped = this.vm.dump(settledHandle)
301
302 // The wrapper returns JSON.stringify(userResult) — parse it back.
303 // A bare string that isn't valid JSON is returned as-is, and code
304 // that returned nothing yields undefined.
305 if (typeof dumped === 'string') {
306 try {
307 return JSON.parse(dumped)
308 } catch {
309 return dumped
310 }
311 }
312 return dumped
313 } finally {
314 settledHandle.dispose()
315 }
316 }
317
318 /** Wait until any in-flight host tool call settles, or `timeoutMs` passes. */
319 private async waitForAnyTask(timeoutMs: number): Promise<void> {
320 const settled = Array.from(this.tasks, (task) => task.settled)
321 let timer: ReturnType<typeof setTimeout> | undefined
322 try {
323 await Promise.race([
324 Promise.race(settled),
325 new Promise<void>((resolve) => {
326 // Resolve (not reject): the execution loop re-checks the deadline.
327 timer = setTimeout(resolve, Math.max(1, timeoutMs))
328 }),
329 ])
330 } finally {
331 clearTimeout(timer)
332 }
333 }
334
335 /**
336 * Install a `console` object on the sandbox global whose `log`/`error`/
337 * `warn`/`info` methods funnel into the host log buffer. Non-`log` levels are
338 * prefixed (e.g. `ERROR: …`) to mirror the other drivers' capture format.
339 */
340 private installConsole(): void {
341 const { vm } = this
342 const methods: Array<[name: string, prefix: string]> = [
343 ['log', ''],
344 ['error', 'ERROR'],
345 ['warn', 'WARN'],
346 ['info', 'INFO'],
347 ]
348
349 const consoleObj = vm.newObject()
350 try {
351 for (const [method, prefix] of methods) {
352 const fn = vm.newFunction((...args) => {
353 const parts = args.map((arg) => this.stringifyConsoleArg(arg))
354 const msg = prefix ? `${prefix}: ${parts.join(' ')}` : parts.join(' ')
355 this.pushLog(msg)
356 })
357 try {
358 consoleObj.setProp(method, fn)
359 } finally {
360 fn.dispose()
361 }
362 }
363 vm.setGlobal('console', consoleObj)
364 } finally {
365 consoleObj.dispose()
366 }
367 }
368
369 /**
370 * Coerce a console argument to a string. quickjs-bun's `JSValue.toString()`
371 * asserts the value is already a string and throws for numbers, objects,
372 * booleans, etc.; `coerceToString()` performs a real `ToString` (matching
373 * the WASM driver's `getString`). A coercion that throws (e.g. a symbol or
374 * a `toString` that throws) degrades to a placeholder rather than aborting
375 * the whole execution.
376 */
377 private stringifyConsoleArg(arg: JSValue): string {
378 const { JSException } = this.quickjs
379 try {
380 const coerced = arg.coerceToString()
381 try {
382 return coerced.toString()
383 } finally {
384 coerced.dispose()
385 }
386 } catch (error) {
387 if (error instanceof JSException) error.dispose()
388 return UNPRINTABLE_LOG_VALUE
389 }
390 }
391
392 /** Append a captured log line, enforcing the entry-count and byte caps. */
393 private pushLog(msg: string): void {
394 if (this.logTruncated) return
395 if (
396 this.logs.length >= MAX_LOG_ENTRIES ||
397 this.logChars + msg.length > MAX_LOG_CHARS
398 ) {
399 this.logTruncated = true
400 this.logs.push('[log output truncated]')
401 return
402 }
403 this.logs.push(msg)
404 this.logChars += msg.length
405 }
406
407 /**
408 * Install each host tool `binding` as an async function on the sandbox
409 * global. Wrappers are produced by evaluating `TOOL_WRAPPER_FACTORY` once and
410 * calling it per binding, so binding names are never interpolated into
411 * evaluated source. No-op when there are no bindings.
412 */
413 private installBindings(bindings: Record<string, ToolBinding>): void {
414 const { vm } = this
415 const entries = Object.entries(bindings)
416 if (entries.length === 0) return
417
418 const factory = vm.evalCode(TOOL_WRAPPER_FACTORY, {
419 filename: '<tool-wrapper>',
420 })
421 try {
422 for (const [name, binding] of entries) {
423 const impl = vm.newFunction((argsHandle) =>
424 this.runBinding(binding, argsHandle),
425 )
426 try {
427 const wrapped = vm.callFunction(factory, vm.undefined, impl)
428 try {
429 vm.setGlobal(name, wrapped)
430 } finally {
431 wrapped.dispose()
432 }
433 } finally {
434 impl.dispose()
435 }
436 }
437 } finally {
438 factory.dispose()
439 }
440 }
441
442 /**
443 * Host side of a tool call. Invoked synchronously from inside the VM;
444 * returns a QuickJS promise immediately and settles it from the host
445 * once `binding.execute` finishes. Never rejects the promise for tool
446 * errors — failures travel in the JSON envelope so the sandbox wrapper
447 * can rethrow them as regular errors.
448 */
449 private runBinding(
450 binding: ToolBinding,
451 argsHandle: JSValue | undefined,
452 ): JSValue {
453 const { vm } = this
454
455 // Bound the number of host tool calls per execution. Untrusted sandbox
456 // code can otherwise fan out (e.g. `Promise.all` over a huge array) into
457 // unbounded concurrent host work — the deadline only bounds wall-clock,
458 // not the burst. Throwing here surfaces as a catchable error at the call
459 // site inside the sandbox.
460 if (this.toolCallsUsed >= this.maxToolCalls) {
461 throw new Error(
462 `Exceeded the maximum of ${this.maxToolCalls} tool calls per execution`,
463 )
464 }
465 this.toolCallsUsed++
466
467 const deferred = vm.newPromise()
468 const promise = deferred.promise.dup()
469
470 let settle: () => void = () => undefined
471 const settledPromise = new Promise<void>((resolve) => {
472 settle = resolve
473 })
474 const task: HostTask = { deferred, settle, settled: settledPromise }
475 this.tasks.add(task)
476
477 const settleWith = (envelope: ToolResultEnvelope): void => {
478 // The task may have been abandoned by a timeout or dispose — never
479 // touch the VM in that case.
480 if (this.disposed || !this.tasks.has(task)) return
481 this.tasks.delete(task)
482 try {
483 let json: string
484 try {
485 json = JSON.stringify(envelope)
486 } catch (error) {
487 json = JSON.stringify({
488 success: false,
489 error: `Tool result is not JSON-serializable: ${
490 error instanceof Error ? error.message : String(error)
491 }`,
492 })
493 }
494 const handle = vm.newString(json)
495 try {
496 deferred.resolve(handle)
497 } finally {
498 handle.dispose()
499 }
500 } catch (error) {
501 // Allocating the result string or resolving the promise can fail if
502 // the sandbox heap is exhausted. Record it so the execution loop can
503 // classify it (and release the VM if fatal) instead of letting it
504 // escape the floating async callback as an unhandled rejection.
505 this.hostSettleError ??= this.toNormalizedError(error)
506 } finally {
507 deferred.dispose()
508 task.settle()
509 }
510 }
511
512 // The wrapper always passes a JSON string, but degrade gracefully if
513 // the handle dumps to something else. A non-string dump is harmless — the
514 // tool just sees empty args — but a *thrown* dump is not: it means the
515 // sandbox heap was exhausted while materializing the args string.
516 let argsJson = '{}'
517 try {
518 const dumped = vm.dump(argsHandle ?? vm.undefined)
519 if (typeof dumped === 'string') {
520 argsJson = dumped
521 }
522 } catch (error) {
523 // Running the tool now would invoke a real host side effect (e.g.
524 // `readFile`/`deleteRecords`) with empty `{}` args instead of the
525 // caller's real inputs, and the underlying OOM would go unclassified.
526 // Record it for the execution loop to surface (and release the VM if
527 // fatal), and abandon this tool call instead of executing it.
528 // `toNormalizedError` disposes the owned JSException value.
529 this.hostSettleError ??= this.toNormalizedError(error)
530 this.tasks.delete(task)
531 deferred.dispose()
532 task.settle()
533 return promise
534 }
535
536 void (async () => {
537 let envelope: ToolResultEnvelope
538 try {
539 const args: unknown = JSON.parse(argsJson)
540 const value = await binding.execute(args)
541 envelope = { success: true, value }
542 } catch (error) {
543 envelope = {
544 success: false,
545 error: error instanceof Error ? error.message : String(error),
546 }
547 }
548 settleWith(envelope)
549 })()
550
551 return promise
552 }
553
554 /**
555 * Flush promise reactions left queued by a prior aborted/timed-out execution
556 * so they cannot bleed into the next run. Runs the queue to completion and
557 * discards the effects (the caller resets per-run state and re-aborts tasks
558 * immediately after). Bounded, and swallows a throwing reaction so a single
559 * bad job cannot abort the whole drain.
560 */
561 private drainStaleJobs(): void {
562 for (let i = 0; i < MAX_STALE_JOB_DRAIN; i++) {
563 try {
564 if (!this.runtime.executePendingJob(1)) return
565 } catch {
566 // A stale reaction threw; discard it and keep draining the rest.
567 }
568 }
569 }
570
571 /** Abandon all in-flight host tool calls and release their VM handles. */
572 private abortTasks(): void {
573 for (const task of this.tasks) {
574 task.deferred.dispose()
575 task.settle()
576 }
577 this.tasks.clear()
578 }
579
580 /**
581 * Build a failed `ExecutionResult` from a thrown value, attaching the
582 * captured logs. If the error is a fatal QuickJS limit (memory/stack), the
583 * runtime is released first since it may be left unusable.
584 */
585 private fail(error: unknown): ExecutionResult<never> {
586 const normalized = this.toNormalizedError(error)
587 if (isFatalQuickJSLimitError(normalized)) {
588 this.releaseVmAfterFatalLimit()
589 }
590 return {
591 success: false,
592 error: normalized,
593 logs: [...this.logs],
594 }
595 }
596
597 /**
598 * Convert any thrown value into a `NormalizedError`, unwrapping a quickjs-bun
599 * `JSException`: a bare `null` exception value (heap too exhausted to
600 * allocate an Error) becomes a `MemoryLimitError`, and a thrown plain
601 * object/array has its `message`/`name` recovered so the model still gets
602 * useful feedback — parity with the WASM driver. Always disposes the owned
603 * exception value.
604 */
605 private toNormalizedError(error: unknown): NormalizedError {
606 const { JSException } = this.quickjs
607 if (error instanceof JSException) {
608 try {
609 const value = error.value
610 // QuickJS throws a bare `null` exception value when the heap is too
611 // exhausted to allocate an Error object. (A literal `throw null` in
612 // sandbox code is indistinguishable and is treated the same way.)
613 if (value.type === 'null') {
614 return memoryLimitError(error.stack)
615 }
616 // A thrown plain object/array surfaces through quickjs-bun's
617 // JSException as the generic "QuickJS object was thrown"; recover its
618 // `message` (and `name`) so the model still gets useful feedback for
619 // self-correction — parity with the WASM driver.
620 if (value.type === 'object' || value.type === 'array') {
621 const message = this.readValueProp(value, 'message')
622 if (message !== undefined) {
623 // Route the recovered name/message back through normalizeError so a
624 // fatal limit thrown as an Error *object* (with some heap headroom
625 // QuickJS throws `InternalError: out of memory`, and stack overflow
626 // surfaces as an `InternalError`/`RangeError` object rather than a
627 // bare `null`) is still classified as MemoryLimit/StackOverflow and
628 // releases the VM, instead of being returned verbatim and letting
629 // an exhausted VM be reused.
630 const recovered = new Error(message)
631 recovered.name = this.readValueProp(value, 'name') ?? error.name
632 if (error.stack !== undefined) recovered.stack = error.stack
633 return normalizeError(recovered)
634 }
635 }
636 return normalizeError(error)
637 } finally {
638 error.dispose()
639 }
640 }
641 return normalizeError(error)
642 }
643
644 /**
645 * Read a string property from a thrown QuickJS value, tolerating throwing
646 * getters (the value is attacker-controlled). Returns undefined on any
647 * failure and releases the owned exception in that case.
648 */
649 private readValueProp(value: JSValue, name: string): string | undefined {
650 try {
651 return value.errorProperty(name)
652 } catch (error) {
653 if (error instanceof this.quickjs.JSException) error.dispose()
654 return undefined
655 }
656 }
657
658 /**
659 * After a memory/stack limit error the QuickJS runtime may be left in an
660 * unusable state — release it eagerly so the host process reclaims the
661 * native memory. Matches the QuickJS WASM driver's behavior.
662 */
663 private releaseVmAfterFatalLimit(): void {
664 if (this.disposed) return
665 this.disposed = true
666 this.abortTasks()
667 try {
668 this.runtime.dispose()
669 } catch {
670 // ignore if the runtime is already torn down
671 }
672 }
673
674 /** Construct the `TimeoutError` thrown when an execution exceeds its deadline. */
675 private timeoutError(): Error {
676 const error = new Error(`Code execution timed out after ${this.timeout}ms`)
677 error.name = 'TimeoutError'
678 return error
679 }
680
681 /** The failed `ExecutionResult` returned once the context has been disposed. */
682 private disposedResult(): ExecutionResult<never> {
683 return {
684 success: false,
685 error: {
686 name: 'DisposedError',
687 message: 'Context has been disposed',
688 },
689 logs: [],
690 }
691 }
692}