- RemoteCodemodeSandbox ran start() step by step, saving the whole heap after every step (and failing on a WeakRef). Sandboxes now open a run with its lifetime (session or saved), and a start() run is one session on the remote, as on main. - start()'s tests run on the worker, inline, and remote sandboxes again, with main's cases for globals numbered with tools and rejections carrying their properties; a test checks a remote start() takes no steps. - start()'s fingerprint names the run's actual CPU budget (none, a number, or remote), not "default" for every sandbox. - start()'s call records carry the module; the dropped calls are computed once. - Durable skips a namespace named like a built-in global or a global's namespace (models) as a module, instead of failing every script; pi-codemode exports CODEMODE_RESERVED_NAMES from /declarations for it. - Docs: CodemodeHostCall.id, durable's call keys and schema, the CHANGELOGs (start()'s jsName, the un-awaited calls rule, /remote, strict mode and UTC in the coding agent), the README on dropped calls and remote start() runs, and the coding agent's Bun caveat, which no longer holds (checked on Bun 1.4.4: a long sort or split stops at the deadline). |
||
|---|---|---|
| .. | ||
| examples/cloudflare | ||
| src | ||
| test | ||
| CHANGELOG.md | ||
| package.json | ||
| README.md | ||
| tsconfig.build.json | ||
| vitest.config.ts | ||
@earendil-works/pi-codemode
Runs model-written JavaScript and TypeScript in a djs VM (a JavaScript engine compiled to WebAssembly) where the only capability is calling injected tools. Nested tool calls never enter the LLM context; only the script's output and return value do.
Scripts use tools, ALL_TOOLS, text, image, exit, store, and load, and may start with a // @options: line. The coding agent uses it for its built-in codemode tool. It has no pi dependencies and can be used on its own to expose any functions (remote APIs, MCP servers, application services) to model-written scripts.
Every sandbox runs a script in its own VM, a separate wasm instance. Three sandboxes share one API, one script environment, and one result format:
| Sandbox | Import from | Where scripts run |
|---|---|---|
CodemodeSandbox |
@earendil-works/pi-codemode |
a worker thread per run (Node, Bun) |
InlineCodemodeSandbox |
@earendil-works/pi-codemode/portable |
the calling thread (any runtime with WebAssembly: browsers, Cloudflare) |
RemoteCodemodeSandbox |
@earendil-works/pi-codemode/portable |
a Durable Object in a separately deployed Worker |
See Usage on Node and Bun and Usage on Cloudflare Workers. Hosts that keep scripts across restarts use the engine directly: see Saved runs.
Usage on Node and Bun
import { CodemodeSandbox } from "@earendil-works/pi-codemode";
const sandbox = new CodemodeSandbox({
timeoutMs: 60_000,
tools: [
{
name: "read",
execute: async (args, { signal }) => {
const { path } = args as { path: string };
return await readFile(path, "utf8");
},
},
],
});
const result = await sandbox.execute(`
const source = await tools.read({ path: "package.json" });
text("bytes " + source.length);
return JSON.parse(source).name;
`);
console.log(result.output); // [{ type: "text", text: "bytes 1234" }]
if (result.ok) console.log(result.value); // "@earendil-works/pi-codemode"
else console.error(result.error.kind, result.error.message);
await sandbox.close();
code is the body of an async function, JavaScript or TypeScript (types are erased), in strict mode: return and top-level await work. Inside the script, with every sandbox:
tools.<name>(args)returns a promise. Arguments and results make a JSON round trip. A tool that throws rejects with anErrorcarrying the same message. Tool names are also exposed as identifiers: characters that are not valid in identifiers become_(toCodemodeIdentifier), somy-toolistools.my_toolas well astools["my-tool"].ALL_TOOLSlists{ name, description }for every tool ontools, withnameas the identifier.import { name } from "<specifier>"andimport * as ns from "<specifier>"reach the tools ofmodules. See Modules.text(value)appends a text item toresult.output; values other than strings are JSON-stringified.console.log/info/warn/error/debugappend text items withconsole: true.image(urlOrItem)appends an image item. It accepts a base64data:URL,{ image_url }, or an image block ({ type: "image", data, mimeType }, as MCP tools and@earendil-works/pi-aiproduce). Remote URLs are rejected.exit()ends the script successfully right away, keeping its output and store writes.globalspassed to the sandbox are called as top-level functions, for example a host helpersearchTools(query). They behave like tools but are not recorded inresult.calls. A name likemodels.classifyputs the function on a frozenmodelsobject. Withspread: true,executereceives all call arguments as an array instead of the first one, andsignaturereplaces the declaration generated from the schemas.store(key, value)andload(key)read and write JSON values synchronously. See Store.- Reading a member of
toolsor a global namespace that does not exist throws aTypeErrorthat names the close matches.missingToolHintends it for tools, for example to point at asearchToolsglobal. - Nothing else: no timers,
fetch,process,require, orWebAssembly. Built-ins are frozen.evalandFunctionwork but only produce more code inside the same VM.
timeoutMs: Infinity disables the deadline; the script then runs until it settles or signal aborts it. A script that waits on a promise nothing can settle (no tool call pending, and the VM has no timers or I/O) fails right away instead of hanging.
memoryLimitBytes caps the VM's heap. Past it the script fails with InternalError: out of memory.
CodemodeSandbox runs each run's VM in a worker thread of its own; tools, call records, the deadline, and the abort stay on the calling thread. A deadline, an abort, or close() terminates the worker, also while the script is inside one long built-in call (a sort or split of a large value), and the worker's memory is freed when it exits; a run that ended terminates its worker too. acquireWorker and onWorkerStarted let a host bound how many workers are alive at once. InlineCodemodeSandbox runs the VM on the calling thread instead: each step yields to the event loop every 10 ms while a script computes, so timers, the deadline, and an abort keep working during while (true) {}, but one long built-in call runs to its end, or to the end of the run's CPU budget, before anything else does.
Runs can have a CPU budget, interruptBudget: the work the VM may do before the script is interrupted, in units of about 1/50000 s of computing (DEFAULT_INTERRUPT_BUDGET, 100000, is about 2 s on a current laptop). Only computing counts, never waiting on tools, and a saved run carries what it used. It counts the VM's work rather than time, so a script stops at the same point on a loaded machine; the unit is this package's own, so a budget keeps its meaning across engines (it is the rate of 1.7.0's QuickJS interrupt polls). CodemodeSandbox has none unless given one; InlineCodemodeSandbox and the Cloudflare remote default to 100000. Past it the script fails with kind: "timeout" and "The script used its CPU budget (about N s of computation)".
Scripts read the host's clock and entropy: Date.now() moves while a script computes. Local time is UTC in every run, whatever the host's time zone (new Date(2026, 6, 1).getTimezoneOffset() is 0). Only runs that can be saved (begin(), resume()) are deterministic from their start.
Store
store/load let scripts keep values across executions. The sandbox does not persist anything itself: pass the current values as options.store, and a successful result reports what the script changed as result.storeWrites ({ set, delete }). Failed executions report no writes.
const result = await sandbox.execute(`store("runs", (load("runs") ?? 0) + 1)`, { store: saved });
if (result.ok) {
for (const key of result.storeWrites.delete) delete saved[key];
Object.assign(saved, result.storeWrites.set);
}
load returns a copy, so mutating it does not change the store. Storing undefined deletes the key. A value may be at most 256 Ki characters of JSON and all values together at most 1 Mi; larger writes throw a RangeError inside the script.
Modules
Tools can also sit behind a module path, for example one module per MCP server. A module's tools are reached by import only: they are not on tools and not in ALL_TOOLS.
const sandbox = new CodemodeSandbox({
tools: [read, bash], // tools.read(), tools.bash()
modules: [{ specifier: "@mcp/github", tools: [searchIssues, getPr] }],
});
await sandbox.execute(`
import { search_issues } from "@mcp/github";
import * as gh from "@mcp/github";
return [await search_issues({ q: "flaky" }), await gh.get_pr({ number: 1 })];
`);
Imports go at the top of the script. Export names follow the identifier rule of tools (search-issues is search_issues; the first tool of a name wins). A call always reaches its own module's tool, also when other modules or tools have a tool of the same name; result.calls records it with its module. An unknown module or export is a SyntaxError with its position (Cannot find module '@mcp/nope'). Specifiers must be non-empty and unique, and may not be tools, another built-in global, or a global's namespace; tool names are unique within a module. Describing modules to the model is up to the host: renderDeclarations() covers tools and globals only.
Source format
parseCodemodeSource() accepts a script whose first line may be an options line:
// @options: {"max_output_tokens": 2000, "timeout_ms": 30000}
const source = await tools.read({ path: "package.json" });
text(JSON.parse(source).name);
Supported fields are max_output_tokens, a token budget for the output, and timeout_ms, a hard deadline. The sandbox does not act on them; the caller decides. The options line is replaced by an empty line, so line numbers in stack traces still match the input. Empty input, invalid JSON, unknown fields, an options line without code, or an options line on any line but the first throw CodemodeSourceError. CODEMODE_SOURCE_GRAMMAR is a Lark grammar for providers that support grammar-constrained tool input. Both are also available from the lightweight @earendil-works/pi-codemode/source entry.
Bundled hosts
The djs module is part of djs's code, so it bundles with the host: esbuild, Bun (also compiled executables), rolldown, Vite, webpack, and Wrangler, which imports it as a compiled module. CodemodeSandbox starts its workers from this package's runtime/worker.js, which is not on disk once the host is bundled: build a file that imports @earendil-works/pi-codemode/worker as an extra entrypoint, and pass it:
import { CodemodeSandbox } from "@earendil-works/pi-codemode";
const sandbox = new CodemodeSandbox({
tools,
// The bundled worker entry. Bun compiled executables need the relative string specifier of the embedded entrypoint.
workerUrl: new URL("./codemode-worker.js", import.meta.url),
});
To load the module from a file or URL instead, pass wasm: loadCodemodeWasm(location); it is compiled once per location, and each worker gets the compiled module.
Usage on Cloudflare Workers
Cloudflare Workers cannot compile WebAssembly at runtime, and their clock does not move while code runs, so a script that computes cannot yield on time. Two sandboxes have the same API, the same script environment, and the same CodemodeResult. Only where the VM runs differs:
| Sandbox | Where the VM runs | Use it for |
|---|---|---|
RemoteCodemodeSandbox |
another isolate, usually a Durable Object in a separate Worker | a Durable Object that runs an agent session |
InlineCodemodeSandbox with an interruptBudget |
the calling thread | a stateless Worker, when blocking the caller is acceptable |
Import them from @earendil-works/pi-codemode/portable, which has no Node imports, or the client alone from @earendil-works/pi-codemode/remote. On Cloudflare, @earendil-works/pi-codemode/cloudflare adds the deployable Durable Object.
Why a separate Worker
A script that computes holds its thread until it awaits a tool, because the clock does not move and the VM cannot yield on time. Measured on Cloudflare (October 2026), a script that computed for ten seconds delayed every other request to the session object by the full ten seconds in two placements:
- inside the session's Durable Object
- in a Dynamic Worker loaded by that object
In a Durable Object of a separately deployed Worker, the delay was about 50 ms. RemoteCodemodeSandbox therefore keeps the tools and call records in the session and sends only the VM to the sandbox Worker. Each tool call travels back to the session over Workers RPC.
The remote does not have to be a Durable Object: anything with execute() (and step() for saved runs) works, for example an object that posts the requests to a Web Worker whose message handler calls serveCodemodeRemote() and serveCodemodeStep(). Requests, messages, and replies are opaque: pass them through unchanged. They carry a protocol version, so a client and a remote deployed from different versions fail with an error that says so. A transport that loses its peer answers the remote's pending and later exchanges with { type: "stop" }, which stops the VM.
Deploying the sandbox Worker
A complete setup is in examples/cloudflare. The sandbox Worker is one file:
// sandbox/src/index.ts
export { CodemodeSandboxDurableObject as CodemodeSandbox } from "@earendil-works/pi-codemode/cloudflare";
export default {
fetch: () => new Response("Not found", { status: 404 }),
};
// sandbox/wrangler.jsonc
{
"name": "pi-codemode-sandbox",
"main": "src/index.ts",
"compatibility_date": "2026-04-22",
"workers_dev": false,
"preview_urls": false,
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["CodemodeSandbox"] }],
"limits": { "cpu_ms": 60000 }
}
Install @earendil-works/pi-codemode in the sandbox Worker's project and run npx wrangler deploy. Wrangler bundles djs (about 1.2 MB) as a compiled WebAssembly module. The object has no routes and keeps no state, and it never uses its storage.
Using it from the agent's Worker
Bind the class with script_name. Binding a class exported from the agent's own Worker would bring back the blocking described above.
// agent/wrangler.jsonc
"durable_objects": {
"bindings": [
{ "name": "CODEMODE_SANDBOX", "class_name": "CodemodeSandbox", "script_name": "pi-codemode-sandbox" }
]
}
Then replace the sandbox. Tools, options other than interruptBudget, and results stay the same:
import type { CodemodeSandboxDurableObject } from "@earendil-works/pi-codemode/cloudflare";
import { RemoteCodemodeSandbox } from "@earendil-works/pi-codemode/remote";
interface Env {
CODEMODE_SANDBOX: DurableObjectNamespace<CodemodeSandboxDurableObject>;
}
// Before: new CodemodeSandbox({ tools, timeoutMs: 60_000 })
const sandbox = new RemoteCodemodeSandbox({
tools,
timeoutMs: 60_000,
remote: () => env.CODEMODE_SANDBOX.getByName(sessionId),
});
const result = await sandbox.execute(code, { signal, store });
Import the sandbox from /remote in the agent's Worker: that entry has only the client, so Wrangler does not upload the djs module with the agent (/portable would; type imports from it cost nothing). remote is called once per execution, and once per step of a run the agent drives, and picks the Durable Object that runs it.
Runs the agent drives itself (Saved runs) work on a RemoteCodemodeSandbox too: each advance() is one RPC that carries the saved run there and back (resume() takes none: the saved run lists the calls it waits on), and nothing stays alive in the sandbox object while tools run or the script waits. Measured in Node with the object's code path: a step costs about 1 ms and 1 KB each way for a small script, and grows with what the script holds (about 12 ms and 150 KB each way for 100 KB of live data, about 1 s and 5 MB for a million-element array), since every step loads and saves the whole run.
- One object per session,
getByName(sessionId), keeps a session's scripts together. Two scripts of the same session take turns on one thread. - One object per execution,
getByName(crypto.randomUUID()), runs every script on its own.
Run both Workers locally with wrangler dev -c agent/wrangler.jsonc -c sandbox/wrangler.jsonc.
Limits on Cloudflare
- CPU budget. While a script computes without calling a tool, no timer can run, and
Date.now()does not advance. A script that never yields is limited only by its CPU budget, not bytimeoutMs. Past the budget, the execution fails withkind: "timeout".- The object's default,
maxInterruptBudget, is 100000 (about 2 s of computation), per execution and per step. - Keep it below the Worker's
cpu_mslimit (30 seconds by default). Hitting that limit resets the object instead of failing one script.
- The object's default,
- Memory. Each VM may use up to 32 MiB by default. All VMs in one isolate share its 128 MB.
- Changing the limits. The Durable Object caps every request at its own limits, whatever the client asks for. To change them, subclass it in the sandbox Worker:
import { CodemodeSandboxDurableObject } from "@earendil-works/pi-codemode/cloudflare";
export class CodemodeSandbox extends CodemodeSandboxDurableObject {
protected maxInterruptBudget = 200_000;
protected maxMemoryLimitBytes = 64 * 1024 * 1024;
}
- Aborts and timeouts.
timeoutMsandsignalend the execution in the caller right away, withkind: "timeout"orkind: "aborted". The remote VM stops at its next tool call. A remote VM that is computing at that moment keeps running until it calls a tool or uses up its CPU budget. - Output. The remote sends output with its next call or with the result, so a caller that stops early has the output up to the last call.
- Billing. Each execution is one Durable Object request. The sandbox object is billed for wall-clock duration while an execution runs, including time spent waiting on tools. A run the agent drives is billed only for its steps.
On the calling thread
When blocking the caller is acceptable, for example in a stateless Worker that serves one request, run the VM on the caller's thread instead. Nothing extra needs to be deployed:
import { InlineCodemodeSandbox } from "@earendil-works/pi-codemode/portable";
const sandbox = new InlineCodemodeSandbox({ tools, timeoutMs: 60_000, interruptBudget: 50_000 });
const result = await sandbox.execute(code);
Its CPU budget is 100000 (about 2 s) unless given. A script that computes blocks the caller until it awaits a tool or uses up its CPU budget.
Declarations for the model
Tools and globals can carry description, inputSchema, and outputSchema (JSON Schema). renderDeclarations() turns them into TypeScript declarations for a model-facing tool description:
renderDeclarations({ tools, globals }); // the arrays given to the sandbox
// declare const tools: {
// /** Read a file */
// read(args: {
// path: string;
// }): Promise<string>;
// };
Property descriptions become // comments. Constraints the type cannot express follow as tags, such as // @integer @minimum 1 @default 20; they are dropped first when a type exceeds the size limit. Schemas only shape the declarations; values are not validated against them. Local references (#/$defs/..., #/definitions/...) are expanded; recursive and remote references render as unknown.
Using with pi-agent-core
To give an Agent a codemode tool, expose its other tools to the sandbox and wrap execute() as an AgentTool:
import type { AgentTool } from "@earendil-works/pi-agent-core";
import {
type CodemodeJsonSchema,
CodemodeSandbox,
type CodemodeTool,
renderDeclarations,
} from "@earendil-works/pi-codemode";
import { obj, str } from "@earendil-works/pi-schema";
const sandboxTools: CodemodeTool[] = agentTools.map((tool) => ({
name: tool.name,
description: tool.description,
inputSchema: tool.parameters as CodemodeJsonSchema,
outputSchema: (tool.outputSchema as CodemodeJsonSchema | undefined) ?? { type: "string" },
execute: async (args, { signal }) => {
const result = await tool.execute("nested", args as never, signal);
if (tool.outputSchema && result.structuredContent !== undefined) return result.structuredContent;
return result.content.map((block) => (block.type === "text" ? block.text : "")).join("\n");
},
}));
const codemodeTool: AgentTool = {
name: "codemode",
label: "Codemode",
description: `Run JavaScript that calls tools as \`await tools.<name>(args)\`. Output with text() or return.\n\n${renderDeclarations({ tools: sandboxTools })}`,
parameters: obj({ code: str() }),
execute: async (_toolCallId, { code }, signal) => {
const sandbox = new CodemodeSandbox({ tools: sandboxTools });
try {
const result = await sandbox.execute(code, { signal });
const content = [...result.output];
if (result.ok && result.value !== undefined) content.push({ type: "text", text: JSON.stringify(result.value) });
if (!result.ok) content.push({ type: "text", text: result.error.stack ?? result.error.message });
return { content, details: undefined, isError: !result.ok };
} finally {
await sandbox.close();
}
},
};
result.output items already have the shape of @earendil-works/pi-ai's TextContent and ImageContent. Calling tool.execute() directly skips the agent's beforeToolCall and afterToolCall hooks. To apply them to nested calls too, run each call through runToolCall() from @earendil-works/pi-agent-core, as the mcp-codemode example does. That example also rejects failed nested calls inside the script and combines codemode with MCP tools.
Deterministic runs
sandbox.start(code, options) runs a script so that a host can run it again after a restart and get the same behavior, for example to resume it from a durable log of its calls' results, as pi's durable code mode does. execute() is unaffected.
The VM only runs when the host hands it something, and has no timers or I/O, so it is deterministic except for what it reads from its environment. start() fixes that:
- Time:
Date.now()readsstartedAt, then thenowof the result being processed, never going backwards.performance.now()counts fromstartedAt. - Randomness:
Math.random()comes fromseed. - Timezone: UTC, whatever the host's.
- Garbage collection: a
WeakRefnever loses its target, and aFinalizationRegistrynever calls back. - Result order: the host answers each call with a result number (1, 2, ...), and the VM applies results strictly in that order, whatever order a transport delivers them in.
The run declares its own tools, modules, and globals, and the host answers every call itself:
const run = sandbox.start(code, {
startedAt: Date.now(),
seed: 7,
tools: [{ name: "read", description: "Read a file" }],
onStarted: (fingerprint) => {}, // what the VM is: djs build, heap and fuel limits
onCall: (call) => {
// call.id counts the run's calls, 1, 2, ... in the order the script made them.
void readFile(call.args).then((text) => run.deliver(nextResult++, Date.now(), call.id, { ok: true, value: text }));
},
onIdle: (seq, issued) => {}, // after result `seq` (0: the first run), `issued` calls in total
});
const result = await run.result;
A run has no deadline unless timeoutMs is given. Result numbers must run 1, 2, ... without gaps. modules and missingToolHint work as for execute(). The same script, startedAt, seed, tools, modules, globals and store, answered with the same results in the same order, makes the same calls with the same arguments and produces the same output on any VM with the same fingerprint. Calls the script made in its last step without awaiting them are never handed to onCall; once the run ended, run.dropped lists them, numbered on from the others. result.during says which result the VM was processing when the script ended and how many calls it had issued, so a replay can check that it ends where the recorded run did. To end a run with an error the script cannot catch, abort its signal.
Replaying costs the script's whole computation again, and its host keeps every result; Saved runs keep the run's state instead. On RemoteCodemodeSandbox a start() run is one session on the remote for the whole script, as an execute() is: nothing is saved between its steps.
Saved runs
For hosts that answer a script's calls themselves and keep its state across restarts, instead of replaying it (Deterministic runs), every sandbox also hands out the run: begin(code, scope) starts a CodemodeDrivenRun that reaches what scope declares (not the sandbox's tools and globals). The host advances it, answers its calls by id, and while it waits can save it as JSON and continue it later, in another process:
const sandbox = new CodemodeSandbox({ memoryLimitBytes: 256 * 1024 * 1024 });
const scope: CodemodeScope = { tools: [{ name: "read" }], store: { cwd: "/repo" } };
const run = await sandbox.begin(code, scope);
await run.advance(signal);
for (const call of run.calls) queue.add(call); // CodemodeHostCall: { id, target: "tool", name: "read", args }
const { saved, deliveries } = await run.save(); // `saved` is opaque JSON
store.put(saved);
store.append(deliveries); // the results applied since the previous save
run.dispose();
// Later, anywhere:
const resumed = await sandbox.resume(scope, store.saved(), async () => store.deliveries());
resumed.settle(callId, { ok: true, value: "file text" });
await resumed.advance(signal);
if (resumed.result !== undefined) use(resumed.result);
A scope takes tools, globals, and modules in the shapes of the options without their functions (a CodemodeTool without execute fits), plus the store and missingToolHint; every field is optional. A call names what it reaches: target: "tool" with the tool's name (from tools, or from what a script imports from scope.modules, with the module's specifier as module), or target: "global"; args is the tool's argument, or a spread global's argument list. A run that ends lists in dropped the calls still open then, which it no longer awaits: the host cancels them. Those made in the script's last step never ran. save() rejects when the run holds a value a snapshot cannot write (a WeakRef). On CodemodeSandbox an aborted advance() terminates the run's worker and ends the run; continue from its last save; on a remote sandbox, which keeps nothing between steps, such a run ends with a sandbox error. The CPU budget counts across saves. execute() is built on the same runs.
Runs that can be saved are deterministic from their start: their clock moves only when a result is applied, and Math.random() is seeded. A snapshot loads only into the djs build that compiles its waiting functions the same way; a newer one refuses it. resume() then calls its third argument for every delivery of the saves so far, in order, and begins the script again from them: no call is made again, and a script that takes another path ends with an error naming the first difference. A delivery names its call (id, target, name) and has the host's outcome and the clock; call is the call as the VM recorded it, opaque. A host that keeps a call's result elsewhere (say, with the task that ran the call) may store a delivery without its outcome and rebuild it. Without the deliveries the run ends with a sandbox error (on a remote sandbox, which learns of the refusal at the next step, once that step ran). close() disposes the runs begin() and resume() made. CodemodeSaved and CodemodeRecordedCall are opaque JSON: store them as they are, since their contents may change between versions. A saved run carries its format version; resume() rejects one saved in a format it does not read.
Results
execute() never rejects for script failures. result.error.kind is one of:
| kind | meaning |
|---|---|
script |
the script threw or failed to parse; stack points at codemode.js:<line> |
timeout |
the deadline expired or the CPU budget ran out |
aborted |
options.signal fired or close() was called |
sandbox |
the VM or its transport failed, for example a wasm trap, a module that does not load, or a failed remote |
result.output holds the text and image items in the order the script produced them, also for failed executions. The host keeps all of it until the script ends, so output is limited to 16 Mi characters of text and base64 image data and 100000 items. Past either limit the script fails with a RangeError, even if it catches the error. result.calls lists every tool call with status: "ok" | "error" | "cancelled". A call that is still running when the script returns (not awaited) is aborted through the tool's signal and reported as cancelled; one the script made in its last step without awaiting it never runs, and is reported as cancelled too.
How it works
Each execute() creates a djs VM from the compiled module (a few milliseconds): a separate wasm instance with its own linear memory. Everything the script can reach outside the language is a host function: tools and globals are async host functions the host answers, text, image, store, load, exit, and console.* are sync ones whose checks run on the host. No code of this package runs in the VM. Arguments, results, and the return value cross as JSON; the output and store functions get the script's values and turn them into JSON on the host.
The host drives the run in steps: a step runs until the script waits on its calls or ends, and yields to the event loop every 10 ms while it computes. The deadline and the abort signal stop a step between its slices.
Runtime notes
- Stack traces use the VM's frames (
at f (codemode.js:2:31)), prefixed withName: messagelike V8. Line and column numbers match the script. - Deep recursion throws a catchable
RangeError. - djs is an interpreter. Glue code and filtering tool results are fast enough; heavy computation is slower than in V8.
Deprecated
These names of earlier versions still work for a release and warn once per process (PI_CODEMODE_DEPRECATED), except loadQuickJSWasm(), which is the same function as loadCodemodeWasm() and does not warn:
| Deprecated | Use instead |
|---|---|
loadQuickJSWasm() |
loadCodemodeWasm() |
QuickJS's module (quickjs-wasi/quickjs.wasm) as wasm |
no wasm option: djs's own module is loaded instead |
registerTool(), unregisterTool(), tools, globals |
the tools and globals options |