npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@enclave-vm/core

v2.21.2

Published

Sandbox runtime for secure JavaScript code execution

Readme

@enclave-vm/core

A sandbox for running AgentScript, the JavaScript subset that language models write to call tools, in Node.js. It validates a script, transforms it, runs it in a reduced realm behind a membrane with limits on time, iterations, tool calls and memory, and returns a plain-data result.

npm version License: Apache-2.0

It is the runtime of Enclave. The static checks come from @enclave-vm/ast; @enclave-vm/broker runs this package behind HTTP routes; @enclave-vm/browser is the counterpart for the browser.

How the Layers Fit Together

A script goes through these steps, in this order:

  1. Pre-scanner (@enclave-vm/ast): the source text, before anything parses it: size, lines, string literals, nesting, regex literals, bidirectional, invisible and look-alike characters.
  2. AgentScript transform (transformAgentScript of @enclave-vm/ast): the script is wrapped in async function __ag_main(), callTool becomes __safe_callTool, and loops get iteration checks. The validator receives the script as this step returns it.
  3. AST validation (@enclave-vm/ast): the AgentScript preset by default, an allowlist of syntax, globals and property keys.
  4. Transformation after validation: the deadline is checked in every function and loop body, concatenation is counted, and every computed key that is not a literal is checked at run time (guardComputedMemberKeys). What a static rule cannot decide, such as a property name the script builds while it runs, is decided here.
  5. Scoring gate (optional, off by default): a heuristic risk score from the script's tool calls.
  6. Runtime sandbox: by default a double VM in this process: the script runs in an inner realm that holds only the allowed globals, inside a parent realm that checks every tool call. Optionally the whole sandbox runs in a worker thread with a heap limit and a hard stop.
  7. Output: the returned value is copied into plain data, errors become bounded text without a stack from the sandbox, and oversized values are refused.

What it does not do

  • It is not process isolation. The default sandbox runs in your process and thread. A script that computes is stopped by checks in its own code; a single built-in call that does all its work natively is not interrupted (see How timeout Is Enforced). For a stop the script cannot influence, use the worker pool; for tenants that must not share a process, or a host that must survive whatever a script allocates, run one enclave per process or container.
  • memoryLimit is the enclave's own accounting, not a limit of the engine's heap (see What memoryLimit Counts).
  • It does not stop your toolHandler. A tool call it stops waiting for keeps running in the host.
  • The scoring gate is a heuristic. A low score is not evidence that a script is safe.

The invariants of the sandbox by layer, and the ones that are still open, are listed in SECURITY-TESTS.md. SECURITY-AUDIT.md is the audit report written for v2.4.0, kept as a record.

Installation

npm install @enclave-vm/core

vectoriadb is an optional peer dependency, used only by the local-llm scorer of the scoring gate in mode: 'similarity'.

Quick Start

import { Enclave } from '@enclave-vm/core';

const enclave = new Enclave({
  timeout: 5000,
  maxToolCalls: 10,
  maxIterations: 1000,
  toolHandler: async (toolName, args) => {
    if (toolName === 'getUser') return { id: args.id, name: 'Alice' };
    if (toolName === 'getOrders') return [{ id: 1 }, { id: 2 }];
    throw new Error(`Unknown tool: ${toolName}`);
  },
});

const result = await enclave.run(`
  const user = await callTool('getUser', { id: 123 });
  const orders = await callTool('getOrders', { userId: user.id });
  return { user: user.name, orderCount: orders.length };
`);

if (result.success) {
  console.log(result.value); // { user: 'Alice', orderCount: 2 }
} else {
  console.error(result.error);
}

enclave.dispose();

runAgentScript(code, options) creates an enclave, runs one script and disposes of it.

Portable AgentScript Runner

Use the Worker entry when the host cannot load Node's vm or worker-thread modules. AgentScriptRunner pre-scans raw source, transforms AgentScript, validates the AST, and then runs it in the bounded interpreter. InterpreterAdapter is a lower-level adapter and does not perform those validation steps by itself.

import { AgentScriptRunner } from '@enclave-vm/core/worker';

const runner = new AgentScriptRunner({
  securityLevel: 'STANDARD',
  timeout: 5000,
  maxSteps: 1_000_000,
  maxToolCalls: 20,
  maxHostFunctionCalls: 200,
  hostFunctions: { getTool: (name) => ({ name }) },
  toolHandler: async (name, args) => ({ name, args }),
});

try {
  const result = await runner.run("return getTool('example').name;");
  console.log(result);
} finally {
  runner.dispose();
}

Statement Events

The interpreter can report each statement a script runs, for tracing and debugging. Pass onStatement to run() of PortableEnclave / AgentScriptRunner, or of an Enclave whose sandboxAdapter is an InterpreterAdapter:

const result = await runner.run(code, toolHandler, {
  onStatement: ({ line, column, type, step }) => span.addEvent('statement', { line, column, type, step }),
  maxStatementEvents: 1000, // default 10,000
});
  • An event is { line, column, type, step }: where the statement starts in the script as it was written (line from 1, column from 0), its ESTree type (VariableDeclaration, IfStatement, ...), and the interpreter steps taken so far. It carries no value of the script, so it can go to an operator's tracing as it is.
  • The hook is called as each statement starts, synchronously, in the async context of the caller of run(); its time counts toward the run's timeout, read right after it returns. A run reports at most maxStatementEvents statements (an integer of at least 1) and then runs on without reporting.
  • A hook that throws, or returns a promise, ends the run at once with a StatementHookError (code: 'STATEMENT_HOOK_FAILED', message The onStatement hook threw), also from inside a parallel() task whose siblings still wait.
  • It needs the enclave's transform: with transform: false, run() with onStatement throws a TypeError.
  • Off by default; without the hook the script is transformed and run as before, at the cost of one check per statement.
  • AgentScriptRunner.capabilities includes 'statement-events'.
  • Interpreter only: run() with onStatement on the double VM, the vm adapter or the worker pool throws a TypeError. The enclave's transform puts a marker with each statement's location in the code it hands the adapter (an adapter of your own that sets reportsStatements: true gets them, and the events as context.onStatement).

