Open History to see the last commit
1import { spawnSync } from 'node:child_process'
2import { createRequire } from 'node:module'
3import ivm from 'isolated-vm'
4import { NodeIsolateContext } from './isolate-context'
5import type {
6 IsolateConfig,
7 IsolateContext,
8 IsolateDriver,
9} from '@tanstack/ai-code-mode'
10
11/**
12 * Configuration for the Node.js isolate driver
13 */
14export interface NodeIsolateDriverConfig {
15 /**
16 * Default memory limit in MB (default: 128)
17 */
18 memoryLimit?: number
19
20 /**
21 * Default execution timeout in ms (default: 30000)
22 */
23 timeout?: number
24
25 /**
26 * Skip the subprocess compatibility probe for isolated-vm.
27 * The probe detects native addon incompatibilities that would otherwise
28 * crash the process with a segfault. Only set to true if you have
29 * independently verified compatibility.
30 */
31 skipProbe?: boolean
32}
33
34let _probeResult: { compatible: boolean; error?: string } | null = null
35
36/**
37 * Probe isolated-vm in a subprocess to detect native addon incompatibilities.
38 * An incompatible build (e.g. compiled for a different Node.js version) will
39 * segfault the process — a crash that no JS error handling can catch.
40 * Running the probe in a child process lets us detect this safely.
41 */
42function probeIsolatedVm(): { compatible: boolean; error?: string } {
43 if (_probeResult) return _probeResult
44
45 try {
46 const esmRequire = createRequire(import.meta.url)
47 const ivmPath = esmRequire.resolve('isolated-vm')
48 const result = spawnSync(
49 process.execPath,
50 [
51 '-e',
52 `const ivm = require(${JSON.stringify(ivmPath)}); new ivm.Isolate({ memoryLimit: 8 }).dispose(); process.exit(0)`,
53 ],
54 { timeout: 10_000, encoding: 'utf8' },
55 )
56
57 if (result.status === 0) {
58 _probeResult = { compatible: true }
59 } else {
60 const signal = result.signal ? ` (signal: ${result.signal})` : ''
61 const stderr = result.stderr.trim() ? `\n${result.stderr.trim()}` : ''
62 _probeResult = {
63 compatible: false,
64 error: `isolated-vm probe exited with code ${result.status}${signal}${stderr}`,
65 }
66 }
67 } catch (err) {
68 _probeResult = {
69 compatible: false,
70 error: `Failed to probe isolated-vm: ${err instanceof Error ? err.message : String(err)}`,
71 }
72 }
73
74 return _probeResult
75}
76
77export { probeIsolatedVm }
78
79/**
80 * Create a Node.js isolate driver using isolated-vm
81 *
82 * This driver creates V8 isolates that are completely sandboxed from the
83 * host environment. Tools are injected as callable async functions that
84 * bridge back to the host for execution.
85 *
86 * A subprocess probe runs on first call to verify that the `isolated-vm`
87 * native addon is compatible with the current Node.js version. If the probe
88 * fails (e.g. segfault from a mismatched binary), a descriptive error is
89 * thrown instead of crashing the host process.
90 *
91 * @example
92 * ```typescript
93 * import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
94 *
95 * const driver = createNodeIsolateDriver({
96 * memoryLimit: 128,
97 * timeout: 30000,
98 * })
99 *
100 * const context = await driver.createContext({
101 * bindings: {
102 * readFile: {
103 * name: 'readFile',
104 * description: 'Read a file',
105 * inputSchema: { type: 'object', properties: { path: { type: 'string' } } },
106 * execute: async ({ path }) => fs.readFile(path, 'utf-8'),
107 * },
108 * },
109 * })
110 *
111 * const result = await context.execute(`
112 * const content = await readFile({ path: './data.json' })
113 * return JSON.parse(content)
114 * `)
115 * ```
116 *
117 * @throws Error if `isolated-vm` is not compatible with the current Node.js version
118 */
119export function createNodeIsolateDriver(
120 config: NodeIsolateDriverConfig = {},
121): IsolateDriver {
122 if (!config.skipProbe) {
123 const probe = probeIsolatedVm()
124 if (!probe.compatible) {
125 throw new Error(
126 `isolated-vm is not compatible with the current Node.js version (${process.version}). ` +
127 `The native addon crashes the process (segfault) when used. ` +
128 `${probe.error ? probe.error + ' ' : ''}` +
129 `Use the QuickJS isolate driver as an alternative, or use a Node.js version supported by isolated-vm.`,
130 )
131 }
132 }
133
134 const defaultMemoryLimit = config.memoryLimit ?? 128
135 const defaultTimeout = config.timeout ?? 30000
136
137 return {
138 async createContext(isolateConfig: IsolateConfig): Promise<IsolateContext> {
139 const memoryLimit = isolateConfig.memoryLimit ?? defaultMemoryLimit
140 const timeout = isolateConfig.timeout ?? defaultTimeout
141
142 // Create isolate with memory limit
143 const isolate = new ivm.Isolate({ memoryLimit })
144
145 // Create context
146 const context = await isolate.createContext()
147
148 // Get reference to global object
149 const jail = context.global
150
151 // Set up global reference
152 await jail.set('global', jail.derefInto())
153
154 // Set up console.log capture
155 const logs: Array<string> = []
156 await jail.set(
157 '__captureLog',
158 new ivm.Reference((msg: string) => {
159 logs.push(msg)
160 }),
161 )
162
163 // Inject console object
164 await context.eval(`
165 const console = {
166 log: (...args) => {
167 const msg = args.map(a =>
168 typeof a === 'object' ? JSON.stringify(a) : String(a)
169 ).join(' ');
170 __captureLog.applySync(undefined, [msg]);
171 },
172 error: (...args) => {
173 const msg = 'ERROR: ' + args.map(a =>
174 typeof a === 'object' ? JSON.stringify(a) : String(a)
175 ).join(' ');
176 __captureLog.applySync(undefined, [msg]);
177 },
178 warn: (...args) => {
179 const msg = 'WARN: ' + args.map(a =>
180 typeof a === 'object' ? JSON.stringify(a) : String(a)
181 ).join(' ');
182 __captureLog.applySync(undefined, [msg]);
183 },
184 info: (...args) => {
185 const msg = 'INFO: ' + args.map(a =>
186 typeof a === 'object' ? JSON.stringify(a) : String(a)
187 ).join(' ');
188 __captureLog.applySync(undefined, [msg]);
189 },
190 };
191 `)
192
193 // Inject each tool binding
194 for (const [name, binding] of Object.entries(isolateConfig.bindings)) {
195 // Create an async Reference that executes the tool
196 // Uses applySyncPromise which properly handles async functions
197 const toolRef = new ivm.Reference(
198 async (argsJson: string): Promise<string> => {
199 try {
200 const args = JSON.parse(argsJson)
201 const result = await binding.execute(args)
202 return JSON.stringify({ success: true, value: result })
203 } catch (error) {
204 const errorMessage =
205 error instanceof Error ? error.message : String(error)
206 return JSON.stringify({ success: false, error: errorMessage })
207 }
208 },
209 )
210
211 // Store reference on global object
212 await jail.set(`__${name}_ref`, toolRef)
213
214 // Create async wrapper that uses applySyncPromise
215 // Tool name is used directly (no prefix) to match how they appear in the system prompt
216 await context.eval(`
217 async function ${name}(input) {
218 const resultJson = await __${name}_ref.applySyncPromise(
219 undefined,
220 [JSON.stringify(input ?? {})]
221 );
222 const result = JSON.parse(resultJson);
223 if (!result.success) {
224 throw new Error(result.error);
225 }
226 return result.value;
227 }
228 `)
229 }
230
231 return new NodeIsolateContext(isolate, context, logs, timeout)
232 },
233 }
234}