Skip to main content

Configuration

Pass an IoCodeMode.Config object to IoCodeModeFactory.

interface Config {
wasmLocation: string;
overwriteSystemInstruction?: (current: string) => string;
interceptors?: {
onToolCall?: (context: ToolCallContext) => Promise<InterceptorDecision>;
};
timeout?: number;
memoryLimit?: number;
toolFilter?: (tool: ToolDefinition) => boolean;
}
PropertyRequiredDefaultPurpose
wasmLocationYes-URL in a browser or filesystem path in Node.js to the QuickJS WebAssembly file.
overwriteSystemInstructionNoIdentityReplaces or extends the built-in instructions given to the model.
interceptors.onToolCallNoAllowAsynchronous authorization, approval, validation, or input-rewriting hook.
timeoutNo30000Maximum execution time per executeCode call, in milliseconds.
memoryLimitNo128QuickJS memory limit per executeCode call, in megabytes.
toolFilterNoInclude allReturns true to expose a tool or false to hide it.

Execution Limits​

LimitScope and Enforcement
timeoutWall-clock deadline per executeCode execution, starting after context setup. Includes pending host tools and onToolCall interceptors. Expiry produces a timeout error result and aborts that run's host-tool signal.
memoryLimitQuickJS runtime allocation limit for the fresh context created per execution. Not pooled across sessions; excludes host-tool memory.

Limits are factory-level settings with no per-call override. execute(args, { signal }) can cancel an execution earlier, but cannot extend its deadline. Already-running tools must observe options.signal to stop; cancellation does not roll back completed side effects.

Delivering the WASM File​

Code Mode publishes the QuickJS asset at @interopio/code-mode/dist/emscripten-module.wasm. You can copy this file from the installed package into a location of your choosing and set wasmLocation to its browser URL or server filesystem path.

For browser applications, a CDN path that resolves the latest published version is also supported:

wasmLocation: "https://unpkg.com/@interopio/code-mode@latest/dist/emscripten-module.wasm";

latest refers to the latest published version of @interopio/code-mode, not necessarily the version installed in your application. For production deployments, replace latest with the exact installed package version so the WASM file matches. Self-host the asset when the application must control availability, satisfy a restrictive content security policy, or avoid a runtime dependency on a public CDN.

Upgrading​

Whenever you upgrade @interopio/code-mode:

  1. Refresh the WASM file. Copy node_modules/@interopio/code-mode/dist/emscripten-module.wasm again to the static-assets or server deployment directory configured by wasmLocation. The WASM file must match the installed Code Mode version. Do not reuse an asset from a previous release, even if its filename is unchanged. If your build copies the asset automatically, ensure it copies from the newly installed package on every build.
  2. Keep integration packages compatible. If you use @interopio/ai-web or @interopio/mcp-core, check each integration package's declared @interopio/code-mode dependency range and update the integration packages together when needed. Compatibility is determined by those ranges, not by matching version numbers across packages.
  3. Update pinned CDN URLs. If you load the WASM file from a CDN instead of copying it locally, update every pinned URL to the exact installed Code Mode version. The latest tag shown above refers to the latest published package version and can change independently of your installed dependency. For production deployments, replace it with the installed version; do not leave a URL pinned to an older release.

Rebuild and redeploy the application with the matching WASM asset or CDN configuration.

Tool Policies​

Generated code runs in QuickJS, not in the browser or Node.js host runtime. The sandbox does not expose fetch or other host network APIs. Perform network requests inside registered host tools so they remain subject to filtering, interception, and host authorization.

Use toolFilter to remove tools from both discovery and execution. Use interceptors.onToolCall to decide whether an individual call is allowed, denied with a reason, or run with replacement input.

interface ToolCallContext {
tool: ToolDefinition;
input: Record<string, unknown>;
callContext?: unknown;
}

interface InterceptorDecision {
allowed: boolean;
reason?: string;
input?: Record<string, unknown>;
}

interface Interceptors {
onToolCall?: (context: ToolCallContext) => Promise<InterceptorDecision>;
}

For each sandbox-originated call, Code Mode checks cancellation, awaits onToolCall, checks cancellation again, then invokes tool.execute(decision.input ?? input, options) if allowed. A denied call throws a policy error inside guest code. The interceptor has no after-call hook: it cannot observe the tool result or measure tool execution duration. Instrument the host tool's execute implementation for those measurements.