The runner supports Node and Cloudflare Workers with nodejs_compat. Tool and host-function arguments and results cross as bounded plain data. Steps, call depth, pending calls, allocation, tool calls, console output, bridge payloads and sidecar storage all have finite limits. maxSteps bounds interpreted CPU work, including work charged for built-in operations. timeout is checked between interpreter steps and at I/O boundaries; deployed Cloudflare Workers do not advance their clocks during CPU-only work, so it is not a hard wall-time cutoff there. Synchronous host callbacks cannot be preempted. Unsupported VM-only options and pre-scan overrides fail at construction.

Configuration

CreateEnclaveOptions

interface CreateEnclaveOptions {
  // Execution limits
  timeout?: number; // Execution timeout in ms (default: by security level, 30000 at STANDARD)
  toolCallGraceMs?: number; // How long a tool call in progress at the timeout may still take (default: same as timeout)
  maxToolCalls?: number; // Maximum tool calls allowed (default: by security level, 100 at STANDARD)
  maxIterations?: number; // Maximum loop iterations (default: by security level, 10000 at STANDARD)
  memoryLimit?: number; // Memory limit in bytes, as the enclave counts it (default: 1048576, 1 MB; 0: off)

  // Security
  securityLevel?: SecurityLevel; // 'STRICT' | 'SECURE' | 'STANDARD' | 'PERMISSIVE' (default: 'STANDARD')
  preset?: AstPreset; // AST validation preset (default: 'agentscript')
  preScan?: { preset?; config? }; // Pre-scanner preset or single limits (see "What the Pre-Scanner Checks")
  validate?: boolean; // Enable AST validation (default: true)
  transform?: boolean; // Enable code transformation (default: true)
  realmGlobals?: 'allowlist' | 'security-level'; // What exists in the script's realm (see "What the Script's Realm Holds")
  secureProxyConfig?: Partial<SecureProxyLevelConfig>; // Override the membrane settings of the level

  // Where the sandbox runs
  adapter?: 'vm' | 'worker_threads'; // In this process (default) or in a pool of worker threads ('isolated-vm' is reserved, not implemented)
  workerPoolConfig?: Partial<WorkerPoolConfig>;
  sandboxAdapter?: SandboxAdapter; // An adapter of your own

  // Tool execution
  toolHandler?: ToolHandler; // Function to execute tool calls
  toolNamespaces?: ToolNamespaces; // Expose tools as `ns.method(args)` (see "Tool Namespaces")
  toolBridge?: { mode?: 'string' | 'direct'; maxPayloadBytes?: number; acknowledgeInsecureDirect?: boolean }; // default: 'string', 5 MB, false

  // Console
  consoleHandler?: ConsoleHandler; // Receive console calls as (level, message) instead of the host console (see "Console Handler")
  maxConsoleCalls?: number; // Maximum console calls (default: by security level)
  maxConsoleOutputBytes?: number; // Maximum total console output (default: by security level)

  // Custom globals
  globals?: Record<string, unknown>; // Additional globals for the VM
  allowFunctionsInGlobals?: boolean; // Allow functions in globals (default: false)
  maxGlobalFunctionCalls?: number; // Cap on calls into functions from globals (default: 10 × maxToolCalls)
  allowBuiltins?: boolean; // default: false

  // Results and errors
  sanitizeStackTraces?: boolean; // Redact paths/frames in every returned error (default: by security level)
  maxSanitizeDepth?: number; // Deepest returned value (default: by security level)
  maxSanitizeProperties?: number; // Most properties in a returned value (default: by security level)

  // Sidecar (large data handling)
  sidecar?: ReferenceSidecarOptions;

  // Scoring gate
  scoringGate?: ScoringGateConfig; // See "AI Scoring Gate"

  // Review hooks
  review?: ReviewOptions; // Host hooks before and after the run and each tool call (see "Review Hooks")

  // Replay (see "Call Positions and Replay")
  toolResultOrder?: 'completion' | 'call'; // When a tool result reaches the script (default: 'completion')
  clock?: () => number; // What Date.now(), new Date() and Date() read (default: the system clock)
  random?: () => number; // What Math.random() returns (default: the engine's)

  // Double VM security layer
  doubleVm?: PartialDoubleVmConfig; // See "Double VM"
}

toolBridge.mode: 'direct' throws at construction unless acknowledgeInsecureDirect: true is set as well.

Option Values

The constructor checks its options and throws a TypeError for a value outside the documented type or range:

  • A limit is a finite integer in its range: timeout from 1 to 2147483647 (the longest delay a timer holds); maxIterations, maxSanitizeDepth and maxSanitizeProperties at least 1; maxToolCalls, maxConsoleCalls, maxConsoleOutputBytes, maxGlobalFunctionCalls and memoryLimit at least 0. Infinity, NaN and a value of another type (a numeric string, null) are refused. The one exception is toolCallGraceMs, a number of at least 0 for which Infinity means "wait without limit".
  • A switch is a boolean: validate, transform, sanitizeStackTraces, allowFunctionsInGlobals, allowBuiltins, doubleVm.enabled, and the switches of secureProxyConfig and doubleVm.parentValidation.
  • securityLevel is one of the four levels.
  • An option passed as undefined is an option that was not set: it has its default, which is the security level's value where the level sets one. A wrapper can forward { maxIterations: opts.maxIterations } whether or not its caller set it.

Limits on the Script Itself

  • Size. A script is at most 5,242,880 characters. A longer one, or a script that is not a string, fails with VALIDATION_ERROR before anything parses it.
  • Dynamic import. A script that contains import() or import.meta is refused before it runs. Every preset refuses it during validation; with validate: false it fails with SECURITY_VIOLATION. The word in a string, a comment or a property name is not the construct.
  • Iteration limit. A script that declares __maxIterations, the runtime's name for the limit, is refused. With validation off the limit still holds: each loop is compared with a number in its own code.

What memoryLimit Counts

memoryLimit (default 1 MB; 0 switches it off) is the enclave's own accounting of the operations that make data grow. It is not a limit of the engine's heap.

  • Text: concatenation (a + b, and x += y, which is charged like x + y) and the methods that multiply their input (repeat, padStart, padEnd, join).
  • Arrays: no single array is larger than the limit holds, at 8 bytes per element, and what an operation adds is charged: push, unshift, splice, fill, the elements concat, flat, flatMap and a spread literal add, and what Array.from makes out of something that is not an array.
  • Sets and Maps: every new entry of a script's Set or Map is charged (16 bytes) before it is added, in both VMs and in the interpreter.
  • Not counted by the VM adapter: a copy is free, so a script can hold many arrays that are each within the limit; object literals are not counted.

