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

isolate-driver.ts

256 lines8.9 KB

1import { existsSync } from 'node:fs'
2import { dirname, join } from 'node:path'
3import { fileURLToPath, pathToFileURL } from 'node:url'
4import {
5 DEFAULT_MAX_TOOL_CALLS,
6 QuickJSBunIsolateContext,
7} from './isolate-context'
8import type {
9 IsolateConfig,
10 IsolateContext,
11 IsolateDriver,
12} from '@tanstack/ai-code-mode'
13import type { QuickJS } from 'quickjs-bun'
14import type { QuickJSBunModule } from './isolate-context'
15​
16/** Default execution timeout in ms (matches the other isolate drivers). */
17const DEFAULT_TIMEOUT_MS = 30000
18​
19/** Default memory limit in MB (matches the other isolate drivers). */
20const DEFAULT_MEMORY_LIMIT_MB = 128
21​
22/** Default max stack size in bytes (matches the QuickJS WASM driver). */
23const DEFAULT_MAX_STACK_SIZE_BYTES = 512 * 1024
24​
25/**
26 * quickjs-bun's exports map only declares a `bun` condition (no import/default).
27 * Bun's resolver understands that; Vite/Node package resolution does not —
28 * even with `conditions: ['bun']` under Nitro's Vite module runner, which
29 * still goes through resolvePackageEntry and fails with:
30 * "No known conditions for \".\" specifier in \"quickjs-bun\" package"
31 *
32 * Prefer Bun.resolveSync, then fall back to locating `index.ts` on disk so
33 * tools that ignore the bun export condition can still load the entry.
34 */
35const QUICKJS_BUN_SPECIFIER = 'quickjs-bun'
36​
37type BunResolveSync = {
38 resolveSync?: (specifier: string, from: string) => string
40​
41function moduleDir(): string {
42 // import.meta.dirname is Node 20.11+ / Bun; fall back for older runtimes.
43 if (typeof import.meta.dirname === 'string') return import.meta.dirname
44 return dirname(fileURLToPath(import.meta.url))
46​
47function findQuickjsBunEntryOnDisk(): string | undefined {
48 const starts = [moduleDir(), process.cwd()]
49 for (const start of starts) {
50 let dir = start
51 for (let i = 0; i < 14; i++) {
52 const candidate = join(dir, 'node_modules', 'quickjs-bun', 'index.ts')
53 if (existsSync(candidate)) return candidate
54 const parent = dirname(dir)
55 if (parent === dir) break
56 dir = parent
57 }
58 }
59 return undefined
61​
62function resolveQuickjsBunEntry(): string {
63 const bun = (globalThis as { Bun?: BunResolveSync }).Bun
64 if (typeof bun?.resolveSync === 'function') {
65 try {
66 return bun.resolveSync(QUICKJS_BUN_SPECIFIER, moduleDir())
67 } catch {
68 // Fall through — e.g. package not visible from this module path.
69 }
70 }
71​
72 const onDisk = findQuickjsBunEntryOnDisk()
73 if (onDisk !== undefined) return onDisk
74​
75 // Last resort: bare specifier (works only under a bun-aware resolver).
76 return QUICKJS_BUN_SPECIFIER
78​
79/**
80 * Runtime-native dynamic import that Vite/Nitro cannot rewrite into the
81 * module runner. A plain `import()` in source is often transformed to
82 * `runInlinedModule`, which then parses quickjs-bun as ESM and dies on
83 * Bun-only syntax / strict-mode edge cases. Building the importer via
84 * `Function` keeps a true host `import()` (Bun loads the .ts entry + bun:ffi).
85 */
86const nativeImport = new Function('specifier', 'return import(specifier)') as (
87 specifier: string,
88) => Promise<QuickJSBunModule>
89​
90/**
91 * Dynamically import the `quickjs-bun` module namespace. Never a static import:
92 * the package only resolves under Bun (or via the absolute-path fallbacks
93 * above). Prefer an absolute file: URL so package.json `exports` (bun-only)
94 * is never consulted by Node/Vite resolvers.
95 */
96function importQuickJSBun(): Promise<QuickJSBunModule> {
97 const entry = resolveQuickjsBunEntry()
98 const specifier =
99 entry === QUICKJS_BUN_SPECIFIER || entry.startsWith('file:')
100 ? entry
101 : pathToFileURL(entry).href
102 return nativeImport(specifier)
104​
105let libraryPromise: Promise<QuickJS> | undefined
106​
107/**
108 * Load the QuickJS library once per process, memoized in `libraryPromise`.
109 * `quickjs-bun` compiles the vendored QuickJS C sources with Bun's embedded
110 * TinyCC on first use (~100ms), after which creating a runtime + context costs
111 * ~1-2ms. A failed load (e.g. a missing prebuilt library path on Windows) is
112 * not cached, so a corrected environment can retry.
113 */
114async function loadQuickJSLibrary(): Promise<QuickJS> {
115 libraryPromise ??= importQuickJSBun().then((mod) => new mod.QuickJS())
116 try {
117 return await libraryPromise
118 } catch (error) {
119 // Don't cache failures (e.g. a missing prebuilt library path on
120 // Windows) so a corrected environment can retry.
121 libraryPromise = undefined
122 throw error
123 }
125​
126/**
127 * Configuration for the QuickJS Bun isolate driver
128 */
129export interface QuickJSBunIsolateDriverConfig {
130 /**
131 * Default execution timeout in ms (default: 30000)
132 */
133 timeout?: number
134​
135 /**
136 * Default memory limit in MB (default: 128).
137 * Applied via QuickJS `JS_SetMemoryLimit` on the per-context runtime.
138 */
139 memoryLimit?: number
140​
141 /**
142 * Default max stack size in bytes (default: 512 KiB).
143 * Applied via QuickJS `JS_SetMaxStackSize` on the per-context runtime.
144 */
145 maxStackSize?: number
146​
147 /**
148 * Maximum number of host tool calls a single execution may make (default:
149 * 1000). Bounds output and memory growth from untrusted sandbox code (e.g. a
150 * `Promise.all` over a huge array); exceeding it throws a catchable error
151 * inside the sandbox. The execution timeout still bounds wall-clock time.
152 */
153 maxToolCalls?: number
155​
156/**
157 * Create a QuickJS isolate driver for the Bun runtime
158 *
159 * This driver runs QuickJS natively through `bun:ffi` (via `quickjs-bun`)
160 * instead of WebAssembly. Each context gets its own QuickJS runtime with a
161 * dedicated heap, stack limit, and interrupt-based timeout, so sandboxes are
162 * isolated from each other at the language level and each enforces its own
163 * resource limits.
164 *
165 * Note this is *not* an OS/VM sandbox: QuickJS is compiled by TinyCC and called
166 * through `bun:ffi`, so it executes in the host process's address space. The
167 * memory "limit" is QuickJS's internal accounting (`JS_SetMemoryLimit`), not a
168 * hardware/OS boundary. For a stronger boundary use `@tanstack/ai-isolate-node`
169 * (a separate V8 isolate) or the WASM driver (WebAssembly linear-memory
170 * sandbox). It requires Bun >= 1.3.14 — on Node.js use
171 * `@tanstack/ai-isolate-node` or `@tanstack/ai-isolate-quickjs` instead.
172 *
173 * Tools are injected as async functions that bridge back to the host.
174 *
175 * @example
176 * ```typescript
177 * import { createQuickJSBunIsolateDriver } from '@tanstack/ai-isolate-quickjs-bun'
178 *
179 * const driver = createQuickJSBunIsolateDriver({
180 * timeout: 30000,
181 * })
182 *
183 * const context = await driver.createContext({
184 * bindings: {
185 * readFile: {
186 * name: 'readFile',
187 * description: 'Read a file',
188 * inputSchema: { type: 'object', properties: { path: { type: 'string' } } },
189 * execute: async ({ path }) => fs.readFile(path, 'utf-8'),
190 * },
191 * },
192 * })
193 *
194 * const result = await context.execute(`
195 * const content = await readFile({ path: './data.json' })
196 * return JSON.parse(content)
197 * `)
198 * ```
199 */
200export function createQuickJSBunIsolateDriver(
201 config: QuickJSBunIsolateDriverConfig = {},
202): IsolateDriver {
203 const defaultTimeout = config.timeout ?? DEFAULT_TIMEOUT_MS
204 const defaultMemoryLimit = config.memoryLimit ?? DEFAULT_MEMORY_LIMIT_MB
205 const defaultMaxStackSize =
206 config.maxStackSize ?? DEFAULT_MAX_STACK_SIZE_BYTES
207 const maxToolCalls = config.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS
208​
209 return {
210 /**
211 * Create a fresh isolate context backed by its own QuickJS runtime +
212 * context. Each context gets a dedicated runtime, so its memory/stack
213 * limits and job queue are independent of every other context. Throws on
214 * Node.js — this driver requires the Bun runtime.
215 */
216 async createContext(isolateConfig: IsolateConfig): Promise<IsolateContext> {
217 if (typeof Bun === 'undefined') {
218 throw new Error(
219 '@tanstack/ai-isolate-quickjs-bun requires the Bun runtime (https://bun.sh). ' +
220 'On Node.js, use @tanstack/ai-isolate-node or @tanstack/ai-isolate-quickjs instead.',
221 )
222 }
223​
224 const timeout = Math.max(1, isolateConfig.timeout ?? defaultTimeout)
225 const memoryLimitMb = isolateConfig.memoryLimit ?? defaultMemoryLimit
226 const maxStackSizeBytes = defaultMaxStackSize
227​
228 const quickjs = await importQuickJSBun()
229 const library = await loadQuickJSLibrary()
230​
231 // A dedicated runtime per context gives every sandbox its own heap
232 // and stack limits, mirroring `setMemoryLimit`/`setMaxStackSize` in
233 // the QuickJS WASM driver.
234 const runtime = new quickjs.JSRuntime({
235 library,
236 memoryBytes: memoryLimitMb * 1024 * 1024,
237 stackBytes: maxStackSizeBytes,
238 })
239​
240 try {
241 const vm = runtime.createContext({ timeoutMs: timeout })
242 return new QuickJSBunIsolateContext({
243 quickjs,
244 runtime,
245 vm,
246 timeout,
247 maxToolCalls,
248 bindings: isolateConfig.bindings,
249 })
250 } catch (error) {
251 runtime.dispose()
252 throw error
253 }
254 },
255 }