Skip to main content
API reference for the @enclave-vm/core package.

Installation

Worker-safe AgentScript runner

The @enclave-vm/core/worker entry exports PortableEnclave, AgentScriptRunner, and their PortableEnclaveOptions, PortableRunOptions, and AgentScriptRunnerOptions types. It runs in Node and Cloudflare Workers with nodejs_compat without Node VM or worker-thread modules. AgentScriptRunner accepts raw, untrusted AgentScript. It pre-scans, transforms, and validates the source before the bounded interpreter runs it. InterpreterAdapter is a lower-level export for code that has already been transformed and validated; it does not perform those checks itself.
AgentScriptRunnerOptions extends the supported PortableEnclaveOptions and adds hostFunctions, required maxHostFunctionCalls, optional maxSteps, maxCallDepth, maxPendingCalls, and rapidEnumeration thresholds and per-operation overrides. Host callbacks receive copied plain-data arguments; their results are copied and bounded before the script sees them. The runner refuses unsupported VM-only options and pre-scan overrides at construction. PortableEnclaveOptions extends CreateEnclaveOptions with an interpreter object for maxSteps, maxCallDepth, maxPendingCalls, and maxAllocationBytes. PortableEnclave.run(code, toolHandler?, runOptions?) accepts PortableRunOptions.maxToolResultBytes and onToolBridgeFailure. The interpreter charges copied host-function results and tool responses against its cumulative allocation budget. maxSteps bounds interpreted CPU work, including built-in operations. timeout is checked between steps and at I/O boundaries; on deployed Cloudflare Workers it is not a hard wall-time cutoff during CPU-only work, and synchronous host callbacks cannot be preempted.

Enclave Class

The main class for secure code execution.

Constructor

The constructor throws a TypeError for an option outside its type or range (a limit that is not a finite integer in range, a switch that is not a boolean, an unknown security level). An option passed as undefined has its default.

CreateEnclaveOptions

| workerPoolConfig | Partial<WorkerPoolConfig> | by level | Worker pool settings for adapter: 'worker_threads' | | sandboxAdapter | SandboxAdapter | undefined | Run scripts with this adapter instead of the double VM (for hosts without node:vm); not disposed by the enclave | maxSanitizeProperties counts keys, array slots, Map entries and Set entries across the whole value. Every Map entry counts, including one with a non-string key that is omitted from the copy returned to the script. A value over the limit is refused. See Configuration for the ranges and for what each limit covers.

Methods

run(code, toolHandler?, options?)

Execute code in the sandbox.
Parameters:
  • code - The script to execute, at most 5,242,880 characters
  • toolHandler - Optional tool handler for this run; replaces the one from the constructor
  • options.onToolBridgeFailure - Optional observer called when a successful tool result is refused by the bridge before it reaches the script. An error thrown by the observer does not change the bridge result.
  • options.maxToolResultBytes - Optional limit on the JSON bytes of a sanitized tool result before sidecar storage. A larger result fails its tool call.
Returns: ExecutionResult. run() does not reject for a failing script: the failure is in the result.
Example:

initialize()

Initialize the scoring gate, for a scorer that needs it (the local-llm scorer loads its model here). run() initializes the gate on first use when this was not called.

getEffectiveConfig()

The limits in effect, after the security level and the options were merged.
getSecurityLevel() returns the level alone, and getScoringStats() the cache statistics of the scoring gate (null without a gate).

dispose()

Clean up resources.
Example:

Validating Without Executing

Enclave has no method that only validates. Validation is the job of @enclave-vm/ast, which the enclave uses itself:
The enclave validates the script after its own transform and with its own list of allowed globals, so a result from a validator you build yourself can differ from what run() decides. See the @enclave-vm/ast reference.

runAgentScript(code, options?)

Create an enclave, run one script and dispose the enclave.

Types

SecurityLevel

ToolHandler

The script’s callTool(name, args, options) options (CallToolOptions, e.g. { throwOnError: false }) are applied inside the sandbox and are not passed to the handler. Example:

ExecutionError

name and message are strings of bounded length (256 and 16,384 characters) whatever a script threw. An error made inside the sandbox has no stack. The values of code:

ExecutionStats

ScoringGateConfig

See AI Scoring Gate.

Adapters

WorkerPoolAdapter

The pool behind adapter: 'worker_threads'. Create one yourself to read its metrics, and pass it as sandboxAdapter:
See Worker Pool for the options and for the errors an execution can end with.

InterpreterAdapter

A tree-walking interpreter for hosts without node:vm:
See The Interpreter Adapter. The double VM is not an adapter you create: it is on by default and configured with the doubleVm option. The interpreter behind the adapter is exported as well, for a host that drives it without an Enclave: Interpreter (options: InterpreterOptions) and the errors a run ends with. A script cannot catch StepLimitError or DeadlineError. Through an Enclave they arrive as result.error.code STEP_LIMIT_EXCEEDED and EXECUTION_TIMEOUT.

Scoring Classes

ScoringGate is the gate an enclave builds from scoringGate; it can be used on its own:
RuleBasedScorer scores features, not source text. FeatureExtractor.extract(code) produces them, and throws FeatureExtractionError for text it cannot parse:

Reference Sidecar

Pass large strings between tools by reference.

ReferenceSidecarOptions

The defaults follow the security level. See Reference Sidecar. Two functions give the values in force:
getReferenceConfig(securityLevel, overrides?) returns the defaults of a level with your overrides applied. getMaxTotalResolvedSize(config) returns the limit on what one execution resolves in total: config.maxTotalResolvedSize when it is a number of at least 0, otherwise twice config.maxTotalSize.

Process-Level Functions

Node.js ends the process when a promise is rejected and nothing handles it, and that rule covers the promises of a sandbox: an async function of a script that throws and is not awaited, a failing tool call nobody awaits. The enclave therefore answers the process events unhandledRejection and rejectionHandled itself for every promise that is not one of the host realm. Your own rejections reach your listeners, or end the process, as before. Two functions are for a host that wants this in its own hands.

disableSandboxRejectionGuard(disabled?)

Leaves every rejection to Node.js and to your listeners. It applies to the whole process, not to one enclave, and at once. disableSandboxRejectionGuard(false) undoes it, but not at once: the guard is active again from the next execution of any enclave, and until then rejections still reach your listeners. Call it only when your application has an unhandledRejection listener that decides for itself; without one, a rejection a script leaves behind ends the process.

isHostPromise(promise)

Whether a promise was made by the host’s Promise (or a subclass of it). A script cannot make its promise pass this test. With the guard disabled, your listener has to ignore every promise for which it returns false, and must not touch the reason: it is a value of the script.
Under --unhandled-rejections=strict Node.js raises the exception before it emits anything, and under =warn it prints its warning first: use the default mode (throw) or none.

Complete Example