The portable interpreter additionally charges copied host-function results and tool responses by their serialized size to the cumulative allocation budget.

A script that goes over the limit fails with MEMORY_LIMIT_EXCEEDED, and a script cannot switch the accounting off or reset it. With a limit set, a returned value whose serialized size is estimated above the limit (above 50 MB where the limit is larger) fails with SERIALIZATION_LIMIT_EXCEEDED. The limit is an estimate: where the host must survive whatever a script allocates, use the worker pool, whose workers have a heap limit of the engine, or a child process or container with a memory limit of the operating system.

Security Levels

The security level sets the defaults of the limits, the globals a script may use, and how the membrane answers a refused property.

| Setting | STRICT | SECURE | STANDARD (default) | PERMISSIVE | | -------------------------------------------- | -------- | -------- | -------------------- | ------------------- | | timeout | 5 s | 15 s | 30 s | 60 s | | maxIterations | 1,000 | 5,000 | 10,000 | 100,000 | | maxToolCalls | 10 | 50 | 100 | 1,000 | | maxConsoleCalls | 100 | 500 | 1,000 | 10,000 | | maxConsoleOutputBytes | 64 KB | 256 KB | 1 MB | 10 MB | | maxSanitizeDepth / maxSanitizeProperties | 5 / 50 | 10 / 100 | 20 / 500 | 50 / 1,000 | | sanitizeStackTraces | on | on | off | off | | allowFunctionsInGlobals | off | off | off | on | | A refused constructor | throws | throws | throws | allowed | | Other refused properties | throw | throw | throw | read as undefined |

The values are exported as SECURITY_LEVEL_CONFIGS.

import { Enclave } from '@enclave-vm/core';

const enclave = new Enclave({
  securityLevel: 'STRICT',
  toolHandler: async (name, args) => {
    /* ... */
  },
});

Allowed Globals by Security Level

Both AST validation and the runtime sandbox use the same allowed globals:

| Global | STRICT | SECURE | STANDARD | PERMISSIVE | | -------------------------------------------------------------------- | ------ | ------ | -------- | ---------- | | callTool | Yes | Yes | Yes | Yes | | Math, JSON, Array, Object, String, Number, Date | Yes | Yes | Yes | Yes | | undefined, NaN, Infinity | Yes | Yes | Yes | Yes | | parseInt, parseFloat, isNaN, isFinite | No | Yes | Yes | Yes | | encodeURI, decodeURI, encodeURIComponent, decodeURIComponent | No | Yes | Yes | Yes | | Set, Map | No | Yes | Yes | Yes | | Error, TypeError, RangeError | No | Yes | Yes | Yes | | console | No | No | No | Yes |

With a consoleHandler, console is allowed at every level (see Console Handler).

Set, Map and the three error types are the runtime's own, the same in the double VM, the single VM, the interpreter and @enclave-vm/browser:

  • A new entry of a Set or Map is charged against memoryLimit as it is added, so a growing Set fails with MEMORY_LIMIT_EXCEEDED like a growing array. WeakMap, WeakSet and WeakRef stay refused.
  • An error has name and message and no stack, and is frozen: String(new Error('x')) is "Error: x", and a catch reads error.message.
  • Where a value leaves the script (the arguments of callTool, the returned value), a Set becomes an array and a Map an array of [key, value] pairs. So does JSON.stringify inside the script.
  • A custom global named Set or Map (in globals) replaces the built-in one. PortableEnclave refuses such a global at construction.

Refused Globals

With the default agentscript preset, every global that is not in the table above is refused, at every security level. Among them:

| Category | Globals | | ------------------ | ------------------------------------------------------------------------------ | | Code Execution | eval, Function, AsyncFunction, GeneratorFunction | | System Access | process, require, module, exports, __dirname, __filename, Buffer | | Global Objects | window, globalThis, self, global, this | | Prototype | constructor, __proto__, prototype | | Reflection | Proxy, Reflect | | Async | Promise, setTimeout, setInterval, setImmediate, queueMicrotask | | Network | fetch, XMLHttpRequest, WebSocket | | Workers | Worker, SharedWorker, ServiceWorker | | Collections | WeakMap, WeakSet, WeakRef, FinalizationRegistry; STRICT: Map, Set | | Binary/Wasm | WebAssembly, ArrayBuffer, SharedArrayBuffer, Atomics | | Error Types | ReferenceError, SyntaxError; STRICT: Error, TypeError, RangeError | | Symbols/Regex | Symbol, RegExp |

What the Script's Realm Holds

The tables above are what the validator accepts. The realm the script runs in agrees with them:

  • Only the allowed globals exist. With the agentscript or babel preset and validation on (the default), every other standard global is removed from the realm before the script runs: Function, eval, globalThis, Proxy, Reflect, Symbol, Promise, RegExp, WebAssembly, the engine's console, and so on. What is left is the allowed globals of the security level, the runtime helpers, your globals and your toolNamespaces. A gap in the static rules therefore does not hand a script a global. This is realmGlobals: 'allowlist'. With another preset, or with validate: false, a script may legitimately name other standard globals, so the default is realmGlobals: 'security-level': only the dangerous globals listed for the level are removed. Either value can be set explicitly.
  • No name resolves through a prototype. constructor, toString, valueOf, hasOwnProperty and the other members of Object.prototype are not reachable as bare names (in every mode).
  • Scripts run in strict mode. this is undefined outside a method call, an assignment to an undeclared name is a ReferenceError, and a function has no caller or arguments.callee. A write that cannot happen throws a TypeError instead of being silently ignored: assigning over a built-in method (obj.toString = ...; the built-in prototypes are frozen) or changing a frozen object, such as an error the runtime threw.
  • Regular expressions cannot run. AgentScript has none, and with the realm allowlist the realm refuses them too, including the ones the engine builds from a string argument of match, matchAll and search. String operations that take plain strings (split(','), replace('a', 'b'), includes) are unaffected.

AST Presets

The preset option selects the AST validation. With transform on (the default), it is applied to the script as transformAgentScript returns it (the __ag_main wrapper, __safe_callTool, the loop checks), and before the transforms that follow validation (see How the Layers Fit Together). It is separate from securityLevel, which sets the runtime limits and, for the agentscript and babel presets, the allowed globals.

