1
/**2
* Runs the VM on the calling thread, for runtimes without worker threads (Cloudflare Workers and3
* Durable Objects, browsers) and for the server side of `RemoteCodemodeSandbox`.4
*5
* Problem: QuickJS runs synchronously. While a script computes, the host's event loop does not6
* run, so neither the deadline timer nor an abort signal can fire. On Workers even `Date.now()` is7
* frozen during synchronous execution, so the VM cannot check a clock either. Example: with a8
* worker thread, `while (true) {}` is stopped by the host's 200 ms timer; on the calling thread9
* that timer never gets a chance to run.10
*11
* Solution: an interrupt budget. QuickJS polls its interrupt handler periodically while a script12
* runs; this launcher counts the polls across the whole execution and interrupts the script once13
* the count passes the budget. The execution then fails with `kind: "timeout"`. The deadline and14
* abort signal still work whenever the script waits on a tool, since the event loop runs then.15
*16
* The rate of polls depends on the code and the machine. Measured with a tight loop: about 50,00017
* per second of CPU on an Apple M-series laptop and about 10,000 per second on Cloudflare Durable18
* Objects (October 2026). The default of 100,000 allows roughly 2 to 10 seconds of uninterrupted19
* computation; keep it well below the platform's own CPU limit, because hitting that limit resets20
* a Durable Object instead of failing one script.21
*22
* Once the VM reports `done` or `crash`, the result is decided, so the VM is interrupted at the23
* next poll instead of running on until the host stops it. Example: a script that keeps printing in24
* a `for (;;)` loop after its output limit was reached would otherwise run until the budget ran out25
* and be reported as a timeout.26
*27
* Stack: the VM runs on the caller's stack, which is smaller than a worker thread's (about 1 MB28
* on Node's main thread), so QuickJS's stack guard is set to {@link INLINE_MAX_STACK_SIZE}.29
*30
* Reentrancy: VM callbacks run inside QuickJS. Messages from the VM are delivered to the host in31
* a microtask, after the VM has returned, so host code (tool calls, `finish()`, disposal) never32
* runs inside a VM callback and never re-enters the VM.33
*/34
import type { CodemodeSandboxBaseOptions } from "../types.ts";35
import type { CodemodeWasmModule } from "../wasm.ts";36
import { CodemodeSandboxBase, errorMessage, type VmLauncher } from "./execution.ts";37
import { startVm } from "./vm.ts";39
export const DEFAULT_INTERRUPT_BUDGET = 100_000;41
/** Allows recursion about 1,000 calls deep and trips well before a 1 MB host stack overflows. */42
export const INLINE_MAX_STACK_SIZE = 256 * 1024;44
export interface InlineCodemodeSandboxOptions extends CodemodeSandboxBaseOptions {45
/**46
* Compiled `quickjs-wasi/quickjs.wasm`. On Cloudflare, import it with Wrangler's `CompiledWasm`47
* rule (`@earendil-works/pi-codemode/cloudflare` does this); on Node, `loadQuickJSWasm()`.48
*/49
wasm: CodemodeWasmModule | Promise<CodemodeWasmModule>;50
/**51
* Interrupt polls an execution may use before it fails with `kind: "timeout"`. The only limit on52
* a script that computes without awaiting a tool. Default: {@link DEFAULT_INTERRUPT_BUDGET}.53
*/54
interruptBudget?: number;55
}57
export function inlineLauncher(58
wasm: CodemodeWasmModule | Promise<CodemodeWasmModule>,59
interruptBudget: number = DEFAULT_INTERRUPT_BUDGET,60
): VmLauncher {61
return async (data, events) => {62
let module: CodemodeWasmModule;63
try {64
module = await wasm;65
} catch (error) {66
throw new Error(`Failed to load QuickJS: ${errorMessage(error)}`);67
}68
let stopped = false;69
let settled = false;70
let polls = 0;71
let exhausted = false;72
const session = await startVm({73
data,74
wasm: module,75
maxStackSize: INLINE_MAX_STACK_SIZE,76
interruptBudget,77
shouldInterrupt: () => {78
if (stopped || settled || exhausted) return true;79
if (++polls <= interruptBudget) return false;80
exhausted = true;81
return true;82
},83
post: (message) => {84
const terminal = message.type === "done" || message.type === "crash";85
// Only the first terminal message counts: a crash caused by interrupting a settled VM is noise.86
if (terminal && settled) return;87
if (terminal) settled = true;88
queueMicrotask(() => {89
if (stopped) return;90
// The interrupt surfaces as a crash or a failed done; report what caused it instead.91
if (exhausted && (message.type === "done" || message.type === "crash")) {92
events.failure({93
kind: "timeout",94
message: `Execution exceeded its interrupt budget of ${interruptBudget}`,95
});96
return;97
}98
events.message(message);99
});100
},101
});102
return {103
post: (message) => {104
if (!stopped) session.deliver(message);105
},106
stop: async () => {107
if (stopped) return;108
stopped = true;109
session.dispose();110
},111
};112
};113
}115
/**116
* Runs each execution's QuickJS VM on the calling thread. Works in any runtime with WebAssembly117
* and microtasks; needs no worker threads, files, or Node built-ins. A script that computes118
* blocks the caller's thread until it awaits a tool or uses up its interrupt budget, so prefer119
* `CodemodeSandbox` where worker threads exist, and `RemoteCodemodeSandbox` to keep scripts off a120
* thread that must stay responsive (such as a Durable Object that serves a session).121
*/122
export class InlineCodemodeSandbox extends CodemodeSandboxBase {123
constructor(options: InlineCodemodeSandboxOptions) {124
super(options, inlineLauncher(options.wasm, options.interruptBudget));125
}126
}