codemode tool, and it has zero dependencies on other Atomic packages. See Standalone libraries for all standalone packages.
Installation
@bastani/atomic-codemode:CodemodeSandbox,loadQuickJSWasm,parseCodemodeSource,renderDeclarations, and worker runtime for Node and Bun.@bastani/atomic-codemode/portable:RemoteCodemodeSandboxandInlineCodemodeSandboxwith zero Node.js imports.@bastani/atomic-codemode/cloudflare:CodemodeSandboxDurableObjectandcreateInlineCodemodeSandboxfor Cloudflare Workers.@bastani/atomic-codemode/declarations: LightweightrenderDeclarations()with no worker or WebAssembly dependencies.@bastani/atomic-codemode/source: LightweightparseCodemodeSource(),CodemodeSourceError, andCODEMODE_SOURCE_GRAMMAR.@bastani/atomic-codemode/worker: Worker entrypoint for bundled Node/Bun hosts.
Usage on Node and Bun
code runs as the body of an async function, so return and top-level await work. Inside the script, every sandbox provides:
tools.<name>(args): Returns a promise; arguments and results pass through JSON round trips. RejectedErrorinstances cross into the script with the same message plus any extra JSON-serializable own properties (such ascode, excludingname,message, andstack). Hyphenated or special names are also exposed viatoCodemodeIdentifier, somy-toolworks as bothtools.my_toolandtools["my-tool"].ALL_TOOLS: Array of{ name, description }for every tool, using the identifier form forname.text(value)andconsole.*:text()appends a text item toresult.output(JSON-stringifying non-strings);console.log/info/warn/error/debugappend text items withconsole: true.image(urlOrItem): Appends an image item from a base64data:URL,{ image_url }, or an image block ({ type: "image", data, mimeType }). Remote URLs are rejected.exit(): Ends the script immediately with a successful result, preserving output and store writes.globals: Optional host helpers callable as top-level functions (or dottednamespace.memberon a frozen object) that are not recorded inresult.calls. Reserved names (tools,ALL_TOOLS,console,text,image,exit,globalThis,store,load) cannot be shadowed. Setspread: trueto pass all arguments as an array, andsignatureto customize the generated declaration.store(key, value)/load(key): Synchronous JSON key-value store across runs (see Store).- Frozen built-in prototypes: Built-in prototypes (
Object.prototype,Array.prototype, etc.) are frozen before execution; monkey-patching throws aTypeError(instance overrides ofconstructor,name,message,toString,toLocaleString,valueOf, andtoJSONremain allowed). - No ambient capabilities: No timers,
fetch,process,require, modules, orWebAssembly.evalandFunctionevaluate only inside the same VM.
timeoutMs is omitted, CodemodeSandbox defaults to 300,000 ms (5 minutes). Pass timeoutMs: Infinity to disable the deadline so scripts run until completion or signal abort. A script that awaits a promise nothing can settle fails immediately instead of hanging. memoryLimitBytes caps the VM heap (InternalError: out of memory when exceeded).
Worker termination and concurrency limits: Aborts, timeouts, and
close() request worker termination and unref the worker without waiting for it to exit. On Bun, long-running built-ins such as String.prototype.indexOf may not poll QuickJS’s interrupt handler and can delay process exit until the built-in returns. Use onWorkerStarted(exited) to hold concurrency slots until actual worker exit, or acquireWorker() (synchronous callback called immediately before creating each worker; throw to reject admission, or return a release callback) to enforce shared admission limits across sandbox instances.Store
store() and load() let scripts carry JSON state across executions without the sandbox persisting anything itself. Pass saved values in options.store, and apply result.storeWrites ({ set, delete }) when result.ok is true (failed executions report no writes):
load() returns a copy so mutations do not affect the store, and storing undefined deletes a key. Individual values cap at MAX_STORE_VALUE_CHARS (256 Ki) JSON characters, and total stored data caps at MAX_STORE_TOTAL_CHARS (1 Mi) characters (RangeError inside the script when exceeded).
Source format
parseCodemodeSource() accepts an optional // @options: JSON header on line 1:
max_output_tokens: non-negative safe integer (>= 0), returned asoptions.maxOutputTokens.timeout_ms: positive safe integer, returned asoptions.timeoutMs.
parseCodemodeSource() returns { code, options: { maxOutputTokens?, timeoutMs? } } and replaces line 1 with a blank line so stack-trace line numbers match the input. Empty input, invalid JSON, unknown fields, header-only input, or a header after line 1 throws CodemodeSourceError. CODEMODE_SOURCE_GRAMMAR exports a Lark grammar for grammar-constrained tool calling (both also exported from @bastani/atomic-codemode/source). The sandbox does not enforce these parsed options automatically; your caller applies them.
Declarations for the model
Tools and globals can carrydescription, inputSchema, and outputSchema (JSON Schema). renderDeclarations() generates compact TypeScript declarations for a model-facing tool description:
// comments, and extra JSON Schema constraints render as tags (// @integer @minimum 1 @default 20, dropped first if a declaration hits the size limit). Local $refs (#/$defs/..., #/definitions/...) expand inline; recursive and remote references render as unknown. Schemas shape declarations only—they do not validate runtime values.
Results
execute() never rejects for script failures. When result.ok is false, result.error.kind is one of:
result.output holds text and image blocks in production order (including on failures), capped at MAX_OUTPUT_CHARS (16 Mi characters) and MAX_OUTPUT_ITEMS (100,000 items)—exceeding either fails the script with an uncatchable RangeError.
result.calls records every tool call with status: "ok" | "error" | "cancelled". Any unawaited call still running when the script returns is aborted via its signal and recorded as "cancelled".
Using with agent-core
Expose an@bastani/atomic-agent-core Agent’s tools to a sandbox and wrap execute() as an AgentTool:
result.output items already match @bastani/atomic-ai’s TextContent and ImageContent. Calling tool.execute() directly bypasses beforeToolCall and afterToolCall; route nested calls through runToolCall() from @bastani/atomic-agent-core so argument validation and hooks apply consistently:
execute, throwing when outcome.isError is true so the script catches the failure.
Deterministic runs
sandbox.start(code, options) runs a script deterministically so a durable host can replay it after restarts from a log of call results (execute() is unaffected):
- Time:
Date.now()starts atstartedAtand advances monotonically from each delivered result’snow;performance.now()counts fromstartedAt. - Randomness, timezone, and GC:
Math.random()usesseed, timezone is fixed to UTC, andWeakRef/FinalizationRegistryare absent. - Strict result order: Results are delivered with sequential numbers (
1,2, …) and applied in exact order regardless of transport arrival.
timeoutMs is passed. Replaying the same script, startedAt, seed, tools, globals, store, and ordered results produces identical calls and output on any VM with the same fingerprint. Abort signal to terminate a run with an uncatchable error.
Bundled Node and Bun hosts
By default,CodemodeSandbox reads quickjs-wasi/quickjs.wasm and starts its worker file next to this package. In bundled executables, pass both explicitly:
"./src/codemode-worker.ts").
Usage on Cloudflare Workers
Cloudflare Workers cannot spawn Node worker threads or compile WebAssembly at runtime. UseRemoteCodemodeSandbox (from @bastani/atomic-codemode/portable, which has zero Node imports) paired with CodemodeSandboxDurableObject (from @bastani/atomic-codemode/cloudflare) in a separate Worker so synchronous QuickJS compute bursts never block your agent session’s Durable Object.
A complete deployment example lives in packages/codemode/examples/cloudflare.
Deploying the sandbox Worker
@bastani/atomic-codemode and run npx wrangler deploy. Wrangler bundles QuickJS (~640 KB) as a precompiled WebAssembly module; the Durable Object stores no state.
Calling it from the agent Worker
Bind the class usingscript_name (binding a class in the agent’s own Worker would reintroduce main-thread blocking):
RemoteCodemodeSandbox from /portable in the agent Worker so QuickJS is not bundled there. Run both Workers locally with wrangler dev -c agent/wrangler.jsonc -c sandbox/wrangler.jsonc.
Cloudflare limits and inline execution
- Interrupt budget: Tight loops without tool calls are bounded by
DEFAULT_INTERRUPT_BUDGET(100,000polls, ~10 seconds on Workers) and fail withkind: "timeout". Keep this below the Worker’scpu_mslimit so scripts fail cleanly instead of resetting the Durable Object. - Memory & caps: Default 32 MiB per VM (shared within the isolate’s 128 MB cap). Subclass
CodemodeSandboxDurableObjectand overrideprotected maxInterruptBudget/protected maxMemoryLimitBytesto adjust caps. - Aborts, timeouts, and billing:
timeoutMsandsignalsettle immediately in the caller (kind: "timeout"or"aborted"); the remote VM stops at its next tool call or interrupt budget. Each execution bills one Durable Object request for wall-clock duration. - Calling thread (
InlineCodemodeSandbox): When blocking a stateless request Worker is acceptable, usecreateInlineCodemodeSandbox({ tools, timeoutMs, interruptBudget })from@bastani/atomic-codemode/cloudflare(lowers QuickJS’s stack guard to 256 KiB; blocks the caller during compute).
How it works
EachCodemodeSandbox.execute() spawns a worker thread that instantiates a fresh QuickJS WebAssembly instance with its own linear memory, importing only a minimal WASI shim (clock, random, discarded stdio) and one host-call bridge. Tool calls travel to the host thread over worker messages; timeouts and aborts set a shared interrupt flag polled by QuickJS and call worker.terminate().
Runtime notes
- Node and Bun enforce memory limits, interrupts, and catchable
RangeErrorstack guards for deep recursion. - Stack traces use QuickJS frames (
at f (codemode.js:2:31)), prefixed withName: messagelike V8; line numbers match the script (column numbers on line 1 are shifted by the async wrapper prefix). - QuickJS is an interpreter: glue code and result filtering run quickly, while heavy CPU computation is slower than in V8.