| Preset | Description | Custom globals in validation | | ------------- | ------------------------------------------------------------------------------ | ---------------------------- | | agentscript | Default. The AgentScript allowlist | Yes | | babel | AgentScript plus Babel.transform() for TSX/JSX (see createRestrictedBabel) | Yes | | strict | The STRICT preset of @enclave-vm/ast | No | | secure | The SECURE preset | No | | standard | The STANDARD preset | No | | permissive | The PERMISSIVE preset | No |

Only the agentscript and babel presets take your custom globals into their allowlist; the other presets use their own fixed rule sets, and custom globals are still available at run time. With these four presets the realm keeps the standard globals that the level does not remove (realmGlobals: 'security-level'), so choose them only for code you trust more than generated code.

import { Enclave } from '@enclave-vm/core';

const enclave = new Enclave({
  preset: 'agentscript', // AST validation preset (default)
  securityLevel: 'STRICT', // Runtime security level
  toolHandler: async (name, args) => {
    /* ... */
  },
});

Tools

Tool Handler

type ToolHandler = (toolName: string, args: Record<string, unknown>, call: ToolCall) => Promise<unknown>;

interface ToolCall {
  callIndex: number; // The call's position in the run, from 0
}

Called for every callTool() and toolNamespaces method call that passes the enclave's checks. Arguments reach it as copied plain data, and its result is sanitized before the script sees it. The script's callTool options (CallToolOptions) are applied inside the sandbox and are not passed to the handler.

Call Positions and Replay

call.callIndex numbers the calls of a run from 0, in the order they reach the host: the calls the enclave's checks let through, the same calls the review hooks see, with the same number (callIndex in PreReviewInput, PostReviewInput and ReviewRecord). The script cannot set or change it.

toolResultOrder: 'call' is experimental in 2.21. What it guarantees: a run of the same script that gets the same results in the same positions makes the same calls, with the same callIndex, in the same order, and, with clock and random, reads the same time and randomness. Its limits:

  • Whether a reply waiting behind a slow call is refused for lack of room (TOOL_RESULTS_WAITING_TOO_LARGE) depends on how long that earlier call stalls, so a replay that answers fast may deliver what the first run refused.
  • With the sidecar on, a reference token's text differs between runs: a token passed to a tool resolves to the same data, but a script whose path depends on a token's text does not replay.

Calls start in the order the script makes them, but their results come back as each tool finishes, and which result a script gets first can change what it does next: in a parallel() whose callbacks make more than one call, or that read Date.now() after an await. With toolResultOrder: 'call' the results reach the script in call order, one per turn of the event loop, so everything a result leads to in the script has run before the next result arrives. A run of the same script that gets the same results then makes the same calls, with the same callIndex, in the same order:

import { isDeepStrictEqual } from 'node:util';

const enclave = new Enclave({
  toolResultOrder: 'call',
  clock: () => journal.nextTime(), // what Date.now(), new Date() and Date() read
  random: () => journal.nextRandom(), // what Math.random() returns
  toolHandler: async (name, args, { callIndex }) => {
    const recorded = journal.call(callIndex);
    if (!recorded) return journal.record(callIndex, name, args, await callMyTool(name, args));
    if (recorded.name !== name || !isDeepStrictEqual(recorded.args, args)) throw new Error('The run diverged');
    return recorded.result;
  },
});

With the sidecar on, a reference token is new in every run: a token passed to a tool resolves to the same data, but a script whose path depends on a token's text (comparing tokens, keying data by one) does not replay.

This is what a host needs to resume a run without keeping a process alive: record each call and its result, and later run the same script again, answering the recorded calls from the record (matched by callIndex; a different tool or different arguments at a recorded position is a divergence) until the first call that has none. A call inside parallel() has a position of its own like any other.

  • toolResultOrder: 'completion' (default) delivers each result as its handler settles; 'call' delivers them in call order. A slow call then holds back the results of the calls made after it, never the calls themselves: every handler still starts as soon as its call is made. What waits for its turn is the bridge's response: sanitized and within the bridge's payload limit and maxToolResultBytes. The replies waiting behind an earlier call hold at most toolBridge.maxPayloadBytes together, in UTF-8 bytes, a large string with its own bytes: when they would hold more, the latest positions fail their calls (TOOL_RESULTS_WAITING_TOO_LARGE, a failure of the tool, so throwOnError: false returns it). A large result goes into the sidecar at its turn, so the call order, not latency, decides which call meets a full sidecar. Once the run is aborted (its deadline, or the end of run()) nothing waits: replies are delivered as they settle. It needs the string tool bridge, with toolBridge.maxPayloadBytes of at least 157 bytes so that the bridge's own refusal reply fits: otherwise, and with toolBridge.mode: 'direct', it is a TypeError.
  • clock is called at every read of Date.now(), new Date() (without arguments) and Date(), and must return a finite number of milliseconds; random is called at every Math.random() and must return a number from 0 up to 1. A value out of range, or a throw, fails the script's read with an error the script can catch (The host clock failed, The host random source failed). The enclave's own deadline and rate limit keep reading the system clock. Neither function is called once the run has returned or was aborted, nor with less than 128 KB of stack left (the read fails instead), and a subclass of Date stays a subclass. Supported by the double VM, the vm adapter, InterpreterAdapter and PortableEnclave; the worker_threads adapter refuses them at construction, also as a sandboxAdapter (an adapter sets supportsHostClock: false for that). A custom sandboxAdapter receives them, checked, as context.clock and context.random, which return undefined when the host's function failed.
  • Results of functions in globals that return promises are not ordered.
  • PortableEnclave and AgentScriptRunner take the same options; AgentScriptRunner.capabilities includes 'replay'.

Replayed Calls and the Detectors

A replay answers in milliseconds the calls that took minutes in the first run, and the operation rate limit and the suspicious-sequence detectors read the system clock: without help they can refuse a replay that the first run passed. Pass the calls the host answers from its record as the replayedCalls option of run(), each with the time it reached the host, in milliseconds from the start of the first run:

