Open History to see the last commit
1import {
2 RELEASE_SYNC,
3 getQuickJS,
4 newQuickJSWASMModule,
5 newVariant,
6} from 'quickjs-emscripten'
7import { QuickJSIsolateContext } from './isolate-context'
8import type { ExecState } from './isolate-context'
9import type { QuickJSContext } from 'quickjs-emscripten'
10import type {
11 IsolateConfig,
12 IsolateContext,
13 IsolateDriver,
14 ToolBinding,
15} from '@tanstack/ai-code-mode'
16
17/** Default memory limit in MB (matches Node isolate driver default). */
18const DEFAULT_MEMORY_LIMIT_MB = 128
19
20/** Default max stack size in bytes for QuickJS runtime. */
21const DEFAULT_MAX_STACK_SIZE_BYTES = 512 * 1024
22
23/**
24 * Configuration for the QuickJS WASM isolate driver
25 */
26export interface QuickJSIsolateDriverConfig {
27 /**
28 * Default execution timeout in ms (default: 30000)
29 */
30 timeout?: number
31
32 /**
33 * Default memory limit in MB (default: 128).
34 * Applied via QuickJS `runtime.setMemoryLimit`.
35 */
36 memoryLimit?: number
37
38 /**
39 * Default max stack size in bytes (default: 512 KiB).
40 * Applied via QuickJS `runtime.setMaxStackSize`.
41 */
42 maxStackSize?: number
43
44 /**
45 * URL or path from which Emscripten loads the QuickJS WASM binary.
46 *
47 * When omitted, `quickjs-emscripten` resolves its bundled WASM binary.
48 * Set this when serving the binary from a public directory or CDN.
49 */
50 wasmLocation?: string
51}
52
53/**
54 * Run a tool binding against JSON-encoded args. Never rejects: errors are
55 * encoded into the JSON envelope so the guest-side wrapper can rethrow them.
56 */
57async function invokeBinding(
58 binding: ToolBinding,
59 argsJson: string,
60): Promise<string> {
61 try {
62 const args = JSON.parse(argsJson)
63 const result = await binding.execute(args)
64 return JSON.stringify({ success: true, value: result })
65 } catch (error) {
66 const errorMessage = error instanceof Error ? error.message : String(error)
67 return JSON.stringify({ success: false, error: errorMessage })
68 }
69}
70
71/**
72 * Inject a tool binding as a host function that returns a QuickJS promise
73 * resolved from the host side.
74 *
75 * Deliberately avoids `newAsyncifiedFunction`: repeated asyncify suspensions
76 * corrupt QuickJS refcounts and abort the WASM module
77 * (https://github.com/justjake/quickjs-emscripten/issues/258). The promise
78 * bridge never suspends the WASM stack, so that bug cannot trigger.
79 */
80function injectBinding(
81 vm: QuickJSContext,
82 name: string,
83 binding: ToolBinding,
84 logs: Array<string>,
85 execState: ExecState,
86): void {
87 const toolFn = vm.newFunction(name, (argsHandle) => {
88 const argsJson = vm.getString(argsHandle)
89 const promise = vm.newPromise()
90
91 // A timed-out execution cancels every outstanding tool call by settling
92 // its deferred with a timeout envelope, so the guest program itself can
93 // settle and the VM can be disposed (freeing a runtime that still holds
94 // an unsettled program promise aborts the shared WASM module).
95 const resolveWithPayload = (payloadJson: string) => {
96 execState.pendingCancels.delete(cancel)
97 if (!vm.alive || !promise.alive) return
98 const payloadHandle = vm.newString(payloadJson)
99 promise.resolve(payloadHandle)
100 payloadHandle.dispose()
101 }
102 const cancel = () =>
103 resolveWithPayload(
104 JSON.stringify({ success: false, error: 'Execution timed out' }),
105 )
106 execState.pendingCancels.add(cancel)
107
108 void invokeBinding(binding, argsJson).then(resolveWithPayload)
109
110 // Resume guest code waiting on the promise. Defense in depth: outside an
111 // active execute() the interrupt deadline is 0, so a stray job from an
112 // abandoned execution is interrupted instead of running unbounded.
113 void promise.settled.then(() => {
114 try {
115 if (vm.runtime.alive) {
116 const jobs = vm.runtime.executePendingJobs()
117 if (jobs.error) {
118 // Errors thrown inside guest async code reject the observed program
119 // promise instead of surfacing here; anything that does land here
120 // would otherwise be silently swallowed and leak its handle.
121 logs.push(
122 `ERROR: uncaught error in sandboxed code: ${JSON.stringify(vm.dump(jobs.error))}`,
123 )
124 jobs.error.dispose()
125 }
126 }
127 } finally {
128 promise.dispose()
129 }
130 })
131
132 return promise.handle
133 })
134
135 // Set on global - the VM keeps its own reference
136 vm.setProp(vm.global, `__${name}_impl`, toolFn)
137 toolFn.dispose()
138
139 // Create wrapper that parses input and output
140 // Function names match the binding keys (e.g., external_fetchWeather)
141 const wrapperCode = `
142 async function ${name}(input) {
143 const resultJson = await __${name}_impl(JSON.stringify(input));
144 const result = JSON.parse(resultJson);
145 if (!result.success) {
146 throw new Error(result.error);
147 }
148 return result.value;
149 }
150 `
151 const wrapperResult = vm.evalCode(wrapperCode)
152 if (wrapperResult.error) {
153 const errorStr = vm.dump(wrapperResult.error)
154 wrapperResult.error.dispose()
155 throw new Error(`Failed to create wrapper for ${name}: ${errorStr}`)
156 }
157 wrapperResult.value.dispose()
158}
159
160/**
161 * Create a QuickJS WASM isolate driver
162 *
163 * This driver uses QuickJS compiled to WebAssembly via Emscripten.
164 * It provides a sandboxed JavaScript environment that runs anywhere
165 * (Node.js, browser, edge) without native dependencies.
166 *
167 * Tools are injected as async functions that bridge back to the host.
168 *
169 * @example
170 * ```typescript
171 * import { createQuickJSIsolateDriver } from '@tanstack/ai-isolate-quickjs'
172 *
173 * const driver = createQuickJSIsolateDriver({
174 * timeout: 30000,
175 * })
176 *
177 * const context = await driver.createContext({
178 * bindings: {
179 * readFile: {
180 * name: 'readFile',
181 * description: 'Read a file',
182 * inputSchema: { type: 'object', properties: { path: { type: 'string' } } },
183 * execute: async ({ path }) => fs.readFile(path, 'utf-8'),
184 * },
185 * },
186 * })
187 *
188 * const result = await context.execute(`
189 * const content = await readFile({ path: './data.json' })
190 * return JSON.parse(content)
191 * `)
192 * ```
193 */
194export function createQuickJSIsolateDriver(
195 config: QuickJSIsolateDriverConfig = {},
196): IsolateDriver {
197 const defaultTimeout = config.timeout ?? 30000
198 const defaultMemoryLimit = config.memoryLimit ?? DEFAULT_MEMORY_LIMIT_MB
199 const defaultMaxStackSize =
200 config.maxStackSize ?? DEFAULT_MAX_STACK_SIZE_BYTES
201 let customQuickJSModule: ReturnType<typeof newQuickJSWASMModule> | undefined
202
203 const loadQuickJS = () => {
204 if (config.wasmLocation === undefined) {
205 return getQuickJS()
206 }
207
208 customQuickJSModule ??= newQuickJSWASMModule(
209 newVariant(RELEASE_SYNC, { wasmLocation: config.wasmLocation }),
210 )
211 return customQuickJSModule
212 }
213
214 return {
215 async createContext(isolateConfig: IsolateConfig): Promise<IsolateContext> {
216 const timeout = isolateConfig.timeout ?? defaultTimeout
217 const memoryLimitMb = isolateConfig.memoryLimit ?? defaultMemoryLimit
218 const maxStackSizeBytes = defaultMaxStackSize
219
220 // Create a plain (non-asyncify) QuickJS context. Host async functions
221 // are bridged with QuickJS promises instead of asyncify suspensions,
222 // so the sync WASM build is sufficient and sidesteps asyncify bugs.
223 const QuickJS = await loadQuickJS()
224 const vm = QuickJS.newContext()
225
226 // Enforce heap and stack limits so OOM/stack overflow surface as JS errors
227 // instead of growing WASM memory until the host process OOMs.
228 vm.runtime.setMemoryLimit(memoryLimitMb * 1024 * 1024)
229 vm.runtime.setMaxStackSize(maxStackSizeBytes)
230
231 // Set up console.log capture
232 const logs: Array<string> = []
233
234 // Create console object
235 const consoleObj = vm.newObject()
236
237 // Helper to create console methods
238 const createConsoleMethod = (prefix: string) => {
239 return vm.newFunction(`console.${prefix}`, (...args) => {
240 const parts = args.map((arg) => {
241 const str = vm.getString(arg)
242 return str
243 })
244 const msg = prefix ? `${prefix}: ${parts.join(' ')}` : parts.join(' ')
245 logs.push(msg)
246 })
247 }
248
249 const logFn = createConsoleMethod('')
250 const errorFn = createConsoleMethod('ERROR')
251 const warnFn = createConsoleMethod('WARN')
252 const infoFn = createConsoleMethod('INFO')
253
254 vm.setProp(consoleObj, 'log', logFn)
255 vm.setProp(consoleObj, 'error', errorFn)
256 vm.setProp(consoleObj, 'warn', warnFn)
257 vm.setProp(consoleObj, 'info', infoFn)
258 vm.setProp(vm.global, 'console', consoleObj)
259
260 // Dispose console handles
261 logFn.dispose()
262 errorFn.dispose()
263 warnFn.dispose()
264 infoFn.dispose()
265 consoleObj.dispose()
266
267 // Shared between execute() and the tool bindings: the interrupt
268 // deadline (0 means "no execution active" — any guest job that tries
269 // to run outside execute() is interrupted immediately) and the cancel
270 // callbacks for tool calls still awaiting their host promise.
271 const execState: ExecState = {
272 deadline: 0,
273 pendingCancels: new Set<() => void>(),
274 }
275
276 // Inject each tool binding as an async function
277 for (const [name, binding] of Object.entries(isolateConfig.bindings)) {
278 injectBinding(vm, name, binding, logs, execState)
279 }
280
281 vm.runtime.setInterruptHandler(() => Date.now() > execState.deadline)
282
283 return new QuickJSIsolateContext(vm, logs, timeout, execState)
284 },
285 }
286}