Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

feat(openai-codex): run exec scripts in a QuickJS sandbox

Jack Rudenkobd49a38d1a14
diff --git a/bun.lock b/bun.lock
index 41b3b94f..c125da07 100644
--- a/bun.lock
+++ b/bun.lock
@@ -25,7 +25,7 @@
},
"packages/cli": {
"name": "claudish",
- "version": "7.60.0",
+ "version": "10.6.1",
"bin": {
"claudish": "bin/claudish.cjs",
},
@@ -33,10 +33,12 @@
"@1password/sdk": "0.4.1-beta.1",
"@inquirer/prompts": "^8.0.1",
"@inquirer/search": "^4.0.1",
+ "@jitl/quickjs-singlefile-mjs-release-sync": "^0.32.0",
"@modelcontextprotocol/sdk": "^1.27.0",
"@opentui/core": "^0.1.107",
"@opentui/react": "^0.1.107",
"dotenv": "^17.2.3",
+ "quickjs-emscripten-core": "^0.32.0",
"react": "^19.2.4",
"zod": "^4.1.13",
},
@@ -335,6 +337,10 @@
"@jimp/utils": ["@jimp/[email protected]", "", { "dependencies": { "@jimp/types": "1.6.0", "tinycolor2": "^1.6.0" } }, "sha512-gqFTGEosKbOkYF/WFj26jMHOI5OH2jeP1MmC/zbK6BF6VJBf8rIC5898dPfSzZEbSA0wbbV5slbntWVc5PKLFA=="],
+ "@jitl/quickjs-ffi-types": ["@jitl/[email protected]", "", {}, "sha512-v9T+GQpmk43VDJ7d72sf0Nexhk+ArvtUihW27dy7lqAl0zBObFKtSBBIm5RBjwIhE8VwsPPm9PNuvPvNqLWUEg=="],
+
+ "@jitl/quickjs-singlefile-mjs-release-sync": ["@jitl/[email protected]", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-h9g2Dri6WxKNjX6a1+sFAafOVxj1n5YIA1GAzMoSdIqK1M8cG07tz3GxKVC3Gbdutz14uQ3oc3Q2lll8otInhA=="],
+
"@jridgewell/gen-mapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/remapping": ["@jridgewell/[email protected]", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
@@ -957,6 +963,8 @@
"qs": ["[email protected]", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w=="],
+ "quickjs-emscripten-core": ["[email protected]", "", { "dependencies": { "@jitl/quickjs-ffi-types": "0.32.0" } }, "sha512-QFnPfjFey8EqknSrSxe1hZrf1/8z7/6s1QzGOmKo6++02r7QRRX7ZoyNaZh7JuVjWsVW87KnQrbZqnHkOAzUyg=="],
+
"range-parser": ["[email protected]", "", {}, "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg=="],
"raw-body": ["[email protected]", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
diff --git a/packages/cli/package.json b/packages/cli/package.json
index b4c6b6b7..cfe2e670 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -25,10 +25,12 @@
"@1password/sdk": "0.4.1-beta.1",
"@inquirer/prompts": "^8.0.1",
"@inquirer/search": "^4.0.1",
+ "@jitl/quickjs-singlefile-mjs-release-sync": "^0.32.0",
"@modelcontextprotocol/sdk": "^1.27.0",
"@opentui/core": "^0.1.107",
"@opentui/react": "^0.1.107",
"dotenv": "^17.2.3",
+ "quickjs-emscripten-core": "^0.32.0",
"react": "^19.2.4",
"zod": "^4.1.13"
},
diff --git a/packages/cli/src/code-mode/output.ts b/packages/cli/src/code-mode/output.ts
new file mode 100644
index 00000000..c3aae6c0
--- /dev/null
+++ b/packages/cli/src/code-mode/output.ts
@@ -0,0 +1,227 @@
+/**
+ * What an exec script produced, and how it is sent back to the model as a
+ * `custom_tool_call_output`.
+ *
+ * The form is the official Codex client's (R1 §3, `code_mode/output.rs`):
+ * a header `"{status}\nWall time {secs:.1} seconds\nOutput:\n"`, then one
+ * `input_text` part per `text()` call in order, then on failure
+ * `"Script error:\n{stack or string}"`. Token truncation to
+ * `max_output_tokens` runs after the error is appended and before the header is
+ * prepended, at 4 bytes per token.
+ *
+ * Images never travel through the script: a nested tool result's image is a
+ * reference `(tool_use_id, index)` in the output, resolved from the request's
+ * own history when the output is rendered (input builder), so the image bytes
+ * are never stored by claudish and appear exactly once in the request.
+ */
+
+/** An image of a nested tool result: the tool_use id and the image's index among that result's image blocks. */
+export interface ImageRef {
+ toolUseId: string;
+ index: number;
+}
+
+/** One item of a script's output, in the order it was produced. */
+export type OutputPart = { type: "text"; text: string } | { type: "image"; ref: ImageRef };
+
+/** A finished script. `failed` carries `error`; `terminated` was ended from outside. */
+export interface ExecOutput {
+ status: "completed" | "failed" | "terminated";
+ /** Wall time from start to finish; undefined when unknown (a reconstructed output). */
+ wallMs: number | undefined;
+ parts: OutputPart[];
+ error?: string;
+}
+
+/** A `custom_tool_call_output` content part. */
+export type ResponsesOutputPart =
+ | { type: "input_text"; text: string }
+ | { type: "input_image"; image_url: string };
+
+/** Lower and upper bound of the `max_output_tokens` pragma (claudish policy). */
+export const MIN_EXEC_OUTPUT_TOKENS = 1;
+export const MAX_EXEC_OUTPUT_TOKENS = 50_000;
+/** Bytes per token for output truncation (Codex's own approximation). */
+export const BYTES_PER_TOKEN = 4;
+
+/** The pragma keys the Codex grammar defines; any other key is rejected. */
+const PRAGMA_KEYS = new Set(["yield_time_ms", "max_output_tokens"]);
+const PRAGMA_LINE = /^[ \t]*\/\/ @exec:([^\r\n]*)$/;
+
+export interface ExecPragma {
+ /** The source to run: the input with a pragma line blanked (line numbers kept). */
+ source: string;
+ /** The pragma's `max_output_tokens`, when given. */
+ maxOutputTokens?: number;
+ /** Why the pragma was rejected; the script is then not run. */
+ error?: string;
+}
+
+/**
+ * Split the optional first-line `// @exec: {...}` pragma from an exec input.
+ *
+ * Only `yield_time_ms` (accepted and ignored: claudish never yields) and
+ * `max_output_tokens` are accepted, as in Codex; an unknown key or a body that
+ * is not a JSON object is an error. The pragma line is replaced by an empty line
+ * so error line numbers still match the model's input.
+ */
+export function parseExecPragma(input: string): ExecPragma {
+ const newline = input.search(/\r?\n/);
+ const firstLine = newline === -1 ? input : input.slice(0, newline);
+ const match = PRAGMA_LINE.exec(firstLine);
+ if (!match) return { source: input };
+ // Keep the line break, so the pragma's line becomes an empty first line.
+ const source = newline === -1 ? "" : input.slice(newline);
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(match[1].trim());
+ } catch {
+ return { source, error: "the // @exec: pragma is not a JSON object" };
+ }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ return { source, error: "the // @exec: pragma is not a JSON object" };
+ }
+ for (const key of Object.keys(parsed)) {
+ if (!PRAGMA_KEYS.has(key)) {
+ return { source, error: `unsupported key ${JSON.stringify(key)} in the // @exec: pragma` };
+ }
+ }
+ const tokens = (parsed as { max_output_tokens?: unknown }).max_output_tokens;
+ if (tokens !== undefined && (typeof tokens !== "number" || !Number.isFinite(tokens))) {
+ return { source, error: "max_output_tokens in the // @exec: pragma must be a number" };
+ }
+ return typeof tokens === "number" ? { source, maxOutputTokens: tokens } : { source };
+}
+
+/**
+ * The default output budget for one exec: discovery's truncation limit when its
+ * mode is `tokens`, else `fallback` (10,000, the protocol default the exec
+ * description states).
+ */
+export function defaultExecOutputTokens(
+ truncationPolicy: { mode: string; limit: number } | undefined,
+ fallback: number
+): number {
+ if (truncationPolicy?.mode === "tokens" && Number.isFinite(truncationPolicy.limit)) {
+ return clampExecOutputTokens(truncationPolicy.limit);
+ }
+ return clampExecOutputTokens(fallback);
+}
+
+/** A requested token budget clamped to [1, 50,000]. */
+export function clampExecOutputTokens(tokens: number): number {
+ if (!Number.isFinite(tokens)) return MAX_EXEC_OUTPUT_TOKENS;
+ return Math.min(MAX_EXEC_OUTPUT_TOKENS, Math.max(MIN_EXEC_OUTPUT_TOKENS, Math.floor(tokens)));
+}
+
+/**
+ * A script error's stack with line numbers mapped back to the model's input:
+ * the source runs wrapped as `(async () => {\n<src>\n})()`, so a frame at
+ * `exec.js:N` is input line `N - 1`.
+ */
+export function mapScriptStack(stack: string, filename = "exec.js"): string {
+ const escaped = filename.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ return stack.replace(new RegExp(`${escaped}:(\\d+)`, "g"), (_m, line: string) => {
+ const n = Math.max(1, Number(line) - 1);
+ return `${filename}:${n}`;
+ });
+}
+
+function statusLine(status: ExecOutput["status"]): string {
+ if (status === "completed") return "Script completed";
+ if (status === "failed") return "Script failed";
+ return "Script terminated";
+}
+
+/** `"{status}\nWall time {secs} seconds\nOutput:\n"`, Codex's header. */
+export function execOutputHeader(output: Pick<ExecOutput, "status" | "wallMs">): string {
+ const wall =
+ output.wallMs === undefined
+ ? "Wall time unknown"
+ : `Wall time ${(Math.max(0, output.wallMs) / 1000).toFixed(1)} seconds`;
+ return `${statusLine(output.status)}\n${wall}\nOutput:\n`;
+}
+
+/** Truncate text parts to `maxBytes` in order; images are kept. */
+function truncateParts(
+ parts: ResponsesOutputPart[],
+ maxBytes: number
+): { parts: ResponsesOutputPart[]; truncated: boolean; totalBytes: number; totalLines: number } {
+ let totalBytes = 0;
+ let totalLines = 0;
+ for (const part of parts) {
+ if (part.type !== "input_text") continue;
+ totalBytes += Buffer.byteLength(part.text, "utf8");
+ totalLines += part.text.split("\n").length;
+ }
+ if (totalBytes <= maxBytes) return { parts, truncated: false, totalBytes, totalLines };
+ const out: ResponsesOutputPart[] = [];
+ let room = maxBytes;
+ for (const part of parts) {
+ if (part.type !== "input_text") {
+ out.push(part);
+ continue;
+ }
+ if (room <= 0) continue;
+ const bytes = Buffer.byteLength(part.text, "utf8");
+ if (bytes <= room) {
+ out.push(part);
+ room -= bytes;
+ continue;
+ }
+ // Cut on a character boundary: decode the byte prefix and drop a split
+ // trailing character.
+ const cut = Buffer.from(part.text, "utf8").subarray(0, room).toString("utf8").replace(/�$/, "");
+ out.push({ type: "input_text", text: `${cut}…` });
+ room = 0;
+ }
+ return { parts: out, truncated: true, totalBytes, totalLines };
+}
+
+export interface FormatExecOutputOptions {
+ /** The exec's output budget in tokens (pragma, else the default). */
+ maxOutputTokens: number;
+ /**
+ * The `image_url` for an image reference, from the tool_results in this
+ * request; undefined drops the image with a text note.
+ */
+ resolveImage?: (ref: ImageRef) => string | undefined;
+}
+
+/**
+ * The `custom_tool_call_output.output` parts for `output`: Codex's header, the
+ * output items, the error, truncated to the token budget.
+ */
+export function formatExecOutput(
+ output: ExecOutput,
+ options: FormatExecOutputOptions
+): ResponsesOutputPart[] {
+ const body: ResponsesOutputPart[] = [];
+ for (const part of output.parts) {
+ if (part.type === "text") {
+ body.push({ type: "input_text", text: part.text });
+ continue;
+ }
+ const url = options.resolveImage?.(part.ref);
+ if (url) body.push({ type: "input_image", image_url: url });
+ else {
+ body.push({
+ type: "input_text",
+ text: `[image ${part.ref.index} of ${part.ref.toolUseId} is no longer in the conversation]`,
+ });
+ }
+ }
+ if (output.error !== undefined && output.error !== "") {
+ body.push({ type: "input_text", text: `Script error:\n${output.error}` });
+ }
+ const maxBytes = clampExecOutputTokens(options.maxOutputTokens) * BYTES_PER_TOKEN;
+ const truncated = truncateParts(body, maxBytes);
+ const head: ResponsesOutputPart[] = [{ type: "input_text", text: execOutputHeader(output) }];
+ if (truncated.truncated) {
+ head.push({
+ type: "input_text",
+ text: `Warning: truncated output (original token count: ${Math.ceil(truncated.totalBytes / BYTES_PER_TOKEN)})\nTotal output lines: ${truncated.totalLines}\n\n`,
+ });
+ }
+ return [...head, ...truncated.parts];
+}
diff --git a/packages/cli/src/code-mode/sandbox/prelude.ts b/packages/cli/src/code-mode/sandbox/prelude.ts
new file mode 100644
index 00000000..e4313e88
--- /dev/null
+++ b/packages/cli/src/code-mode/sandbox/prelude.ts
@@ -0,0 +1,116 @@
+/**
+ * The guest-side prelude, evaluated in every script's QuickJS context before
+ * the model's code.
+ *
+ * It is ONE function expression the host calls with the bridge object, so the
+ * host functions (`call`, `text`, `register`) live only in this closure and are
+ * never reachable from the global object. It defines the four globals the exec
+ * description promises — `text`, `exit`, `tools`, `ALL_TOOLS` — as
+ * non-writable, non-configurable properties.
+ *
+ * Every intrinsic it uses is captured into a closure constant when it loads
+ * (`$apply`, `$slice`, `$String`, …) and called through `$apply`, so a script
+ * that later overwrites `String.prototype.slice`, `Reflect` or
+ * `Function.prototype.call` cannot change what the bridge does. The host
+ * never trusts the guest's slicing either: it re-checks every string it
+ * receives (`script-runtime.ts`).
+ *
+ * Isolation: `SharedArrayBuffer`, `Atomics`, `WeakRef` and
+ * `FinalizationRegistry` are deleted; `console` and timers are never defined
+ * (as in Codex); `Date` is kept (as in Codex); `Math.random` is replaced by a
+ * PRNG seeded from the exec call id, so a re-run of the same script draws the
+ * same numbers.
+ */
+
+/** The exit sentinel's marker property, for diagnostics only (identity is what counts). */
+export const EXIT_SENTINEL_TAG = "__claudish_exit__";
+
+/**
+ * The prelude source. Called as `prelude(bridge, seed, identsJson, allToolsJson)`:
+ * - `bridge.call(ident, args)` → a promise for the nested tool's result;
+ * - `bridge.text(string)` → appends one output item (host enforces the budget);
+ * - `bridge.register(cut, exitSentinel)` → hands the host the trusted slice
+ * function and the exit sentinel object it compares rejections against.
+ */
+export const PRELUDE_SOURCE = `(function (bridge, seed, identsJson, allToolsJson) {
+ "use strict";
+ const $apply = Reflect.apply;
+ const $String = String;
+ const $stringify = JSON.stringify;
+ const $parse = JSON.parse;
+ const $slice = String.prototype.slice;
+ const $freeze = Object.freeze;
+ const $create = Object.create;
+ const $defineProperty = Object.defineProperty;
+ const $isArray = Array.isArray;
+ const $imul = Math.imul;
+ const $Promise = Promise;
+ const $promiseReject = Promise.reject;
+ const $call = bridge.call;
+ const $text = bridge.text;
+ const $register = bridge.register;
+
+ const EXIT = $freeze({ ${EXIT_SENTINEL_TAG}: true });
+ $apply($register, undefined, [function (s, n) { return $apply($slice, s, [0, n]); }, EXIT]);
+
+ function toText(value) {
+ if (typeof value === "string") return value;
+ if (value === undefined || value === null || typeof value === "number" ||
+ typeof value === "boolean" || typeof value === "bigint") {
+ return $String(value);
+ }
+ try {
+ const s = $apply($stringify, undefined, [value]);
+ if (typeof s === "string") return s;
+ } catch (e) {}
+ try { return $String(value); } catch (e) { return "[value could not be stringified]"; }
+ }
+
+ function text(value) {
+ $apply($text, undefined, [toText(value)]);
+ }
+
+ function exit() {
+ throw EXIT;
+ }
+
+ const idents = $apply($parse, undefined, [identsJson]);
+ const tools = $create(null);
+ for (let i = 0; i < idents.length; i++) {
+ const ident = idents[i];
+ const fn = function (args) {
+ if (typeof args !== "object" || args === null || $apply($isArray, undefined, [args])) {
+ return $apply($promiseReject, $Promise, [
+ "claudish: tools." + ident + " takes an object as its argument; this call was not run",
+ ]);
+ }
+ return $apply($call, undefined, [ident, args]);
+ };
+ $defineProperty(tools, ident, { value: fn, enumerable: true });
+ }
+ $freeze(tools);
+
+ const allTools = $apply($parse, undefined, [allToolsJson]);
+ for (let i = 0; i < allTools.length; i++) $freeze(allTools[i]);
+ $freeze(allTools);
+
+ let state = seed >>> 0;
+ function random() {
+ state = (state + 0x6d2b79f5) | 0;
+ let t = $imul(state ^ (state >>> 15), 1 | state);
+ t = (t + $imul(t ^ (t >>> 7), 61 | t)) ^ t;
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ }
+ $defineProperty(Math, "random", { value: random, writable: false, configurable: false });
+
+ delete globalThis.SharedArrayBuffer;
+ delete globalThis.Atomics;
+ delete globalThis.WeakRef;
+ delete globalThis.FinalizationRegistry;
+
+ const fixed = { writable: false, configurable: false, enumerable: false };
+ $defineProperty(globalThis, "text", { value: text, ...fixed });
+ $defineProperty(globalThis, "exit", { value: exit, ...fixed });
+ $defineProperty(globalThis, "tools", { value: tools, ...fixed });
+ $defineProperty(globalThis, "ALL_TOOLS", { value: allTools, ...fixed });
+})`;
diff --git a/packages/cli/src/code-mode/sandbox/quickjs-loader.ts b/packages/cli/src/code-mode/sandbox/quickjs-loader.ts
new file mode 100644
index 00000000..062ba83e
--- /dev/null
+++ b/packages/cli/src/code-mode/sandbox/quickjs-loader.ts
@@ -0,0 +1,213 @@
+/**
+ * The QuickJS wasm module behind the exec sandbox: loaded lazily, once per
+ * process, and only by a code-mode request.
+ *
+ * Packaging (C3 spike, recorded in the implementation log): the `-singlefile-`
+ * sync release variant (`@jitl/quickjs-singlefile-mjs-release-sync`) carries
+ * the wasm inlined as base64, so ONE import path works from `src/`, from the
+ * bundled `dist/index.js` and from a `bun build --compile` binary, with no
+ * wasm asset to copy. Both packages are imported dynamically: a classic
+ * provider never evaluates them.
+ *
+ * One module serves every script; each script gets its own runtime + context
+ * (`script-runtime.ts`). The lease enforces two process-wide policies:
+ *
+ * - at most `MAX_LIVE_RUNTIMES` runtimes live at once (one running plus
+ * suspended ones waiting on Claude Code); admitting one more evicts the
+ * least recently active suspended runtime, whose record then goes lost;
+ * - when no runtime is live and the module's wasm memory exceeds
+ * `RECYCLE_WASM_BYTES`, the module is dropped and the next script reloads it
+ * (~11 ms), because wasm linear memory never shrinks.
+ *
+ * A wasm `RuntimeError` or QuickJS assertion anywhere poisons the module: it is
+ * dropped, every runtime in it is treated as lost (handles abandoned with the
+ * module, never disposed), and the next script loads a fresh one.
+ */
+
+import type { QuickJSWASMModule } from "quickjs-emscripten-core";
+import { log } from "../../logger.js";
+
+/** One running + up to 31 suspended runtimes: ≤ 1 GiB of the 2 GiB wasm ceiling at 32 MiB each. */
+export const MAX_LIVE_RUNTIMES = 32;
+/** Wasm memory above which an idle module is dropped. */
+export const RECYCLE_WASM_BYTES = 256 * 1024 * 1024;
+/**
+ * Wasm memory a slice may not grow the module past. QuickJS's per-runtime
+ * memory limit does NOT bound the module's linear memory: measured in the C3
+ * spike, `a.push("x".repeat(1024) + a.length)` under a 32 MiB runtime limit
+ * grew the module to 2048 MiB (the wasm maximum) in 3.8 s before QuickJS
+ * reported out of memory, and an object-push loop reached 143 MiB. A slice
+ * that grows the module past this ceiling is interrupted as out of memory, and
+ * the module is retired so the next script starts in a fresh one.
+ */
+export const WASM_CEILING_BYTES = 1024 * 1024 * 1024;
+
+/** A runtime the lease tracks for the live cap and LRU eviction. */
+export interface LeasedRuntime {
+ /** Last time the runtime ran a slice (ms). */
+ lastActive: number;
+ /** True while a slice is executing (never evicted then). */
+ running: boolean;
+ /** Dispose the runtime because the cap needs its slot; the owner marks its record lost. */
+ evict(): void;
+ /** The module was poisoned: drop every handle without disposing. */
+ abandon(): void;
+}
+
+/** The loaded module plus the process-wide runtime bookkeeping. */
+export class QuickJSModuleLease {
+ readonly module: QuickJSWASMModule;
+ private readonly live = new Set<LeasedRuntime>();
+ private poisonedReason: string | undefined;
+ private retired = false;
+
+ constructor(module: QuickJSWASMModule) {
+ this.module = module;
+ }
+
+ /** True once the module failed internally; no new runtime may be created in it. */
+ get poisoned(): boolean {
+ return this.poisonedReason !== undefined;
+ }
+
+ /** True when this lease is no longer the current module (poisoned or recycled). */
+ get usable(): boolean {
+ return !this.poisoned && !this.retired;
+ }
+
+ get liveCount(): number {
+ return this.live.size;
+ }
+
+ /**
+ * Register a new runtime. At the cap, the least recently active suspended
+ * runtime is evicted first. Returns false when no slot can be freed (every
+ * live runtime is running), in which case the caller must not create one.
+ */
+ admit(runtime: LeasedRuntime): boolean {
+ while (this.live.size >= MAX_LIVE_RUNTIMES) {
+ let oldest: LeasedRuntime | undefined;
+ for (const candidate of this.live) {
+ if (candidate.running) continue;
+ if (!oldest || candidate.lastActive < oldest.lastActive) oldest = candidate;
+ }
+ if (!oldest) return false;
+ this.live.delete(oldest);
+ log(
+ `[CodeMode] sandbox: ${MAX_LIVE_RUNTIMES} live scripts; evicting the least recently used`
+ );
+ try {
+ oldest.evict();
+ } catch (err) {
+ this.poison(`evicting a runtime threw: ${err}`);
+ return false;
+ }
+ }
+ this.live.add(runtime);
+ return true;
+ }
+
+ /** A runtime was disposed by its owner. May recycle an idle, oversized module. */
+ release(runtime: LeasedRuntime): void {
+ this.live.delete(runtime);
+ if (this.live.size === 0 && !this.retired && this.wasmBytes() > RECYCLE_WASM_BYTES) {
+ this.retired = true;
+ dropCurrent(this);
+ log("[CodeMode] sandbox: idle module over 256 MiB of wasm memory; dropped for reload");
+ }
+ }
+
+ /**
+ * Stop admitting scripts into this module (its wasm memory is over the
+ * ceiling and never shrinks); the scripts already in it finish normally.
+ */
+ retire(reason: string): void {
+ if (this.retired) return;
+ this.retired = true;
+ dropCurrent(this);
+ log(`[CodeMode] sandbox module retired: ${reason}`);
+ }
+
+ /**
+ * The module failed internally (wasm trap, QuickJS assertion, a library
+ * lifetime error). Every live runtime is abandoned and the module dropped.
+ */
+ poison(reason: string): void {
+ if (this.poisonedReason !== undefined) return;
+ this.poisonedReason = reason;
+ log(`[CodeMode] sandbox module poisoned: ${reason}`);
+ const runtimes = [...this.live];
+ this.live.clear();
+ for (const runtime of runtimes) {
+ try {
+ runtime.abandon();
+ } catch {
+ // Abandoning only drops host references; nothing to recover.
+ }
+ }
+ dropCurrent(this);
+ }
+
+ /** Current wasm linear memory size; 0 when the library does not expose it. */
+ wasmBytes(): number {
+ try {
+ const heap = (this.module as unknown as { module?: { HEAPU8?: Uint8Array } }).module?.HEAPU8;
+ return heap?.byteLength ?? 0;
+ } catch {
+ return 0;
+ }
+ }
+}
+
+let current: QuickJSModuleLease | undefined;
+let loading: Promise<QuickJSModuleLease | undefined> | undefined;
+/** Set when the packages cannot be imported at all: no retry in this process. */
+let unavailable: string | undefined;
+
+function dropCurrent(lease: QuickJSModuleLease): void {
+ if (current === lease) current = undefined;
+}
+
+async function loadModule(): Promise<QuickJSModuleLease | undefined> {
+ const started = performance.now();
+ try {
+ const core = await import("quickjs-emscripten-core");
+ const variant = await import("@jitl/quickjs-singlefile-mjs-release-sync");
+ const module = await core.newQuickJSWASMModuleFromVariant(variant.default);
+ log(`[CodeMode] sandbox module loaded in ${(performance.now() - started).toFixed(1)} ms`);
+ return new QuickJSModuleLease(module);
+ } catch (err) {
+ unavailable = String(err);
+ log(`[CodeMode] sandbox unavailable: ${unavailable}`);
+ return undefined;
+ }
+}
+
+/**
+ * The current module, loading it on first use (single-flight). Undefined when
+ * QuickJS cannot be loaded in this process. Never throws.
+ */
+export async function loadQuickJSModule(): Promise<QuickJSModuleLease | undefined> {
+ if (current?.usable) return current;
+ if (unavailable !== undefined) return undefined;
+ if (!loading) {
+ loading = loadModule().then((lease) => {
+ if (lease) current = lease;
+ return lease;
+ });
+ loading.finally(() => {
+ loading = undefined;
+ });
+ }
+ return loading;
+}
+
+/** The current module when one is loaded and usable; never loads. */
+export function currentQuickJSModule(): QuickJSModuleLease | undefined {
+ return current?.usable ? current : undefined;
+}
+
+/** Whether a sandbox can run in this process (loads the module on first call). */
+export async function isSandboxAvailable(): Promise<boolean> {
+ return (await loadQuickJSModule()) !== undefined;
+}
diff --git a/packages/cli/src/code-mode/sandbox/script-runtime.ts b/packages/cli/src/code-mode/sandbox/script-runtime.ts
new file mode 100644
index 00000000..cb6f499d
--- /dev/null
+++ b/packages/cli/src/code-mode/sandbox/script-runtime.ts
@@ -0,0 +1,707 @@
+/**
+ * One exec script in its own QuickJS runtime + context, suspended across
+ * Claude Code round trips.
+ *
+ * `tools.X(args)` returns a deferred QuickJS promise and records a nested call;
+ * after a slice (`start` or `resume`, then the job queue drained) every call
+ * created in that slice IS the batch of tool_use blocks for the downstream
+ * message, so `Promise.all` lands all of its calls in one batch with no extra
+ * logic. Claude Code's tool_results come back on a later request and are fed in
+ * by `resume`: a result resolves its call with the result text, an `is_error`
+ * result REJECTS it with a plain string (as Codex rejects nested tool errors),
+ * so `Promise.allSettled` sees `{status:"rejected", reason:"…"}`.
+ *
+ * Settlement order after every slice (architecture §5.6):
+ * 1. the top-level promise's state is read FIRST: fulfilled, or rejected with
+ * the `exit()` sentinel → completed, and every call still outstanding is
+ * discarded (it never runs — unlike Codex, where an unawaited call may
+ * already have run); rejected otherwise → failed;
+ * 2. pending with ≥ 1 call created in this slice → blocked(calls);
+ * 3. pending with none → failed: the script awaits something that can never
+ * settle;
+ * 4. CPU budget or memory exhausted → failed.
+ *
+ * Handle ownership (pinned by the C3 spike): a host function's RETURNED handle
+ * is consumed by the library (it dups the value for QuickJS and disposes the
+ * handle at scope end), so a deferred's `handle` is dead once returned and this
+ * runtime owns only each deferred's resolve/reject functions. `dispose()` is
+ * idempotent and runs on every terminal transition: unsettled deferreds, the
+ * top-level promise handle, the trusted helper handles, the context, the
+ * runtime — in that order. A wasm trap or library lifetime error anywhere
+ * poisons the module (`quickjs-loader.ts`); the script is then lost.
+ *
+ * The interrupt handler can only TERMINATE a slice, never yield it (R2 §2), so
+ * the CPU budget is cumulative across slices and also the longest one slice can
+ * block the event loop.
+ */
+
+import { createHash } from "node:crypto";
+import type {
+ QuickJSContext,
+ QuickJSDeferredPromise,
+ QuickJSHandle,
+ QuickJSRuntime,
+} from "quickjs-emscripten-core";
+import type { ExecToolMeta } from "../exec-tool.js";
+import {
+ type ExecOutput,
+ type ImageRef,
+ type OutputPart,
+ mapScriptStack,
+ parseExecPragma,
+} from "../output.js";
+import type { ToolNameTable } from "../tool-names.js";
+import { PRELUDE_SOURCE } from "./prelude.js";
+import {
+ type LeasedRuntime,
+ type QuickJSModuleLease,
+ WASM_CEILING_BYTES,
+} from "./quickjs-loader.js";
+
+export type { ExecOutput, ImageRef, OutputPart } from "../output.js";
+
+/** One nested tool call a script made: `seq` orders it within the script. */
+export type NestedCall = {
+ seq: number;
+ ident: string;
+ name: string;
+ input: Record<string, unknown>;
+};
+
+/** Claude Code's answer to one nested call. `ok: false` rejects it with `text`. */
+export type NestedResult = { seq: number; ok: boolean; text: string; images?: ImageRef[] };
+
+export type ScriptStep =
+ | { kind: "blocked"; calls: [NestedCall, ...NestedCall[]] }
+ | { kind: "done"; output: ExecOutput };
+
+export interface ScriptRuntime {
+ start(source: string): ScriptStep;
+ resume(results: NestedResult[]): ScriptStep;
+ dispose(): void;
+ /**
+ * End a suspended script from outside (interrupt, conversation moved on):
+ * a `terminated` output carrying what it produced so far plus `note`.
+ */
+ terminate(note: string): ExecOutput;
+ /** False after dispose, eviction or a poisoned module: the script state is gone. */
+ readonly alive: boolean;
+ /** True when the module was poisoned or the runtime evicted (its record goes lost). */
+ readonly lost: boolean;
+}
+
+/** claudish policy; model-independent. */
+export interface SandboxLimits {
+ memoryBytes: number;
+ maxStackBytes: number;
+ cpuMs: number;
+ sourceBytes: number;
+ callsPerBatch: number;
+ callsPerScript: number;
+ callInputBytes: number;
+ batchInputBytes: number;
+ resultBytes: number;
+ resultBytesPerScript: number;
+ outputBytes: number;
+}
+
+export const DEFAULT_SANDBOX_LIMITS: SandboxLimits = {
+ memoryBytes: 32 * 1024 * 1024,
+ maxStackBytes: 512 * 1024,
+ cpuMs: 2_000,
+ sourceBytes: 256 * 1024,
+ callsPerBatch: 32,
+ callsPerScript: 256,
+ callInputBytes: 2 * 1024 * 1024,
+ batchInputBytes: 8 * 1024 * 1024,
+ resultBytes: 1024 * 1024,
+ resultBytesPerScript: 8 * 1024 * 1024,
+ outputBytes: 1024 * 1024,
+};
+
+export interface CreateScriptRuntimeOptions {
+ tools: ToolNameTable;
+ /** `ALL_TOOLS` entries; default: names only. */
+ allTools?: readonly ExecToolMeta[];
+ limits?: Partial<SandboxLimits>;
+ /** Seeds `Math.random` (the exec call id). */
+ seed: string;
+ module: QuickJSModuleLease;
+ /** Called when the lease evicts this runtime for the live cap (its record goes lost). */
+ onEvicted?: () => void;
+ /** Test seam: default `performance.now`. */
+ now?: () => number;
+}
+
+interface PendingCall {
+ call: NestedCall;
+ deferred: QuickJSDeferredPromise;
+}
+
+const RESULT_TRUNCATED_MARKER = "\n[claudish: tool result truncated at 1 MiB]";
+
+function seedNumber(seed: string): number {
+ return createHash("sha256").update(seed).digest().readUInt32BE(0);
+}
+
+function utf8Bytes(text: string): number {
+ return Buffer.byteLength(text, "utf8");
+}
+
+/** `1 MiB` for whole MiB, else `<n>-byte`. */
+function describeBytes(bytes: number): string {
+ const mib = bytes / (1024 * 1024);
+ return Number.isInteger(mib) ? `${mib} MiB` : `${bytes}-byte`;
+}
+
+/** An Error-shaped value as `Name: message` plus its stack, lines mapped to the input. */
+function describeErrorObject(v: { name?: unknown; message: string; stack?: unknown }): string {
+ const head = typeof v.name === "string" && v.name ? `${v.name}: ${v.message}` : v.message;
+ const stack = typeof v.stack === "string" ? v.stack.trimEnd() : "";
+ return stack ? `${head}\n${mapScriptStack(stack)}` : head;
+}
+
+/** Codex's rendering of a thrown value: a string as-is, an Error with its stack. */
+function describeGuestError(value: unknown): string {
+ if (typeof value === "string") return value;
+ if (!value || typeof value !== "object") return String(value);
+ const v = value as { message?: unknown };
+ if (typeof v.message === "string") {
+ return describeErrorObject(value as { message: string });
+ }
+ try {
+ return JSON.stringify(value);
+ } catch {
+ return String(value);
+ }
+}
+
+/** A failure that is the guest's (memory, a thrown value), not the library's. */
+class GuestFault extends Error {}
+
+class QuickJSScriptRuntime implements ScriptRuntime, LeasedRuntime {
+ lastActive = 0;
+ running = false;
+
+ private readonly limits: SandboxLimits;
+ private readonly now: () => number;
+ private readonly lease: QuickJSModuleLease;
+ private readonly tools: ToolNameTable;
+ private readonly allTools: readonly ExecToolMeta[];
+ private readonly seed: string;
+ private readonly onEvicted?: () => void;
+
+ private rt: QuickJSRuntime | undefined;
+ private ctx: QuickJSContext | undefined;
+ private topHandle: QuickJSHandle | undefined;
+ private cutHandle: QuickJSHandle | undefined;
+ private exitHandle: QuickJSHandle | undefined;
+
+ private readonly pending = new Map<number, PendingCall>();
+ private sliceCalls: NestedCall[] = [];
+ private sliceInputBytes = 0;
+ private seq = 0;
+ private callCount = 0;
+ private resultBytes = 0;
+
+ private readonly parts: OutputPart[] = [];
+ private outputUsed = 0;
+ private outputDropped = 0;
+
+ private cpuUsed = 0;
+ private sliceStart = -1;
+ private interrupted = false;
+ private wasmExceeded = false;
+ private sliceWasmBytes = 0;
+ private startedAt: number | undefined;
+ private disposed = false;
+ private wasLost = false;
+
+ constructor(opts: CreateScriptRuntimeOptions) {
+ this.limits = { ...DEFAULT_SANDBOX_LIMITS, ...opts.limits };
+ this.now = opts.now ?? (() => performance.now());
+ this.lease = opts.module;
+ this.tools = opts.tools;
+ this.allTools =
+ opts.allTools ??
+ opts.tools.entries().map((e) => ({ name: e.ident, description: "", inputSchema: {} }));
+ this.seed = opts.seed;
+ this.onEvicted = opts.onEvicted;
+ }
+
+ get alive(): boolean {
+ return !this.disposed;
+ }
+
+ get lost(): boolean {
+ return this.wasLost;
+ }
+
+ // ─── lifecycle ──────────────────────────────────────────────────────
+
+ start(input: string): ScriptStep {
+ this.startedAt = this.now();
+ if (this.rt || this.disposed) return this.fail("claudish: this script was already started");
+ if (utf8Bytes(input) > this.limits.sourceBytes) {
+ return this.fail(
+ `claudish: the script is ${utf8Bytes(input)} bytes; the limit is ${this.limits.sourceBytes}`
+ );
+ }
+ const pragma = parseExecPragma(input);
+ if (pragma.error) return this.fail(pragma.error);
+ if (!this.lease.usable) return this.lose("the sandbox module is unavailable");
+ return this.guard(() => {
+ this.createContext();
+ return this.slice(() => {
+ const ctx = this.requireCtx();
+ const result = ctx.evalCode(`(async () => {\n${pragma.source}\n})()`, "exec.js");
+ if (result.error) {
+ throw new GuestFault(this.consumeError(result.error));
+ }
+ this.topHandle = result.value;
+ });
+ });
+ }
+
+ resume(results: NestedResult[]): ScriptStep {
+ if (this.disposed || !this.ctx || !this.topHandle) {
+ return this.lose("the script is no longer running");
+ }
+ return this.guard(() =>
+ this.slice(() => {
+ const bySeq = new Map<number, NestedResult>();
+ for (const result of results) bySeq.set(result.seq, result);
+ const outstanding = [...this.pending.values()];
+ this.pending.clear();
+ for (const { call, deferred } of outstanding) {
+ const result = bySeq.get(call.seq);
+ if (!result) {
+ this.settle(deferred, false, "no tool_result returned");
+ continue;
+ }
+ this.deliver(deferred, result);
+ }
+ })
+ );
+ }
+
+ terminate(note: string): ExecOutput {
+ const parts = [...this.parts];
+ if (note) parts.push({ type: "text", text: note });
+ const output: ExecOutput = { status: "terminated", wallMs: this.wallMs(), parts };
+ this.dispose();
+ return output;
+ }
+
+ dispose(): void {
+ if (this.disposed) return;
+ this.disposed = true;
+ try {
+ for (const { deferred } of this.pending.values()) {
+ if (deferred.alive) deferred.dispose();
+ }
+ this.pending.clear();
+ for (const handle of [this.topHandle, this.cutHandle, this.exitHandle]) {
+ if (handle?.alive) handle.dispose();
+ }
+ this.topHandle = this.cutHandle = this.exitHandle = undefined;
+ this.ctx?.dispose();
+ this.rt?.dispose();
+ } catch (err) {
+ this.lease.poison(`disposing a script runtime threw: ${err}`);
+ this.wasLost = true;
+ } finally {
+ this.ctx = undefined;
+ this.rt = undefined;
+ this.lease.release(this);
+ }
+ }
+
+ /** LeasedRuntime: the live cap needs this slot. */
+ evict(): void {
+ this.wasLost = true;
+ this.dispose();
+ this.onEvicted?.();
+ }
+
+ /** LeasedRuntime: the module is poisoned; drop handles without touching wasm. */
+ abandon(): void {
+ this.wasLost = true;
+ this.disposed = true;
+ this.pending.clear();
+ this.topHandle = this.cutHandle = this.exitHandle = undefined;
+ this.ctx = undefined;
+ this.rt = undefined;
+ this.onEvicted?.();
+ }
+
+ // ─── context setup ──────────────────────────────────────────────────
+
+ private createContext(): void {
+ if (!this.lease.admit(this)) {
+ throw new GuestFault("claudish: every sandbox slot is running a script; try again");
+ }
+ const rt = this.lease.module.newRuntime();
+ this.rt = rt;
+ rt.setMemoryLimit(this.limits.memoryBytes);
+ rt.setMaxStackSize(this.limits.maxStackBytes);
+ rt.setInterruptHandler(() => {
+ if (this.sliceStart < 0) return false;
+ if (this.cpuUsed + (this.now() - this.sliceStart) > this.limits.cpuMs) {
+ this.interrupted = true;
+ return true;
+ }
+ // The runtime's memory limit does not bound the module's linear memory
+ // (see WASM_CEILING_BYTES); a slice that grows it past the ceiling stops.
+ const wasm = this.lease.wasmBytes();
+ if (wasm > WASM_CEILING_BYTES && wasm > this.sliceWasmBytes) {
+ this.wasmExceeded = true;
+ return true;
+ }
+ return false;
+ });
+ const ctx = rt.newContext();
+ this.ctx = ctx;
+
+ const bridge = ctx.newObject();
+ const call = ctx.newFunction("call", (identH, argsH) => this.onCall(identH, argsH));
+ const text = ctx.newFunction("text", (valueH) => this.onText(valueH));
+ const register = ctx.newFunction("register", (cutH, exitH) => {
+ this.cutHandle = cutH.dup();
+ this.exitHandle = exitH.dup();
+ });
+ ctx.setProp(bridge, "call", call);
+ ctx.setProp(bridge, "text", text);
+ ctx.setProp(bridge, "register", register);
+ call.dispose();
+ text.dispose();
+ register.dispose();
+
+ const prelude = ctx.evalCode(PRELUDE_SOURCE, "prelude.js");
+ if (prelude.error) {
+ bridge.dispose();
+ throw new Error(`prelude failed: ${this.consumeError(prelude.error)}`);
+ }
+ const seed = ctx.newNumber(seedNumber(this.seed));
+ const idents = ctx.newString(JSON.stringify(this.tools.entries().map((e) => e.ident)));
+ const allTools = ctx.newString(JSON.stringify(this.allTools));
+ const applied = ctx.callFunction(prelude.value, ctx.undefined, bridge, seed, idents, allTools);
+ for (const h of [prelude.value, bridge, seed, idents, allTools]) h.dispose();
+ if (applied.error) {
+ throw new Error(`prelude failed: ${this.consumeError(applied.error)}`);
+ }
+ applied.value.dispose();
+ if (!this.cutHandle || !this.exitHandle) throw new Error("prelude did not register");
+ }
+
+ // ─── host functions ─────────────────────────────────────────────────
+
+ private onCall(identH: QuickJSHandle, argsH: QuickJSHandle): QuickJSHandle {
+ const ctx = this.requireCtx();
+ const ident = ctx.typeof(identH) === "string" ? ctx.getString(identH) : "";
+ const name = this.tools.nameFor(ident);
+ if (!name) return this.rejected(`claudish: tools.${ident} is not a tool; see ALL_TOOLS`);
+ if (this.sliceCalls.length >= this.limits.callsPerBatch) {
+ return this.rejected(
+ `claudish: more than ${this.limits.callsPerBatch} tool calls in one batch; this call was not run`
+ );
+ }
+ if (this.callCount >= this.limits.callsPerScript) {
+ return this.rejected(
+ `claudish: more than ${this.limits.callsPerScript} tool calls in one script; this call was not run`
+ );
+ }
+ if (ctx.typeof(argsH) !== "object") {
+ return this.rejected(
+ `claudish: tools.${ident} takes an object as its argument; this call was not run`
+ );
+ }
+ const input = ctx.dump(argsH) as unknown;
+ if (!input || typeof input !== "object" || Array.isArray(input)) {
+ return this.rejected(
+ `claudish: tools.${ident} takes an object as its argument; this call was not run`
+ );
+ }
+ const bytes = utf8Bytes(JSON.stringify(input));
+ if (bytes > this.limits.callInputBytes) {
+ return this.rejected(
+ `claudish: the input to tools.${ident} is ${bytes} bytes; the limit is ${this.limits.callInputBytes}; this call was not run`
+ );
+ }
+ if (this.sliceInputBytes + bytes > this.limits.batchInputBytes) {
+ return this.rejected(
+ `claudish: this batch's tool inputs exceed ${this.limits.batchInputBytes} bytes; this call was not run`
+ );
+ }
+ this.sliceInputBytes += bytes;
+ this.callCount++;
+ const call: NestedCall = {
+ seq: this.seq++,
+ ident,
+ name,
+ input: input as Record<string, unknown>,
+ };
+ const deferred = ctx.newPromise();
+ this.pending.set(call.seq, { call, deferred });
+ this.sliceCalls.push(call);
+ // The library consumes the returned handle; the deferred keeps its resolvers.
+ return deferred.handle;
+ }
+
+ private onText(valueH: QuickJSHandle): void {
+ const ctx = this.requireCtx();
+ if (ctx.typeof(valueH) !== "string") {
+ throw new TypeError("claudish: text() bridge expects a string");
+ }
+ const lengthH = ctx.getProp(valueH, "length");
+ const length = ctx.getNumber(lengthH);
+ lengthH.dispose();
+ const remaining = this.limits.outputBytes - this.outputUsed;
+ if (!(length > 0)) {
+ this.parts.push({ type: "text", text: "" });
+ return;
+ }
+ if (remaining <= 0) {
+ this.outputDropped += length;
+ return;
+ }
+ let received: string;
+ if (length <= remaining) {
+ received = ctx.getString(valueH);
+ } else {
+ const limitH = ctx.newNumber(remaining);
+ const cut = ctx.callFunction(
+ this.requireHandle(this.cutHandle),
+ ctx.undefined,
+ valueH,
+ limitH
+ );
+ limitH.dispose();
+ if (cut.error) {
+ cut.error.dispose();
+ received = "";
+ } else {
+ received = ctx.typeof(cut.value) === "string" ? ctx.getString(cut.value) : "";
+ cut.value.dispose();
+ }
+ }
+ // Never trust the guest's cut: bound what is kept here.
+ const kept = received.length > remaining ? received.slice(0, remaining) : received;
+ this.outputDropped += Math.max(0, length - kept.length);
+ this.outputUsed += kept.length;
+ this.parts.push({ type: "text", text: kept });
+ }
+
+ // ─── slices and settlement ──────────────────────────────────────────
+
+ /** Run `body` as one CPU-budgeted slice, drain the job queue, then settle. */
+ private slice(body: () => void): ScriptStep {
+ const rt = this.requireRt();
+ this.sliceCalls = [];
+ this.sliceInputBytes = 0;
+ this.running = true;
+ this.sliceWasmBytes = this.lease.wasmBytes();
+ this.sliceStart = this.now();
+ try {
+ body();
+ const jobs = rt.executePendingJobs();
+ if (jobs.error) throw new GuestFault(this.consumeError(jobs.error));
+ } finally {
+ this.cpuUsed += this.now() - this.sliceStart;
+ this.sliceStart = -1;
+ this.running = false;
+ this.lastActive = Date.now();
+ }
+ return this.settleTop();
+ }
+
+ private settleTop(): ScriptStep {
+ if (this.interrupted || this.wasmExceeded) return this.cpuExceeded();
+ const ctx = this.requireCtx();
+ const top = this.requireHandle(this.topHandle);
+ const state = ctx.getPromiseState(top);
+ if (state.type === "fulfilled") {
+ if (!state.notAPromise) state.value.dispose();
+ return this.finish("completed");
+ }
+ if (state.type === "rejected") {
+ const isExit = this.exitHandle !== undefined && ctx.sameValue(state.error, this.exitHandle);
+ if (isExit) {
+ state.error.dispose();
+ return this.finish("completed");
+ }
+ return this.finish("failed", this.consumeError(state.error));
+ }
+ const [first, ...rest] = this.sliceCalls;
+ if (first) return { kind: "blocked", calls: [first, ...rest] };
+ return this.finish(
+ "failed",
+ "deadlocked: the script awaits a promise that can never settle (no tool calls are pending)"
+ );
+ }
+
+ /** The slice was interrupted: CPU budget, or the module's wasm ceiling. */
+ private cpuExceeded(): ScriptStep {
+ if (this.wasmExceeded) {
+ this.lease.retire("a script grew its wasm memory past the ceiling");
+ return this.finish(
+ "failed",
+ "out of memory: the script grew the sandbox's memory past claudish's limit"
+ );
+ }
+ return this.finish(
+ "failed",
+ `interrupted: exceeded the ${this.limits.cpuMs / 1000} s CPU budget`
+ );
+ }
+
+ /** A terminal step: the output so far (+ the drop warning), then dispose. */
+ private finish(status: "completed" | "failed", error?: string): ScriptStep {
+ const parts = [...this.parts];
+ if (this.outputDropped > 0) {
+ parts.push({
+ type: "text",
+ text: `Warning: output exceeded claudish's ${describeBytes(this.limits.outputBytes)} limit; ${this.outputDropped} bytes dropped`,
+ });
+ }
+ const output: ExecOutput = { status, wallMs: this.wallMs(), parts };
+ if (error !== undefined) output.error = error;
+ this.dispose();
+ return { kind: "done", output };
+ }
+
+ private fail(error: string): ScriptStep {
+ return this.finish("failed", error);
+ }
+
+ /** The script state is gone (poisoned module, eviction). */
+ private lose(reason: string): ScriptStep {
+ this.wasLost = true;
+ return this.finish("failed", `claudish lost this script's state (${reason})`);
+ }
+
+ /**
+ * Run `fn`, mapping a guest fault to a failed script and any other throw (a
+ * wasm trap, a library lifetime error) to a poisoned module.
+ */
+ private guard(fn: () => ScriptStep): ScriptStep {
+ try {
+ return fn();
+ } catch (err) {
+ if (err instanceof GuestFault) {
+ if (this.interrupted || this.wasmExceeded) return this.cpuExceeded();
+ return this.fail(err.message);
+ }
+ this.lease.poison(String(err));
+ this.wasLost = true;
+ this.abandonAfterPoison();
+ return {
+ kind: "done",
+ output: {
+ status: "failed",
+ wallMs: this.wallMs(),
+ parts: [...this.parts],
+ error: "claudish's sandbox failed internally; this script's state is lost",
+ },
+ };
+ }
+ }
+
+ private abandonAfterPoison(): void {
+ if (this.disposed) return;
+ this.abandon();
+ }
+
+ // ─── result delivery ────────────────────────────────────────────────
+
+ private deliver(deferred: QuickJSDeferredPromise, result: NestedResult): void {
+ for (const ref of result.images ?? []) this.parts.push({ type: "image", ref });
+ let text = typeof result.text === "string" ? result.text : String(result.text);
+ if (utf8Bytes(text) > this.limits.resultBytes) {
+ const cut = Buffer.from(text, "utf8")
+ .subarray(0, this.limits.resultBytes)
+ .toString("utf8")
+ .replace(/�$/, "");
+ text = `${cut}${RESULT_TRUNCATED_MARKER}`;
+ }
+ const bytes = utf8Bytes(text);
+ if (this.resultBytes + bytes > this.limits.resultBytesPerScript) {
+ this.settle(
+ deferred,
+ false,
+ `claudish: this script's tool results exceed ${this.limits.resultBytesPerScript} bytes; this result was not delivered`
+ );
+ return;
+ }
+ this.resultBytes += bytes;
+ this.settle(deferred, result.ok, text);
+ }
+
+ private settle(deferred: QuickJSDeferredPromise, ok: boolean, text: string): void {
+ const ctx = this.requireCtx();
+ const value = ctx.newString(text);
+ if (ok) deferred.resolve(value);
+ else deferred.reject(value);
+ value.dispose();
+ deferred.dispose();
+ }
+
+ /** A promise handle already rejected with `message` (consumed by the library on return). */
+ private rejected(message: string): QuickJSHandle {
+ const ctx = this.requireCtx();
+ const deferred = ctx.newPromise();
+ const value = ctx.newString(message);
+ deferred.reject(value);
+ value.dispose();
+ return deferred.handle;
+ }
+
+ // ─── helpers ────────────────────────────────────────────────────────
+
+ private consumeError(handle: QuickJSHandle): string {
+ const ctx = this.requireCtx();
+ let value: unknown;
+ try {
+ value = ctx.dump(handle);
+ } finally {
+ if (handle.alive) handle.dispose();
+ }
+ const text = describeGuestError(value);
+ if (/out of memory/i.test(text)) return "out of memory: the script exceeded its 32 MiB heap";
+ return text;
+ }
+
+ private wallMs(): number | undefined {
+ return this.startedAt === undefined ? undefined : Math.max(0, this.now() - this.startedAt);
+ }
+
+ private requireCtx(): QuickJSContext {
+ if (!this.ctx) throw new Error("script context is gone");
+ return this.ctx;
+ }
+
+ private requireRt(): QuickJSRuntime {
+ if (!this.rt) throw new Error("script runtime is gone");
+ return this.rt;
+ }
+
+ private requireHandle(handle: QuickJSHandle | undefined): QuickJSHandle {
+ if (!handle?.alive) throw new Error("script handle is gone");
+ return handle;
+ }
+}
+
+/**
+ * A runtime for one exec script in `module`. Synchronous: the module must
+ * already be loaded (`loadQuickJSModule`). The runtime and context are created
+ * by `start`.
+ */
+export function createScriptRuntime(opts: CreateScriptRuntimeOptions): ScriptRuntime {
+ return new QuickJSScriptRuntime(opts);
+}
+
+/** For logs: a step in one line. */
+export function describeStep(step: ScriptStep): string {
+ if (step.kind === "blocked") return `blocked on ${step.calls.length} call(s)`;
+ return `${step.output.status}${step.output.error ? ` (${step.output.error.split("\n")[0]})` : ""}`;
+}