const result = await enclave.run(script, undefined, {
  replayedCalls: journal.calls().map((call) => ({
    callIndex: call.callIndex,
    toolName: call.name,
    elapsedMs: call.reachedHostAt - journal.startedAt,
  })),
  replayedCallsResumeAtMs: journal.pausedCall.reachedHostAt - journal.startedAt,
});
  • A listed call skips the rate limit and the suspicious-sequence detectors (the first run passed them there), and on the worker pool maxMessagesPerSecond; the operation-name patterns still apply. It enters their history at its original time, moved so that the latest replayed call is now, and the live calls after the replay are judged against that history: a delete right after the replay is a delete after access when the replayed read was less than 30 seconds before the latest replayed call in the first run.
  • A call is replayed only while it is the next one listed: the same callIndex and the same tool. The first call that is not, and every call after it, is live and checked in full.
  • replayedCallsResumeAtMs (optional) is when the first run reached the call this run continues live with, the call it paused at, in milliseconds from its start. Without it the latest replayed call is placed at now, so the time between it and the paused call is lost: a list, a call that took 5 seconds, then a send that paused, is refused on resume as a list followed at once by a send. With it, that moment is placed at now at the first live operation after the replay (a tool call or a call into a function in globals), and the replayed calls keep their original distance to it. It applies only when every listed call was replayed; a run that leaves the list early keeps the latest replayed call at now. It needs replayedCalls and must be a finite number not below the last elapsedMs, otherwise run() throws a TypeError.
  • Calls to functions in globals are not listed: they run again, under the rate limit.
  • The list is checked when run() is called: at most maxToolCalls entries, callIndex an integer from 0 that increases, toolName of 1 to 256 characters, elapsedMs a finite number from 0 that does not decrease. Anything else is a TypeError, and the script does not run. The script cannot see or change the list.
  • Without the option nothing changes. It applies to the double VM, the worker pool, PortableEnclave and AgentScriptRunner (AgentScriptRunner.capabilities includes 'replayed-calls'); a sandbox without these checks ignores it.
  • To find out at run time whether the installed version has it, read ENCLAVE_RUN_FEATURES, exported by @enclave-vm/core and @enclave-vm/core/worker: it includes 'replayed-calls', 'replayed-calls-resume' for replayedCallsResumeAtMs, and 'refused-call' for result.refusedCall (below). An older version has no such export and ignores the options.
import * as enclaveCore from '@enclave-vm/core';

const canReplay = enclaveCore.ENCLAVE_RUN_FEATURES?.includes('replayed-calls') ?? false;

Calls the Enclave Refused

result.refusedCall tells the host, without reading error text, that the enclave itself refused a tool call during the run: { code, toolName?, pattern? }. code is MAX_TOOL_CALLS_EXCEEDED, RATE_LIMIT_EXCEEDED, OPERATION_NOT_ALLOWED (outside allowedOperationPattern), OPERATION_BLOCKED (blockedOperationPatterns) or SUSPICIOUS_SEQUENCE, with the detector's id as pattern.

  • It holds the first refusal of the run, also when the script caught the error and went on.
  • It is set on the host side only. A script that throws an error with the same message does not set it, and a run without a refusal has no refusedCall.
  • A refused call never reached the host, so it has no callIndex. toolName is absent where the limit is applied before the name is read: the tool-call cap of PortableEnclave and of the single VM.
  • Double VM, worker pool, PortableEnclave and AgentScriptRunner, and the tool-call cap of the single VM in both bridge modes.

Tool Namespaces

Expose tools to scripts as namespaced functions instead of (or alongside) callTool():

const enclave = new Enclave({
  toolHandler: async (name, args) => callMyTool(name, args),
  toolNamespaces: {
    mail: ['list', 'send'], // mail.list(args) calls the tool 'mail.list'
    users: { get: 'users:get' }, // users.get(args) calls the tool 'users:get'
  },
});

const result = await enclave.run(`
  const inbox = await mail.list({ unread: true });
  const sender = await users.get({ id: inbox[0].from });
  return sender.name;
`);

A namespace method call is a callTool() call: mail.list(args, options) behaves exactly like callTool('mail.list', args, options). It counts toward maxToolCalls, goes through the double VM's rate limit, operation-name and suspicious-sequence checks, its result is sanitized, and it reaches your toolHandler. args defaults to {}. Each namespace is a frozen, null-prototype object created inside the sandbox, so aliasing (const m = mail; m.list()) and destructuring work and no host object is exposed.

The constructor throws a TypeError (Invalid toolNamespaces: ...) for names that are not identifiers, prototype keys (__proto__, constructor, prototype), names starting with __, reserved words and sandbox globals used as namespaces (callTool, Math, console, ...), identifiers the AgentScript validator refuses (process, fetch, ...), namespaces that collide with a custom global, duplicated methods, and tool names every adapter cannot carry (empty, over 256 characters, or outside letters, digits, :, ., _ and - starting with a letter, including a generated <namespace>.<method> name).

Prefer namespaces over exposing tools as functions in globals: functions in globals are gated and sanitized (see Custom Globals), but the suspicious-sequence detectors only see tool calls.

callTool Options

Scripts can pass options as the third argument of callTool (or the second argument of a namespace method):

const r = await callTool('users:get', { id }, { throwOnError: false });
if (r.success) {
  return r.data;
}
return { failed: r.error.message }; // r.error: { name, message, code?, toolName }

| Option | Default | Description | | -------------- | ------- | ---------------------------------------------------------------------------------------------------------------------- | | throwOnError | true | false: resolve to { success: true, data } or, when the tool fails, { success: false, error } instead of throwing |

Only failures of the tool itself (the handler threw or rejected, or its result could not be delivered) are returned this way; the error object is plain data with no stack. Refusals by the enclave (abort, maxToolCalls, rate limit, operation-name and suspicious-sequence checks, invalid arguments) always throw. Options are applied inside the sandbox and are not passed to the toolHandler.

Console Handler

Without a consoleHandler, console is allowed only at PERMISSIVE and writes to the host process console. With one, scripts may use console at every security level and each call goes to the handler instead:

import { Enclave, type ConsoleHandler } from '@enclave-vm/core';

const consoleHandler: ConsoleHandler = (level, message) => logger[level](message);
const enclave = new Enclave({ securityLevel: 'STRICT', consoleHandler });

await enclave.run(`console.info('users', { count: 2 }); return 1;`); // logger.info('users {"count":2}')
  • level is a ConsoleLevel ('log' | 'info' | 'warn' | 'error' | 'debug'); message is the formatted line (arguments joined by spaces, objects JSON-serialized).
  • maxConsoleCalls and maxConsoleOutputBytes are checked before the handler runs; past a limit the script's call throws and the handler is not called.
  • The handler's return value is ignored and anything it throws or rejects with is swallowed.
  • The handler is not started for a console call a script makes with the stack nearly full (less than 128 KB left): that line is dropped. Without a handler, at PERMISSIVE, such a call throws a RangeError in the script instead of starting the host console. See A script at a full stack.
  • The script's console is a frozen, null-prototype object built inside the sandbox; it leads to neither the handler nor any host object.
  • Supported by the double VM (default), the vm adapter and the worker_threads adapter. A custom sandboxAdapter receives the handler as context.consoleHandler; the built-in InterpreterAdapter passes it one line of text per call, like the other adapters.
  • Combining a consoleHandler with a console entry in globals throws a TypeError.

