Quick Example
Core Options
Scripts run in strict mode at every security level:
this is undefined outside a method call, an assignment to an undeclared name is an error, and a write that cannot happen (over a built-in method, or to a frozen object) throws a TypeError instead of being ignored.
A script has a maximum size of 5,242,880 characters. A longer one, or a script that is not a string, fails with VALIDATION_ERROR before anything parses it. With validation on, the pre-scanner’s limits come first: 100 KB with the default agentscript preset (see preScan).
Option Values
The constructor checks the options below and throws aTypeError for a value outside the type or range. A limit is a finite integer in its range and a switch is a boolean: Infinity, NaN and a value of another type (a numeric string, null) are refused. 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.
Console
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 reaches the handler instead:
levelis'log' | 'info' | 'warn' | 'error' | 'debug'(ConsoleLevel);messageis the formatted line: arguments joined by spaces, objects JSON-serialized.maxConsoleCallsandmaxConsoleOutputBytesare 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 script sees neither.
- The script’s
consoleis a frozen, null-prototype object built inside the sandbox. It holds no reference the script can reach to the handler or to any host object. - Supported by the double VM (default), the
vmadapter and theworker_threadsadapter. A custom sandbox adapter receives the handler ascontext.consoleHandler; the built-inInterpreterAdapterpasses it one line of text per call and applies the same two limits, like the other adapters.@enclave-vm/browserhas its own options and is unchanged. - A
consoleHandlercannot be combined with aconsoleentry inglobals(the constructor throws aTypeError).
Memory Tracking
memoryLimit is the enclave’s own accounting, not a limit of the engine’s heap. It counts the operations that make text and arrays grow:
- Text: concatenation (
a + b, andx += y, which is charged likex + y) and the methods that multiply their input (repeat,padStart,padEnd,join). - Arrays: no array has more slots than the limit holds, at 8 bytes per slot, and the slots an operation adds are charged:
push,unshift,splice, a write to an element beyond the end, an assignment tolength,Array(n), the elementsconcat,flat,flatMapand a spread literal add, and whatArray.frommakes out of something that is not an array.
[].indexOf.call({ length: 1e15 }, x) fails with MEMORY_LIMIT_EXCEEDED instead of walking that length. One call into a built-in is not interrupted at the deadline, so its length is what bounds it. Of an object that is not an array the length is read once.
It does not count a copy (a script can hold many arrays that are each within the limit), and it does not count object literals, Maps and Sets. A script that goes over the limit fails with MEMORY_LIMIT_EXCEEDED. With a limit set, the VM adapters also measure the returned value: one whose serialized size is estimated above memoryLimit, or above 50 MB where the limit is larger, fails with SERIALIZATION_LIMIT_EXCEEDED.
Treat the limit as an estimate. The worker pool adds a heap limit of the engine per worker; a worker thread shares the host’s process, so that limit is a backstop and not a guarantee that the host survives. Where the host must survive whatever a script allocates, run the enclave in a child process or a container with a memory limit of the operating system.
Reference Sidecar
Double VM Layer
AI Scoring Gate
Worker Pool Adapter
The defaults shown are those of the
STANDARD security level; see Worker Pool for the other levels and for the errors an execution can end with.
Custom Sandbox Adapter
@enclave-vm/core runs scripts with node:vm. Where that is not available (a browser worker, an edge runtime), run() fails with @enclave-vm/core needs node:vm, ...; pass a sandboxAdapter to run scripts another way. It replaces the double VM and the adapter option.
execute, but isolation is then the adapter’s job: it receives the ExecutionContext (limits, tool handler, stats, abort signal) and must enforce it. The caller owns the adapter: enclave.dispose() does not dispose it, so one adapter can serve several enclaves. In a browser, @enclave-vm/browser is usually the better fit.
The Interpreter Adapter
InterpreterAdapter is a tree-walking interpreter for AgentScript with no dependency on node:vm, QuickJS or WASM, for runtimes that have none of them. It runs the language the validator accepts, and a conformance suite compares it with the default sandbox script by script. Tool calls go through the same host bridge as in the other adapters (JSON both ways, the tool-call limit, sanitized arguments and results), and the returned value is copied into plain data.
It differs from the VM adapters in what isolates a script. There is one realm: the script works on ordinary objects of the host, and the interpreter decides, operation by operation, what it may do with them. So:
- The standard globals are frozen stand-ins with a fixed set of members (
Object.keysexists,Object.getPrototypeOfdoes not), and nothing but data the script created can be changed. - Calls are awaited as they are made: a function of the script cannot run in the background.
- Built-ins that would call a function of the script themselves are refused where the interpreter cannot wait for it (
JSON.parsewith a reviver,Array.fromwith a mapping function,replacewith a function). - Regular expressions, classes, generators and labels are not available.
- Custom
globalsmust be JSON data; they are given to the script as frozen copies. - A built-in method works on the kind of value it belongs to: an array method on an array, a string method on a string (
[].join.call({ length: 3 })is refused).call,applyandbindare resolved to the function they invoke, so a limit holds however a call is written. - One call cannot make more than a script may hold: an array of at most 1,000,000 items (
concat,flat,push,split), a text of at most 16,000,000 chars when an array is joined or converted to text (join,'' + array, a template literal, an array given to a built-in that expects text), 1,000,000 chars fromrepeat,padStart,padEndand from the replacements ofreplace/replaceAll.JSON.stringifycounts its indentation, and whatJSON.parsebuilds is charged tomaxAllocationBytesbefore it is built. - The timeout ends a script that computes as well as one that waits. The interpreter reads the clock every few hundred steps and before every built-in call, and the execution fails with
EXECUTION_TIMEOUT. - The work of a built-in counts as steps, in proportion to what it reads: a built-in that works through a long text or array uses up
maxStepsand shows instats.iterationCount, like a loop of the script would. - A function cannot be stored under a name the engine calls by itself:
then,toString,valueOf,toJSON,toLocaleString,toISOString, andjoinon an array. The write is refused, so converting, serializing or awaiting a value never runs a function of the script; any other value may be stored under those names. - Of an iterator (
values(),keys(),entries()of an array) onlynextcan be called.for…of, spread and destructuring work as usual. - A BigInt is limited to 1,048,576 bits. Beyond the size of a number, what it holds is charged to the allocation budget and working on it counts as steps.
- A text made by
+is charged to the allocation budget in full when it is made. A variable that is appended to (s += x) is charged for what is appended, and in full once its value is used for anything else. - A script cannot catch the allocation limit, the step limit or the timeout: no
catchorfinallyof the script runs after one of them.
Security Options
An error made inside the sandbox has no
stack: no sandbox realm captures a stack trace, so error.stack is undefined for the script and absent from result.error. That covers what a script throws, and the errors the runtime raises inside the sandbox (a limit, a failed tool call). It 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 interpreter adapter, which has no realm of its own) keep their stack, and sanitizeStackTraces applies to those.
Execution Result
Therun() method returns:
result.error is plain text of bounded length, whatever a script threw: name is a string of at most 256 characters and message one of at most 16,384. A thrown string is the message; a thrown null, undefined, number 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. The message of a validation failure is cut to 500 characters per issue and 32,768 in total; error.data.issues holds the issues.
Error Codes
result.error.code is one of:
With the VM adapters the message of a timeout starts with
Script execution timed out. With sidecar enabled, a tool call whose references cannot be resolved within the limits fails inside the script like any failing tool call (see Reference Sidecar).
Related
- Overview - Getting started
- Security Levels - Preset comparison
- Tool System - Tool integration