> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentfront.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# @enclave-vm/core

> API reference for the @enclave-vm/core package

API reference for the `@enclave-vm/core` package.

## Installation

```bash theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
npm install @enclave-vm/core
```

## Enclave Class

The main class for secure code execution.

### Constructor

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
new Enclave(options?: CreateEnclaveOptions)
```

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

| Property | Type | Default | Description |
| - | - | - | - |
| `securityLevel` | `SecurityLevel` | `'STANDARD'` | Security preset |
| `preset` | `AstPreset` | `'agentscript'` | AST validation preset |
| `timeout` | `number` | `30000` (by level) | Execution timeout in ms, 1 to 2147483647. Cooperative in process; with the worker pool a script is terminated five seconds after it |
| `toolCallGraceMs` | `number` | same as `timeout` | How long a tool call in progress at the timeout may still take |
| `maxToolCalls` | `number` | `100` (by level) | Maximum tool calls per execution |
| `maxIterations` | `number` | `10000` (by level) | Maximum loop iterations |
| `memoryLimit` | `number` | `1048576` | Memory limit in bytes (1 MB), as the enclave counts it; `0` switches the tracking off |
| `toolHandler` | `ToolHandler` | `undefined` | Tool execution function |
| `toolNamespaces` | `ToolNamespaces` | `undefined` | Expose tools as `ns.method(args)` bindings that are `callTool()` calls |
| `consoleHandler` | `ConsoleHandler` | `undefined` | Receive the script's console calls as `(level, message)` instead of the host console; allows `console` at every security level |
| `maxConsoleCalls`, `maxConsoleOutputBytes` | `number` | by level | Limits on the script's console output |
| `globals` | `Record<string, unknown>` | `{}` | Custom globals |
| `allowFunctionsInGlobals` | `boolean` | by level | Allow functions in `globals` (calls are gated and results sanitized) |
| `maxGlobalFunctionCalls` | `number` | 10 × `maxToolCalls` | Maximum calls into functions from `globals` |
| `validate` | `boolean` | `true` | Validate the script before it runs. A dynamic import is refused also with `false` |
| `preScan` | `{ preset?, config? }` | the pre-scanner preset named like `preset` (`standard` for `babel`) | Which pre-scanner preset checks the text of a script before anything parses it, and overrides of single limits (`PartialPreScannerConfig` of `@enclave-vm/ast`) |
| `transform` | `boolean` | `true` | Transform the script before it runs |
| `realmGlobals` | `'allowlist' \| 'security-level'` | by preset | Which standard globals exist in the script's realm |
| `sanitizeStackTraces` | `boolean` | by level | Sanitize the stack of a returned error that has one (errors made inside the sandbox have none) |
| `maxSanitizeDepth`, `maxSanitizeProperties` | `number` | by level | Limits on values that cross the sandbox boundary |
| `secureProxyConfig` | `Partial<SecureProxyLevelConfig>` | by level | Which property names the runtime refuses on every value |
| `toolBridge` | `{ mode?, maxPayloadBytes?, acknowledgeInsecureDirect? }` | `{ mode: 'string', maxPayloadBytes: 5MB }` | How tool calls cross the sandbox boundary |
| `sidecar` | `ReferenceSidecarOptions` | `undefined` | Reference sidecar configuration |
| `scoringGate` | `ScoringGateConfig` | `undefined` | AI scoring configuration |
| `doubleVm` | `PartialDoubleVmConfig` | `{ enabled: true }` | Double VM configuration |
| `adapter` | `'vm' \| 'worker_threads'` | `'vm'` | Where the sandbox runs: in this process, or in a pool of worker threads. In both cases the script runs in the double VM (a single VM with `doubleVm: { enabled: false }`) |
| `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 |

See [Configuration](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/configuration.md) for the ranges and for what each limit covers.

### Methods

#### run(code, toolHandler?)

Execute code in the sandbox.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
async run<T = unknown>(code: string, toolHandler?: ToolHandler): Promise<ExecutionResult<T>>
```

**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

**Returns:** `ExecutionResult`. `run()` does not reject for a failing script: the failure is in the result.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ExecutionResult<T = unknown> {
  success: boolean;
  value?: T;
  error?: ExecutionError;
  stats: ExecutionStats;
  scoringResult?: ScoringGateResult;
}
```

**Example:**

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const result = await enclave.run(`
  const x = 1 + 2;
  return x;
`);
console.log(result.value); // 3
```

#### 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.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
initialize(): Promise<void>
```

#### getEffectiveConfig()

The limits in effect, after the security level and the options were merged.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
getEffectiveConfig(): {
  securityLevel: SecurityLevel;
  timeout: number;
  maxIterations: number;
  maxToolCalls: number;
  sanitizeStackTraces: boolean;
  maxSanitizeDepth: number;
  maxSanitizeProperties: number;
  memoryLimit: number;
  realmGlobals: 'allowlist' | 'security-level';
}
```

`getSecurityLevel()` returns the level alone, and `getScoringStats()` the cache statistics of the scoring gate (`null` without a gate).

#### dispose()

Clean up resources.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
dispose(): void
```