Custom Globals

You can provide custom globals to the VM:

const enclave = new Enclave({
  globals: {
    config: { apiUrl: 'https://api.example.com' },
    helpers: {
      formatDate: (date: Date) => date.toISOString(),
    },
  },
  allowFunctionsInGlobals: true, // Required when globals contain functions
  toolHandler: async (name, args) => {
    /* ... */
  },
});

const result = await enclave.run(`
  const url = config.apiUrl;
  const formatted = helpers.formatDate(new Date());
  return { url, formatted };
`);

Set allowFunctionsInGlobals: true only when you intentionally provide functions: a function in globals is code of your host that a script can call, and what it can reach through its closure is yours to judge.

Every call from the script into a function from globals (including functions nested in objects) goes through the enclave's gate:

  • it is refused once the execution is aborted, and counts toward maxGlobalFunctionCalls (default: 10 × maxToolCalls), not toward maxToolCalls;
  • its arguments are copied into plain host data first, the way tool arguments are: the function receives null-prototype objects, arrays, primitives and Dates, never a live script value, and a call that passes a function or a symbol is refused. The script's this is not passed either;
  • in the double VM (the default) it shares the operation rate limit (doubleVm.parentValidation.maxOperationsPerSecond) with tool calls;
  • its return value is sanitized like a tool result: the script receives a plain-data copy, and a value containing functions or symbols, or exceeding the sanitize depth/size limits, is refused;
  • an error it throws reaches the script as a plain error without the host stack;
  • calling it with new is refused.

The suspicious-sequence detectors only look at tool calls, so expose tools with toolNamespaces or callTool(), not as functions. The worker_threads adapter never passes functions into the sandbox.

Values passed in globals are read-only inside the sandbox. They are the host's own objects, shared by every execution of the enclave, so a script cannot assign to them, add or delete properties, freeze them, or call a built-in method that changes its receiver (push, sort, Map.prototype.set, Date.prototype.setTime, ...): the attempt throws, or is ignored at PERMISSIVE. Reading works as before, and an array returned by a built-in method (map, filter, slice, ...) is the script's own copy, which it can sort or extend. To let scripts keep state, return it from a tool instead.

A custom global cannot be named Object: the sandbox provides its own. The constructor throws.

A function is not started when the script calls it with the stack nearly full (less than 128 KB left): the call throws a RangeError in the script, and the function has not run. The check only decides whether a function starts: it is never started halfway. It says nothing about a function that did start. An async function that is still in progress when toolCallGraceMs is over is left behind like a tool call, and run() ends without its result reaching the script.

The validation of globals judges what a script can reach through a value, not only what the value has itself. The methods of a class are functions in globals: an instance of a class with methods needs allowFunctionsInGlobals: true, and so does a function in a property that is not enumerable or is keyed by a symbol. Code that runs when a property is read is refused whatever is allowed: a getter or setter, on the value or on its class, and a Proxy of an object. That includes a Buffer (pass a Uint8Array) and an Error object (pass its message). A function passed as a global is judged as a function; what hangs on it is not looked at. An instance of a class without methods or accessors is plain data and is accepted, unless secureProxyConfig.blockConstructor is off (as at PERMISSIVE): then a script can read its constructor, which is a function.

A regular expression passed in globals can be read (source, flags, global, ...) but not run: test, exec and its use as the pattern of match, matchAll, replace, search or split throw, at every security level. A match would run the host's pattern on a text the script chooses, outside the rules that apply to the script's own expressions, and with the g or y flag it writes lastIndex on the host's object. Pass a function that does the matching, or let the script build the expression from source and flags where the preset allows RegExp. The same goes for match, matchAll and search on a String object (new String(...)) passed in globals; a plain string is not affected.

With the single VM, an object of the script's own that a host built-in hands back to a callback (the object a script gave reduce to collect into) stays the script's and stays writable. The runtime recognises it by its prototype chain, which ends in the sandbox's Object.prototype. An object without a prototype (Object.create(null)) carries nothing that says who made it and is treated as the host's, so it arrives read-only in the callback: collect into {} or an array.

Inside arrays, Maps and Sets only plain data is allowed (primitives, plain objects, arrays, Maps, Sets, Dates, RegExps, typed arrays): the built-in methods of those collections (forEach, iteration, get) hand elements to the script directly, so a function (or an object with methods) stored there would be called without the gate. The constructor refuses it with an error naming the path, e.g. Custom global "cfg" contains a function inside a collection at hooks.0.run. Every own entry counts there, enumerable or not, and Map and Set subclasses are refused inside collections. Arrays anywhere in globals must be plain arrays (no Proxy, no custom prototype), since those can hide entries from validation. Promises, WeakMaps, iterators and generators are refused anywhere in globals, since their contents cannot be validated.

Execution Result

interface ExecutionResult<T> {
  success: boolean;
  value?: T; // Result when success is true
  error?: {
    message: string;
    name: string;
    code?: string; // Error code (e.g., 'VALIDATION_ERROR'; see "Error Codes")
    stack?: string; // Only for errors made outside the sandbox
    data?: Record<string, unknown>;
  };
  stats: {
    duration: number; // Execution time in ms
    toolCallCount: number; // Number of tool calls made
    iterationCount: number; // Number of loop iterations
    memoryUsage?: number; // Peak tracked memory in bytes (when memoryLimit is set)
    startTime: number;
    endTime: number;
  };
  scoringResult?: ScoringGateResult; // When a scoring gate evaluated the script
  review?: { decisions: ReviewRecord[] }; // Once review has started: every decision of the hooks
  refusedCall?: { code: string; toolName?: string; pattern?: string }; // The first tool call the enclave refused itself
}