AI Web and MCP Core pass tools to Code Mode with their plain, unprefixed MCP names. They do not populate ToolDefinition.source, and ToolSource.mcpName is optional, so match tools by tool.name rather than relying on tool.source?.mcpName. MCP tool annotations are not passed through. The portable tool fields are name, description, inputSchema, outputSchema, and execute; toolFilter receives the runtime tool, while onToolCall receives it as context.tool.

const codeMode = await IoCodeModeFactory({
wasmLocation: "/quickjs/emscripten-module.wasm",
toolFilter: (tool) => !tool.name.startsWith("admin."),
interceptors: {
onToolCall: async ({ tool, input }) => {
if (tool.name === "payments.transfer") {
return { allowed: false, reason: "Transfers require manual approval." };
}

return { allowed: true, input };
},
},
});

Approval and Sandbox Timeout​

The host supplies approvalUi.request({ toolName, input }): Promise<boolean>. It must display the proposed call and resolve to true for approval or false for denial/dismissal. Code Mode does not invoke the host tool until the interceptor resolves with allowed: true:

const codeMode = await IoCodeModeFactory({
wasmLocation: "/quickjs/emscripten-module.wasm",
timeout: 60_000,
interceptors: {
onToolCall: async ({ tool, input }) => {
if (tool.name !== "payments.transfer") {
return { allowed: true, input };
}

const approved = await approvalUi.request({ toolName: tool.name, input });

return approved ? { allowed: true, input } : { allowed: false, reason: "The user did not approve the transfer." };
},
},
});

Approval lifecycle:

  1. The configured timeout continues counting during approval; it is neither paused nor reset.
  2. On timeout, executeCode resolves to an error result containing TimeoutError, and the run's host-tool signal is aborted.
  3. If the interceptor later resolves with approval, the post-interceptor signal check prevents tool.execute from starting. Caller cancellation has the same effect on a pending call.
  4. The host approval promise/dialog is not automatically cancelled. ToolCallContext has no dedicated signal field; the application owns dialog expiry and cleanup.

Set timeout to cover approval plus tool execution. There is no per-call deadline extension.

Important

The sandbox isolates generated JavaScript from the host runtime, but it does not make underlying tools safe. The host remains responsible for validating inputs and enforcing authorization for side-effecting operations.

Tool Results in Sandbox Code​

Host tool implementations return IoCodeMode.ToolResult:

interface ToolResult {
content: { type: "text"; text: string }[];
structuredContent?: Record<string, unknown>;
isError?: boolean;
}

The tool_*() binding does not return the ToolResult envelope. Conversion is applied in this order:

ConditionSandbox Behavior
isError is truthyThrows an error using the concatenated text content.
structuredContent !== undefinedResolves to structuredContent.
outputSchema is presentAttempts JSON.parse() on text content; returns the original string if parsing fails.
OtherwiseResolves to text content as a string.

Text blocks are joined with "\n". outputSchema selects JSON parsing, not schema validation. For JSON text without structured output or an output schema, parse the returned string explicitly.

For example, when a text-only tool has no outputSchema, parse its JSON explicitly:

const resultText = await tool_search_orders({ query: "open" });
const result = JSON.parse(resultText);
return result.matches;

In AI Web, non-UI tools are virtualized through Code Mode. A non-UI tool rejected by toolFilter is hidden from the model and cannot be called directly either. MCP App tools with a UI resource remain direct tools and bypass Code Mode.

Caller Context​

A host that directly invokes Code Mode can pass opaque caller state to an individual executeCode invocation with execute(args, { context }). Code Mode forwards it to onToolCall as callContext and to each underlying tool as options.context, without exposing it to sandbox code. For example, a custom host can forward request metadata for authorization:

const executeCode = session.getLlmTools().find((tool) => tool.name === "executeCode")!;
const result = await executeCode.execute({ code: "return await tool_search({ query: 'orders' });", explanation: "Search for orders." }, { signal, context: requestMetadata });

The signal and context belong to this execution only, even if another call uses the same session. onToolCall can inspect callContext for policy decisions; sandbox code cannot read or forge it. For integration-specific context forwarding, see AI Web CodeModeConfig and MCP Core CodeModeConfig.