**Example:**

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const enclave = new Enclave();
try {
  await enclave.run(code);
} finally {
  enclave.dispose();
}
```

### Validating Without Executing

`Enclave` has no method that only validates. Validation is the job of `@enclave-vm/ast`, which the enclave uses itself:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { JSAstValidator, createAgentScriptPreset } from '@enclave-vm/ast';

const validator = new JSAstValidator(createAgentScriptPreset());
const validation = await validator.validate(`eval('dangerous');`);
// validation.valid === false
// validation.issues: [{ code, severity, message, location? }, ...]
```

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](https://docs.agentfront.dev/enclave/api-reference/ast-guard.md).

## runAgentScript(code, options?)

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

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function runAgentScript<T = unknown>(code: string, options?: CreateEnclaveOptions): Promise<ExecutionResult<T>>
```

## Types

### SecurityLevel

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
type SecurityLevel = 'STRICT' | 'SECURE' | 'STANDARD' | 'PERMISSIVE';
```

| Level | Description |
| - | - |
| `STRICT` | Maximum security for untrusted code |
| `SECURE` | High security for semi-trusted code |
| `STANDARD` | Balanced security for internal tools |
| `PERMISSIVE` | Minimal restrictions (testing only) |

### ToolHandler

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
type ToolHandler = (
  name: string,
  args: Record<string, unknown>
) => Promise<unknown>;
```

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:**

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const toolHandler: ToolHandler = async (name, args) => {
  switch (name) {
    case 'users:list':
      return db.users.findAll({ limit: args.limit });
    default:
      throw new Error(`Unknown tool: ${name}`);
  }
};
```

### ExecutionError

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ExecutionError {
  name: string;
  message: string;
  code?: string;
  stack?: string;
  data?: Record<string, unknown>;
}
```

`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`:

| Code | Description |
| - | - |
| `VALIDATION_ERROR` | AST validation failed, or the script is too large or not a string |
| `SECURITY_VIOLATION` | A dynamic import, or a blocked operation recorded at `STRICT` or `SECURE` |
| `SCORING_BLOCKED` | Refused by the scoring gate; `data` holds `totalScore`, `riskLevel`, `signals` |
| `DOUBLE_VM_EXECUTION_ERROR` | The script failed in the double VM: an error it did not catch, a failed tool call, the tool-call or iteration limit, a timeout |
| `VM_EXECUTION_ERROR` | The same in the single VM; with either VM, the timeout of a script that was only waiting |
| `MEMORY_LIMIT_EXCEEDED` | `memoryLimit` exceeded; `data` holds `usedBytes`, `limitBytes` |
| `SERIALIZATION_LIMIT_EXCEEDED` | The returned value is larger than the memory limit allows |
| `EXECUTION_ERROR` | The adapter itself failed (with the worker pool, `name` is the pool's error) |
| `ENCLAVE_ERROR` | Any other failure outside the sandbox, such as a syntax error in the script |
| `EXECUTION_TIMEOUT`, `STEP_LIMIT_EXCEEDED` | The timeout and the step budget of the `InterpreterAdapter` |

### ExecutionStats

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ExecutionStats {
  duration: number;
  toolCallCount: number;
  iterationCount: number;
  memoryUsage?: number; // Peak tracked memory, when memoryLimit is set
  startTime: number;
  endTime: number;
}
```

### ScoringGateConfig

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ScoringGateConfig {
  scorer?: ScorerType; // 'disabled' (default) | 'rule-based' | 'local-llm' | 'external-api'
  scoring?: ProgressiveScoringConfig; // Progressive mode: rule-based first, then a detailed scorer
  blockThreshold?: number; // Default 70
  warnThreshold?: number; // Default 40
  failOpen?: boolean; // Default true
  customRules?: Record<string, number>; // Base scores of the rule-based scorer by rule id
  toolNamespaces?: ToolNamespaces; // Default: the enclave's (a normalized list is accepted as well)
  localLlm?: LocalLlmConfig;
  externalApi?: ExternalApiConfig;
  cache?: ScoringCacheConfig;
  verbose?: boolean;
}

interface ScoringGateResult {
  allowed: boolean;
  warned?: boolean;
  totalScore?: number; // 0-100; absent when scoring failed
  riskLevel?: 'none' | 'low' | 'medium' | 'high' | 'critical';
  signals?: RiskSignal[]; // { id, score, description, level, context? }
  reason?: string;
  latencyMs: number;
  cached: boolean;
}
```

See [AI Scoring Gate](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/ai-scoring.md).

## Adapters

### WorkerPoolAdapter

The pool behind `adapter: 'worker_threads'`. Create one yourself to read its metrics, and pass it as `sandboxAdapter`:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { Enclave, WorkerPoolAdapter } from '@enclave-vm/core';

const pool = new WorkerPoolAdapter({ maxWorkers: 4, memoryLimitPerWorker: 128 * 1024 * 1024 }, 'STANDARD');
const enclave = new Enclave({ securityLevel: 'STANDARD', sandboxAdapter: pool });

console.log(pool.getMetrics());

enclave.dispose();
pool.dispose(); // An adapter you passed in is yours to dispose
```

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
new WorkerPoolAdapter(
  config?: Partial<WorkerPoolConfig>,
  securityLevel?: SecurityLevel, // Default 'STANDARD'
  doubleVmConfig?: DoubleVmConfig, // Default: the double VM
)
```

See [Worker Pool](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/worker-pool.md) for the options and for the errors an execution can end with.

### InterpreterAdapter

A tree-walking interpreter for hosts without `node:vm`:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { Enclave, InterpreterAdapter } from '@enclave-vm/core';

const enclave = new Enclave({ sandboxAdapter: new InterpreterAdapter() });
```

See [The Interpreter Adapter](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/configuration.md#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.

| Error | `name` | When |
| - | - | - |
| `InterpreterError` | `InterpreterError` | The script used something the interpreter does not allow: a blocked key, an unknown identifier, a call it refuses |
| `StepLimitError` | `StepLimitError` | The step budget (`maxSteps`) is used up |
| `DeadlineError` | `TimeoutError` | The `deadline` option (a time as `Date.now()` gives it) has passed while the script was computing. The interpreter reads the clock every few hundred steps and before each built-in or host function it calls |

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:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { ScoringGate } from '@enclave-vm/core';

const gate = new ScoringGate({ scorer: 'rule-based', blockThreshold: 70 });
await gate.initialize();

const result = await gate.evaluate(code);
console.log(result.allowed, result.totalScore, result.signals);

gate.dispose();
```

`RuleBasedScorer` scores features, not source text. `FeatureExtractor.extract(code)` produces them, and throws `FeatureExtractionError` for text it cannot parse:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { FeatureExtractor, RuleBasedScorer } from '@enclave-vm/core';

const features = new FeatureExtractor().extract(code);
const result = await new RuleBasedScorer().score(features);

console.log(result.totalScore); // 0-100
console.log(result.signals.map((signal) => signal.id)); // e.g. ['EXFIL_PATTERN', 'BULK_OPERATION']
```

## Reference Sidecar

Pass large strings between tools by reference.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { Enclave } from '@enclave-vm/core';

const enclave = new Enclave({
  sidecar: {
    enabled: true,
    extractionThreshold: 1024 * 1024, // 1MB
  },
});
```

### ReferenceSidecarOptions

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ReferenceSidecarOptions {
  enabled: boolean;
  maxTotalSize?: number; // All stored references together
  maxReferenceSize?: number; // One reference
  extractionThreshold?: number; // Size from which a string is stored
  maxResolvedSize?: number; // What one tool call resolves
  maxTotalResolvedSize?: number; // What one execution resolves; default twice maxTotalSize
  allowComposites?: boolean; // Concatenation with references
  maxReferenceCount?: number; // References in one execution
}
```

The defaults follow the security level. See [Reference Sidecar](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/reference-sidecar.md).

Two functions give the values in force:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { getReferenceConfig, getMaxTotalResolvedSize } from '@enclave-vm/core';

const config = getReferenceConfig('SECURE', { maxTotalSize: 32 * 1024 * 1024 });
getMaxTotalResolvedSize(config); // 67108864: twice maxTotalSize, because maxTotalResolvedSize is not set
```

`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?)

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
disableSandboxRejectionGuard(disabled?: boolean): void
```

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)

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
isHostPromise(promise: unknown): boolean
```

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.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { disableSandboxRejectionGuard, isHostPromise } from '@enclave-vm/core';

disableSandboxRejectionGuard();

process.on('unhandledRejection', (reason, promise) => {
  if (!isHostPromise(promise)) return; // a script's promise: not the application's, do not read the reason
  logger.error('Unhandled rejection', reason);
  process.exitCode = 1;
});
```

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

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { Enclave } from '@enclave-vm/core';

// Create enclave with full configuration
const enclave = new Enclave({
  // Security
  securityLevel: 'STRICT',

  // Limits
  timeout: 30000,
  maxToolCalls: 50,
  maxIterations: 10000,
  memoryLimit: 64 * 1024 * 1024,

  // Custom globals
  globals: {
    config: { debug: true },
  },

  // Tool handling
  toolHandler: async (name, args) => {
    console.log(`Tool: ${name}`, args);
    return { success: true };
  },

  // Console output of the script
  consoleHandler: (level, message) => console.log(`[script ${level}]`, message),

  // AI Scoring
  scoringGate: {
    scorer: 'rule-based',
    blockThreshold: 70,
    warnThreshold: 40,
  },

  // Run scripts in a pool of worker threads
  adapter: 'worker_threads',
  workerPoolConfig: {
    maxWorkers: 4,
  },
});

// Execute code
const result = await enclave.run(`
  console.log('Hello from Enclave');
  const data = await callTool('fetch', { url: '/api/data' });
  return data;
`);

console.log(result);
console.log('Score:', result.scoringResult?.totalScore);

// Clean up
enclave.dispose();
```

## Related

* [Overview](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/overview.md) - Feature overview
* [Configuration](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/configuration.md) - All options
* [Security Levels](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/security-levels.md) - Security details


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.