result.error is plain, bounded text. Whatever a script threw, name and message are strings: name of at most 256 characters, message of at most 16,384. A thrown string is the message; a thrown null, undefined or other primitive is named in the message (The script threw null); an object without a string message is reported as The script threw a value that is not an error. An object a script makes to look like the memory-limit error is not reported as one. The message of a validation failure is cut to 500 characters per issue and 32,768 in total; error.data.issues holds the issues.

Errors made inside the sandbox have no stack. No sandbox realm captures a stack trace, so error.stack is undefined for the script and absent from result.error for what a script throws and for what the runtime raises inside the sandbox (a limit, a failed tool call). This holds for the double VM and the single VM, in process and in a worker. Errors the host makes outside a sandbox realm (an adapter that fails, a worker pool error, an error of the InterpreterAdapter, which has no realm of its own) keep their stack. With sanitizeStackTraces on (the default for STRICT and SECURE), such a stack is sanitized, whichever stage raised the error: stack frames become at [REDACTED] and paths, URLs and file locations in the remaining lines are redacted.

Error Codes

| Code | Description | | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- | | VALIDATION_ERROR | AST validation failed, or the script is too large or not a string | | SECURITY_VIOLATION | The script contains a dynamic import (also with validate: false), or a blocked operation was recorded at STRICT or SECURE | | SCORING_BLOCKED | Refused by the scoring gate | | REVIEW_NEEDS_CHANGES | A review hook asks for changes to the script before it runs (or to a call, as the error the script sees) | | REVIEW_NEEDS_APPROVAL | A review hook asks for approval of the script, or of a call (error.data names the call: toolName, callIndex, args) | | REVIEW_DENIED | A review hook denied the script, or post stopped the run (a denied call is an error the script sees) | | REVIEW_FAILED | A review hook threw, did not answer within review.timeoutMs, or answered out of shape | | DOUBLE_VM_EXECUTION_ERROR | The script failed in the double VM (the default): an error it did not catch, a failed tool call, the tool-call or iteration limit, a timeout | | VM_EXECUTION_ERROR | The same with doubleVm: { enabled: false }; with either VM, the timeout of a script that was only waiting | | MEMORY_LIMIT_EXCEEDED | memoryLimit exceeded | | SERIALIZATION_LIMIT_EXCEEDED | The returned value is larger than the memory limit allows | | EXECUTION_ERROR | The adapter itself failed; with the worker pool error.name is the pool's error (WorkerTimeoutError, ...) | | ENCLAVE_ERROR | Any other failure outside the sandbox, such as a script with a syntax error | | EXECUTION_TIMEOUT, STEP_LIMIT_EXCEEDED | The timeout and the step budget of the InterpreterAdapter |

For the limits error.message says which one ended the script: Script execution timed out ..., Maximum iteration limit exceeded ..., Maximum tool call limit exceeded ....

How timeout Is Enforced

  • The time is the script's: the clock starts when the sandbox is ready to run it. Validation, the transform and the creation of the sandbox adapter (once per enclave; with the worker pool that starts the worker threads) come before it. Waiting for a free worker counts, and a script whose time has passed while it waited is not started: run() returns ExecutionAbortedError.
  • Until the script's first await, Node's vm interrupts it at the deadline.
  • After that, the script checks the clock itself: the transformer inserts a check at the start of every function and loop body and in front of a parameter default, so synchronous work, recursion and promise chains that never yield are stopped at the deadline as well. A script that catches the timeout error cannot enter another function or loop iteration. The deadline is cooperative: it is looked at between the steps of the script's own code.
  • A tool call in progress at the deadline is not cut off, and its result is delivered. This does not hold with adapter: 'worker_threads': there the deadline fails a tool call still in progress with Execution aborted (EXECUTION_ABORTED) at once, without waiting for toolCallGraceMs, and the handler's later result is not delivered to the script. From then on the next tool call or call into a host function is refused with Execution aborted. The same holds for an async function from globals.
  • That wait has an end: toolCallGraceMs after the deadline the execution ends with the timeout error, whatever is still in progress, and error.data.pendingHostCalls says how many calls were left running. The default is the value of timeout, so run() takes at most twice timeout. 0 ends every execution at the deadline; Infinity waits for the handler however long it takes, as versions up to 2.18 did (a handler that never settles then keeps run() from settling).
  • When run() has returned, for whatever reason, the script is finished for the host as well. What it left behind (a tool call it did not await, with a then on it) can no longer call a tool, a function from globals or the console, and it ends within a bounded number of steps: its next checks throw Script execution has ended.
  • A script that only waits is ended as well. Waiting takes no code: a thenable that never calls back (return { then: () => 0 }) is enough, and nothing runs that could look at the clock. So the enclave keeps count of what the host has in flight for the script (tool calls, async functions from globals), and from the deadline on run() returns the timeout error as soon as that count is zero. A sandbox has no timers and no I/O, so nothing else could wake the script. (With adapter: 'worker_threads' the pool ends such a script like a busy one: with its worker, five seconds after the deadline.)
  • Not covered: a single built-in call that does all its work natively, and a script run with transform: false. The engine finishes one call into a built-in before the next check, so timeout does not bound its duration. And the enclave cannot stop your toolHandler: a call it stops waiting for keeps running in the host, so a tool that changes something should be safe to repeat, or have a time limit of its own. For a stop the script cannot influence, use adapter: 'worker_threads': a script that is still running five seconds after its timeout is terminated with its worker (see Worker Pool Adapter). A process you can terminate does the same for everything else that runs in it.

What the Pre-Scanner Checks

Enclave runs the pre-scanner on the script as it was written, before anything parses it, with the pre-scanner preset named like the AST preset:

