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

code-mode-isolates.md

406 lines18.5 KB

1---
2title: Code Mode Isolate Drivers
3id: code-mode-isolates
4order: 4
5description: "Compare Code Mode sandbox drivers — Node isolated-vm, QuickJS WASM, QuickJS Bun (bun:ffi), Cloudflare Workers, and Daytona sandboxes — and choose the right runtime for your deployment."
6keywords:
7 - tanstack ai
8 - code mode
9 - isolate driver
10 - isolated-vm
11 - quickjs
12 - quickjs-bun
13 - bun
14 - bun:ffi
15 - cloudflare workers
16 - daytona
17 - sandbox
18 - secure execution
19---
20​
21Isolate drivers provide the secure sandbox runtimes that [Code Mode](./code-mode.md) uses to execute generated TypeScript. All drivers implement the same `IsolateDriver` interface, so you can swap them without changing any other code.
22​
23## Choosing a Driver
24​
25​
26| | Node (`isolated-vm`) | QuickJS (WASM) | QuickJS Bun (`bun:ffi`) | Cloudflare Workers | Daytona |
27| -------------------- | ------------------------ | --------------------------- | ------------------------ | ------------------------------ | ---------------------------------- |
28| **Best for** | Server-side Node.js apps | Browsers, edge, portability | Bun servers | Edge deployments on Cloudflare | Full remote Linux sandboxes |
29| **Performance** | Fast (V8 JIT) | Slower (interpreted) | Fast (native QuickJS) | Fast (V8 on Cloudflare edge) | Fast (native runtime; remote call) |
30| **Native deps** | Yes (C++ addon) | None | None (TinyCC on the fly) | None | None |
31| **Browser support** | No | Yes | No (Bun only) | N/A | Yes |
32| **Memory limit** | Configurable | Configurable | Configurable | N/A | Configurable |
33| **Stack size limit** | N/A | Configurable | Configurable | N/A | N/A |
34| **Setup** | `pnpm add` | `pnpm add` | `bun add` | Deploy a Worker first | Create or pass a Daytona sandbox |
35​
36​
37---
38​
39## Node.js Driver (`@tanstack/ai-isolate-node`)
40​
41Uses V8 isolates via the [`isolated-vm`](https://github.com/laverdet/isolated-vm) native addon. This is the fastest option for server-side Node.js applications because generated code runs in the same V8 engine as the host, under JIT compilation, with no serialization overhead beyond tool call boundaries.
42​
43### Installation
44​
45<!-- ::start:tabs variant="package-manager" mode="install" -->
46​
47react: @tanstack/ai-isolate-node
48vue: @tanstack/ai-isolate-node
49solid: @tanstack/ai-isolate-node
50svelte: @tanstack/ai-isolate-node
51preact: @tanstack/ai-isolate-node
52angular: @tanstack/ai-isolate-node
53vanilla: @tanstack/ai-isolate-node
54octane: @tanstack/ai-isolate-node
55​
56<!-- ::end:tabs -->
57​
58`isolated-vm` is a native C++ addon and must be compiled for your platform. It requires Node.js 18 or later.
59​
60### Usage
61​
62```typescript
63import { createNodeIsolateDriver } from '@tanstack/ai-isolate-node'
64​
65const driver = createNodeIsolateDriver({
66 memoryLimit: 128, // MB
67 timeout: 30_000, // ms
68})
69```
70​
71### Options
72​
73​
74| Option | Type | Default | Description |
75| ------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------ |
76| `memoryLimit` | `number` | `128` | Maximum heap size for the V8 isolate, in megabytes. Execution is terminated if this limit is exceeded. |
77| `timeout` | `number` | `30000` | Maximum wall-clock time per execution, in milliseconds. |
78​
79​
80### How it works
81​
82Each `execute_typescript` call creates a fresh V8 isolate. Your tools are bridged into the isolate as async reference functions — when generated code calls `external_myTool(...)`, the call crosses the isolate boundary back into the host Node.js process, executes your tool implementation, and returns the result. Console output (`log`, `error`, `warn`, `info`) is captured and returned in the execution result. The isolate is destroyed after each call.
83​
84---
85​
86## QuickJS Driver (`@tanstack/ai-isolate-quickjs`)
87​
88Uses [QuickJS](https://bellard.org/quickjs/) compiled to WebAssembly via Emscripten. Because the sandbox is a WASM module, it has no native dependencies and runs anywhere JavaScript runs: Node.js, browsers, Deno, Bun, and Cloudflare Workers (without deploying a separate Worker).
89​
90### Installation
91​
92<!-- ::start:tabs variant="package-manager" mode="install" -->
93​
94react: @tanstack/ai-isolate-quickjs
95vue: @tanstack/ai-isolate-quickjs
96solid: @tanstack/ai-isolate-quickjs
97svelte: @tanstack/ai-isolate-quickjs
98preact: @tanstack/ai-isolate-quickjs
99angular: @tanstack/ai-isolate-quickjs
100vanilla: @tanstack/ai-isolate-quickjs
101octane: @tanstack/ai-isolate-quickjs
102​
103<!-- ::end:tabs -->
104​
105### Usage
106​
107```typescript
108import { createQuickJSIsolateDriver } from '@tanstack/ai-isolate-quickjs'
109​
110const driver = createQuickJSIsolateDriver({
111 memoryLimit: 128, // MB
112 timeout: 30_000, // ms
113 maxStackSize: 524288, // bytes (512 KiB)
114 wasmLocation: '/assets/quickjs/emscripten-module.wasm',
115})
116```
117​
118### Options
119​
120​
121| Option | Type | Default | Description |
122| -------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------ |
123| `memoryLimit` | `number` | `128` | Maximum heap memory for the QuickJS VM, in megabytes. |
124| `timeout` | `number` | `30000` | Maximum wall-clock time per execution, in milliseconds. |
125| `maxStackSize` | `number` | `524288` | Maximum call stack size in bytes (default: 512 KiB). Increase for deeply recursive code; decrease to catch runaway recursion sooner. |
126| `wasmLocation` | `string` | — | URL or path from which Emscripten loads the QuickJS WASM binary. When omitted, `quickjs-emscripten` resolves its bundled binary. |
127​
128### Serving the WASM binary
129​
130Set `wasmLocation` when the QuickJS WASM binary is hosted in a public directory or on a CDN:
131​
132```typescript
133import { createQuickJSIsolateDriver } from '@tanstack/ai-isolate-quickjs'
134​
135const driver = createQuickJSIsolateDriver({
136 wasmLocation: 'https://cdn.example.com/quickjs/emscripten-module.wasm',
137})
138```
139​
140Serve the synchronous release binary exported by `@jitl/quickjs-wasmfile-release-sync/wasm`. For a cross-origin URL, configure the host to allow cross-origin requests.
141​
142​
143### How it works
144​
145QuickJS runs the synchronous WASM build and bridges host async functions (your tools) through QuickJS promises, avoiding suspension of the WASM stack. Fatal errors (memory exhaustion, stack overflow) are detected, the VM is disposed, and a structured error is returned. Console output is captured and returned with the result.
146​
147> **Performance note:** QuickJS interprets JavaScript rather than JIT-compiling it, so compute-heavy scripts run slower than with the Node driver. For typical LLM-generated scripts that are mostly waiting on `external_*` tool calls, this difference is not significant.
148​
149---
150​
151## QuickJS Bun Driver (`@tanstack/ai-isolate-quickjs-bun`)
152​
153Runs [QuickJS](https://bellard.org/quickjs/) natively on the [Bun](https://bun.sh/) runtime through `bun:ffi`, via the [`quickjs-bun`](https://github.com/superpowerdotcom/quickjs-bun) package. There are no native dependencies and no build step — the vendored QuickJS C sources are compiled on the fly with Bun's embedded TinyCC, once per process. This makes it the fastest sandboxed option for Code Mode on Bun.
154​
155### Installation
156​
157<!-- ::start:tabs variant="package-manager" mode="install" -->
158​
159react: @tanstack/ai-isolate-quickjs-bun
160vue: @tanstack/ai-isolate-quickjs-bun
161solid: @tanstack/ai-isolate-quickjs-bun
162svelte: @tanstack/ai-isolate-quickjs-bun
163preact: @tanstack/ai-isolate-quickjs-bun
164angular: @tanstack/ai-isolate-quickjs-bun
165vanilla: @tanstack/ai-isolate-quickjs-bun
166octane: @tanstack/ai-isolate-quickjs-bun
167​
168<!-- ::end:tabs -->
169​
170Requires Bun 1.3.14 or later. On Windows, provide a prebuilt QuickJS dynamic library via the `QUICKJS_BUN_NATIVE_LIBRARY` environment variable.
171​
172### Usage
173​
174```typescript
175import { createQuickJSBunIsolateDriver } from '@tanstack/ai-isolate-quickjs-bun'
176​
177const driver = createQuickJSBunIsolateDriver({
178 memoryLimit: 128, // MB
179 timeout: 30_000, // ms
180 maxStackSize: 524288, // bytes (512 KiB)
181})
182```
183​
184### Options
185​
186​
187| Option | Type | Default | Description |
188| -------------- | -------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------ |
189| `memoryLimit` | `number` | `128` | Maximum heap memory for the QuickJS runtime, in megabytes. |
190| `timeout` | `number` | `30000` | Maximum wall-clock time per execution, in milliseconds. |
191| `maxStackSize` | `number` | `524288` | Maximum call stack size in bytes (default: 512 KiB). Increase for deeply recursive code; decrease to catch runaway recursion sooner. |
192| `maxToolCalls` | `number` | `1000` | Maximum host tool calls per execution. Bounds output and memory growth from untrusted sandbox code that fans out (e.g. `Promise.all` over a huge array); exceeding it throws a catchable error inside the sandbox. |
193​
194​
195### How it works
196​
197Each context gets a dedicated native QuickJS runtime with its own memory limit, stack size, and interrupt-based timeout, so contexts execute independently — unlike the WASM driver, which serializes all executions through one shared asyncified WASM module. Fatal errors (memory exhaustion, stack overflow) are detected, the VM is disposed, and a structured error is returned; create a fresh context afterwards. A per-execution `maxToolCalls` budget bounds host tool-call fan-out. Console output is captured and returned with the result.
198​
199> **Bun only:** This driver requires Bun 1.3.14 or later and throws a descriptive error when creating a context on Node.js — use the Node or QuickJS WASM driver there. On Bun, prefer this driver over the WASM one: it runs QuickJS natively, and quickjs-emscripten's asyncify bridge is unreliable for async host tool calls under Bun.
200​
201---
202​
203## Cloudflare Workers Driver (`@tanstack/ai-isolate-cloudflare`)
204​
205Runs generated code inside a [Cloudflare Worker](https://workers.cloudflare.com/) at the edge. Your application server sends code and tool schemas to the Worker via HTTP; the Worker executes the code and calls back when it needs a tool result. This keeps your tool implementations on your server while sandboxed execution happens on Cloudflare's global network.
206​
207### Installation
208​
209<!-- ::start:tabs variant="package-manager" mode="install" -->
210​
211react: @tanstack/ai-isolate-cloudflare
212vue: @tanstack/ai-isolate-cloudflare
213solid: @tanstack/ai-isolate-cloudflare
214svelte: @tanstack/ai-isolate-cloudflare
215preact: @tanstack/ai-isolate-cloudflare
216angular: @tanstack/ai-isolate-cloudflare
217vanilla: @tanstack/ai-isolate-cloudflare
218octane: @tanstack/ai-isolate-cloudflare
219​
220<!-- ::end:tabs -->
221​
222### Usage
223​
224```typescript
225import { createCloudflareIsolateDriver } from '@tanstack/ai-isolate-cloudflare'
226​
227const driver = createCloudflareIsolateDriver({
228 workerUrl: 'https://my-code-mode-worker.my-account.workers.dev',
229 authorization: process.env.CODE_MODE_WORKER_SECRET,
230 timeout: 30_000,
231 maxToolRounds: 10,
232})
233```
234​
235### Options
236​
237​
238| Option | Type | Default | Description |
239| --------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------- |
240| `workerUrl` | `string` | — | **Required.** Full URL of the deployed Cloudflare Worker. |
241| `authorization` | `string` | — | Optional value sent as the `Authorization` header on every request. Use this to prevent unauthorized access to your Worker. |
242| `timeout` | `number` | `30000` | Maximum wall-clock time for the entire execution (including all tool round-trips), in milliseconds. |
243| `maxToolRounds` | `number` | `10` | Maximum number of tool-call/result cycles per execution. Prevents infinite loops when generated code calls tools in a loop. |
244​
245​
246### Deploying the Worker
247​
248The package exports a ready-made Worker handler at `@tanstack/ai-isolate-cloudflare/worker`. Create a `wrangler.toml` and a worker entry file:
249​
250```toml
251# wrangler.toml
252name = "code-mode-worker"
253main = "src/worker.ts"
254compatibility_date = "2024-01-01"
255​
256[unsafe]
257bindings = [{ name = "eval", type = "eval" }]
258```
259​
260```typescript
261// src/worker.ts
262export { default } from '@tanstack/ai-isolate-cloudflare/worker'
263```
264​
265Deploy:
266​
267```bash
268wrangler deploy
269```
270​
271### How it works
272​
273The driver implements a request/response loop for tool execution:
274​
275```
276Driver (your server) Worker (Cloudflare edge)
277───────────────────── ─────────────────────────
278Send: code + tool schemas ──────▶ Execute code
279 ◀────── Return: needs tool X with args Y
280Execute tool X locally
281Send: tool result ──────▶ Resume execution
282 ◀────── Return: final result / needs tool Z
283...repeat until done...
284```
285​
286Each round-trip adds network latency, so the `maxToolRounds` limit both prevents runaway scripts and caps the maximum number of cross-continent hops. Console output from all rounds is aggregated and returned in the final result.
287​
288> **Security:** The Worker requires `UNSAFE_EVAL` (local dev) or the `eval` unsafe binding (production) to execute arbitrary code. Restrict access using the `authorization` option or Cloudflare Access policies.
289​
290---
291​
292## Daytona Driver (`@tanstack/ai-isolate-daytona`)
293​
294Runs generated code inside a Daytona sandbox through `sandbox.process.codeRun`. Your application process still owns TanStack tool implementations; the Daytona sandbox only receives wrapped generated code plus replayed tool results.
295​
296### Installation
297​
298<!-- ::start:tabs variant="package-manager" mode="install" -->
299​
300react: @tanstack/ai-isolate-daytona
301vue: @tanstack/ai-isolate-daytona
302solid: @tanstack/ai-isolate-daytona
303svelte: @tanstack/ai-isolate-daytona
304preact: @tanstack/ai-isolate-daytona
305angular: @tanstack/ai-isolate-daytona
306vanilla: @tanstack/ai-isolate-daytona
307octane: @tanstack/ai-isolate-daytona
308​
309<!-- ::end:tabs -->
310​
311If your application creates sandboxes with the official Daytona SDK, also install it:
312​
313<!-- ::start:tabs variant="package-manager" mode="install" -->
314​
315react: @daytona/sdk
316vue: @daytona/sdk
317solid: @daytona/sdk
318svelte: @daytona/sdk
319preact: @daytona/sdk
320angular: @daytona/sdk
321vanilla: @daytona/sdk
322octane: @daytona/sdk
323​
324<!-- ::end:tabs -->
325​
326### Usage
327​
328```typescript
329import { Daytona } from '@daytona/sdk'
330import { createDaytonaIsolateDriver } from '@tanstack/ai-isolate-daytona'
331​
332const daytona = new Daytona()
333const sandbox = await daytona.create({ language: 'typescript' })
334​
335const driver = createDaytonaIsolateDriver({
336 sandbox,
337 timeout: 30_000,
338 maxToolRounds: 10,
339})
340```
341​
342### Options
343​
344| Option | Type | Default | Description |
345|--------|------|---------|-------------|
346| `sandbox` | `DaytonaSandboxLike` | — | **Required.** A caller-owned Daytona sandbox-like object with `process.codeRun(code, params?, timeout?)`. |
347| `timeout` | `number` | `30000` | Maximum wall-clock time for the entire execution, including replay rounds, in milliseconds. |
348| `maxToolRounds` | `number` | `10` | Maximum number of sandbox <-> host tool callback rounds. Prevents infinite loops when generated code repeatedly asks for tools. |
349​
350### How it works
351​
352The driver uses the same host-owned tool replay shape as the Cloudflare driver without Cloudflare's parent Worker / Dynamic Worker split:
353​
354```text
355Driver (your server) Daytona sandbox
356───────────────────── ───────────────
357Send: wrapped code ──────▶ Execute with process.codeRun
358 ◀────── Return: need_tools with tool requests
359Execute tools locally
360Replay with toolResults ──────▶ Continue execution
361 ◀────── Return: final result / more tool requests
362...repeat until done...
363```
364​
365Use this driver when you want Code Mode execution in a full Daytona sandbox instead of an in-process isolate, QuickJS WASM runtime, or Cloudflare Worker. The sandbox should use a language/runtime capable of executing the JavaScript emitted by Code Mode, and your application remains responsible for sandbox lifecycle, filesystem, network, cleanup, and secret policy. Creating a Code Mode context does not create or delete a Daytona sandbox.
366​
367---
368​
369## The `IsolateDriver` Interface
370​
371All provided drivers satisfy this interface, exported from `@tanstack/ai-code-mode`:
372​
373```typescript
374import type { ToolBinding, NormalizedError } from "@tanstack/ai-code-mode";
375​
376interface IsolateDriver {
377 createContext(config: IsolateConfig): Promise<IsolateContext>
379​
380interface IsolateConfig {
381 bindings: Record<string, ToolBinding>
382 timeout?: number
383 memoryLimit?: number
385​
386interface IsolateContext {
387 execute(code: string): Promise<ExecutionResult>
388 dispose(): Promise<void>
390​
391interface ExecutionResult<T = unknown> {
392 success: boolean
393 value?: T
394 logs: Array<string>
395 error?: NormalizedError
397```
398​
399You can implement this interface to build a custom driver — for example, a Docker-based sandbox or a Deno subprocess.
400​
401## Next Steps
402​
403- [Code Mode](./code-mode) — Core setup, API reference, and getting started guide
404- [Showing Code Mode in the UI](./client-integration) — Display execution progress in your React app
405- [Code Mode with Snippets](./code-mode-with-snippets) — Add persistent, reusable snippet libraries
406​