| AST preset | Pre-scanner preset | Script | Lines | String literals | Regex literals | Bidirectional controls | Invisible characters | | ----------------------- | ------------------ | ---------------------------------------------------- | ------------------------------- | --------------------------- | ------------------------------------------- | ---------------------- | -------------------- | | agentscript (default) | agentscript | 100 KB, nesting 20 | 1,000 of at most 2,000 chars | 10 KB each, 100 KB in total | refused | refused | refused | | strict | strict | 500 KB, nesting 30 | 2,000 of at most 5,000 chars | 50 KB each, 500 KB in total | 10 of at most 100 chars, analyzed for ReDoS | refused | refused | | secure | secure | 1 MB, nesting 40 | 5,000 of at most 8,000 chars | 100 KB each, 1 MB in total | 20 of at most 200 chars, analyzed | refused | allowed | | standard, babel | standard | 5 MB, nesting 50 | 10,000 of at most 10,000 chars | 500 KB each, 5 MB in total | 30 of at most 500 chars, analyzed | allowed | allowed | | permissive | permissive | 5,242,880 chars (the enclave's maximum), nesting 100 | 100,000 of at most 50,000 chars | 1 MB each, 10 MB in total | allowed | allowed | allowed |

Every preset except permissive also refuses a null byte, more consecutive operators than its limit, and one of a fixed list of letters that look like ASCII letters (Cyrillic and Greek look-alikes of a, c, e, o, p, x, y, and the full-width a and e), anywhere in the text.

The preScan option picks another preset or changes single limits of the one in force; the pre-scanner's own absolute maximums still hold:

// The limits enclaves had before 2.19.2, whatever the AST preset
const enclave = new Enclave({ preScan: { preset: 'standard' } });

// The agentscript pre-scanner with room for larger string literals (for the reference sidecar, say).
// The limit on one literal and the limit on all literals together are separate: raise both.
const enclave = new Enclave({
  preScan: {
    config: {
      maxInputSize: 1024 * 1024,
      maxLineLength: 100000,
      maxStringLength: 512 * 1024,
      maxTotalStringContent: 1024 * 1024,
    },
  },
});

A line is at most 100,000 characters under any configuration (the pre-scanner's absolute maximum), so a literal longer than that has to be a template literal over several lines.

With validate: false the pre-scanner does not run; a script is limited to 5,242,880 characters in any case.

Worker Pool Adapter

adapter: 'worker_threads' runs each script in a worker thread taken from a pool. Inside the worker the script runs in the same sandbox as in process: the double VM by default. The worker thread is a layer around that sandbox and adds what only a separate thread can:

  • A heap limit per worker. A script that outgrows memoryLimitPerWorker loses its worker, and the pool starts a replacement. The engine enforces the limit, or the pool does when the engine cannot: see The Worker Heap Limit, also for what the limit does not guarantee.
  • A stop that does not depend on the script. A script that does not end is terminated together with its worker (timeout plus a grace period of five seconds). In process, a script that cannot be interrupted keeps the host's thread.
import { Enclave } from '@enclave-vm/core';

const enclave = new Enclave({
  adapter: 'worker_threads', // Run scripts in the worker pool
  workerPoolConfig: {
    minWorkers: 2,
    maxWorkers: 8,
    memoryLimitPerWorker: 256 * 1024 * 1024, // 256MB
  },
  toolHandler: async (name, args) => {
    /* ... */
  },
});

A worker thread is not a sandbox by itself: it has the whole Node.js API and shares the process with the host. It is also not process isolation. For tenants that must not share a process, run one enclave per process or container.

What Is Different From In-Process Execution

  • Tool calls are sent to the host thread and go through the same tool bridge as in-process tool calls (argument and result sanitization, sidecar references, the tool-call limit), so they behave the same. Tool names must start with a letter and contain only letters, digits, :, ., _ and -; a call with another name fails with an error the script can catch.
  • Custom globals reach a worker as JSON data. Functions in globals are not available there.
  • Console output without a consoleHandler is printed by the host with a [Worker] prefix.
  • toolBridge.mode: 'direct' does not apply: requests and responses always cross as strings.

When to Use the Worker Pool

| Scenario | Recommendation | | ------------------------------------- | ------------------------------------ | | Trusted internal scripts | In process (lower overhead) | | Untrusted AI-generated code | Worker Pool (hard stop) | | Memory-sensitive workloads | Worker Pool (heap limit per worker) | | Tenants that must not share a process | One enclave per process or container | | A host that must survive any script | One enclave per process or container |

Worker Pool Configuration

| Option | Default | Description | | ------------------------ | --------- | ---------------------------------------------------------------- | | minWorkers | 2 | Minimum warm workers | | maxWorkers | CPU count | Maximum concurrent workers | | memoryLimitPerWorker | 128MB | Heap limit of each worker (its old generation); 0: none | | memoryCheckIntervalMs | 1000 | Interval of the memory monitor | | maxMessagesPerSecond | 1000 | Messages a worker may send per second while it runs an execution | | maxPendingToolCalls | 100 | Tool calls one execution may have in flight | | maxMessageSizeBytes | 16MB | Largest single message a worker may send | | maxExecutionsPerWorker | 1000 | Recycle after N executions | | maxQueueSize | 100 | Maximum pending executions | | queueTimeoutMs | 30000 | Longest wait for a free worker | | idleTimeoutMs | 30000 | Time before idle worker release |

These are the defaults of WorkerPoolConfig (DEFAULT_WORKER_POOL_CONFIG). An enclave starts from the preset of its security level, exported as WORKER_POOL_PRESETS, and workerPoolConfig overrides single settings of it:

| Level | minWorkers | maxWorkers | memoryLimitPerWorker | maxMessagesPerSecond | maxMessageSizeBytes | maxExecutionsPerWorker | | ---------- | ---------- | ---------- | -------------------- | -------------------- | ------------------- | ---------------------- | | STRICT | 2 | 4 | 64MB | 100 | 1MB | 100 | | SECURE | 2 | 8 | 128MB | 500 | 4MB | 500 | | STANDARD | 2 | 16 | 256MB | 1000 | 16MB | 1000 | | PERMISSIVE | 4 | 32 | 512MB | 5000 | 64MB | 5000 |

Executions beyond maxWorkers wait in a queue (maxQueueSize, queueTimeoutMs). The wait counts against the script's timeout, so size maxWorkers for the concurrency you expect.

maxMessagesPerSecond is counted per execution: what an earlier execution sent from the same worker is not held against the next one, and the result and the worker's confirmation that it is idle are not counted. maxMessageSizeBytes is applied before a message is parsed. The limit an execution gets is never below what the enclave's own limits let one message carry (a tool request of toolBridge.maxPayloadBytes, a result of memoryLimit), so it decides where those are larger than it or off: with memoryLimit: 0 it is the only bound on the size of a result.

How a Worker Execution Ends

A worker runs one execution at a time. After its result it confirms that it is idle, which it can only do when nothing of the script keeps its thread busy, and only then is it given to the next execution. A worker that does not confirm within one second is terminated and replaced; the result it sent stands.

An execution the pool ends itself ends its worker too, and the pool starts a new one. run() then returns error.code EXECUTION_ERROR with one of these in error.name:

| error.name | When | | ------------------------------------- | -------