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

Installation

npm install @enclave-vm/core

Enclave Class

The main class for secure code execution.

Constructor

new Enclave(options?: EnclaveOptions)

EnclaveOptions

PropertyTypeDefaultDescription
securityLevelSecurityLevel'STANDARD'Security preset
timeoutnumber30000Execution timeout in ms
maxToolCallsnumber100Maximum tool calls per execution
maxIterationsnumber10000Maximum loop iterations
memoryLimitnumber67108864Memory limit in bytes (64MB)
toolHandlerToolHandlerundefinedTool execution function
globalsRecord<string, unknown>{}Custom globals
scoringGateScoringGateOptionsundefinedAI scoring configuration
adapterEnclaveAdapterundefinedExecution adapter
verboseErrorsbooleanfalseInclude detailed error info

Methods

run(code, options?)

Execute code in the sandbox.
async run(code: string, options?: RunOptions): Promise<ExecutionResult>
Parameters:
  • code - JavaScript code to execute
  • options - Optional execution options
Returns: ExecutionResult
interface RunOptions {
  timeout?: number;
  context?: Record<string, unknown>;
  maxToolCalls?: number;
}

interface ExecutionResult {
  success: boolean;
  value?: unknown;
  error?: ExecutionError;
  stdout?: string;
  stats?: ExecutionStats;
}
Example:
const result = await enclave.run(`
  const x = 1 + 2;
  return x;
`);
console.log(result.value); // 3

validate(code)

Validate code without executing.
async validate(code: string): Promise<ValidationResult>
Returns: ValidationResult
interface ValidationResult {
  valid: boolean;
  issues: ValidationIssue[];
}

interface ValidationIssue {
  rule: string;
  message: string;
  severity: 'error' | 'warning';
  location?: {
    line: number;
    column: number;
  };
}
Example:
const validation = await enclave.validate(`
  eval('dangerous');
`);
// validation.valid === false
// validation.issues[0].message === "Identifier 'eval' is not allowed"

dispose()

Clean up resources.
dispose(): void
Example:
const enclave = new Enclave();
try {
  await enclave.run(code);
} finally {
  enclave.dispose();
}

Types

SecurityLevel

type SecurityLevel = 'STRICT' | 'SECURE' | 'STANDARD' | 'PERMISSIVE';
LevelDescription
STRICTMaximum security for untrusted code
SECUREHigh security for semi-trusted code
STANDARDBalanced security for internal tools
PERMISSIVEMinimal restrictions (testing only)

ToolHandler

type ToolHandler = (
  name: string,
  args: Record<string, unknown>,
  context?: Record<string, unknown>
) => Promise<unknown>;
Example:
const toolHandler: ToolHandler = async (name, args, context) => {
  switch (name) {
    case 'users:list':
      return db.users.findAll({ limit: args.limit });
    default:
      throw new Error(`Unknown tool: ${name}`);
  }
};

ExecutionError

interface ExecutionError {
  code: ErrorCode;
  name: string;
  message: string;
  stack?: string;
  data?: Record<string, unknown>;
}

type ErrorCode =
  | 'VALIDATION_ERROR'
  | 'TIMEOUT'
  | 'MAX_TOOL_CALLS'
  | 'MAX_ITERATIONS'
  | 'TOOL_ERROR'
  | 'MEMORY_LIMIT_EXCEEDED'
  | 'SCORING_BLOCKED'
  | 'RUNTIME_ERROR';

ExecutionStats

interface ExecutionStats {
  duration: number;
  toolCallCount: number;
  iterationCount: number;
  memoryUsage?: number;
}

ScoringGateOptions

interface ScoringGateOptions {
  scorer: 'rule-based' | 'custom';
  blockThreshold: number;
  warnThreshold?: number;
  onScore?: (result: ScoringResult) => void;
  customScorer?: (code: string) => Promise<ScoringResult>;
}

interface ScoringResult {
  score: number;
  signals: string[];
}

Factory Functions

createWorkerPoolAdapter(options)

Create a worker pool adapter for OS-level isolation.
function createWorkerPoolAdapter(options: WorkerPoolOptions): EnclaveAdapter
Options:
interface WorkerPoolOptions {
  poolSize: number;
  maxWorkerMemory?: number;
  maxExecutionsPerWorker?: number;
  idleTimeout?: number;
}
Example:
import { Enclave, createWorkerPoolAdapter } from '@enclave-vm/core';

const enclave = new Enclave({
  adapter: createWorkerPoolAdapter({
    poolSize: 4,
    maxWorkerMemory: 128 * 1024 * 1024,
  }),
});

createDoubleVmAdapter(options)

Create a double-VM adapter for nested isolation.
function createDoubleVmAdapter(options?: DoubleVmOptions): EnclaveAdapter
Options:
interface DoubleVmOptions {
  outerTimeout?: number;
  innerTimeout?: number;
}

RuleBasedScorer Class

Semantic pattern detection scorer.
import { RuleBasedScorer } from '@enclave-vm/core';

const scorer = new RuleBasedScorer();
const result = scorer.score(code);

console.log(result.score);   // 0-100
console.log(result.signals); // ['list-send-pattern', 'bulk-operation']

Methods

score(code)

score(code: string): ScoringResult

Reference Sidecar

Handle large tool responses.
import { Enclave } from '@enclave-vm/core';

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

SidecarOptions

interface SidecarOptions {
  enabled: boolean;
  threshold?: number; // Size threshold for reference creation
  storage?: 'memory' | 'redis';
  ttl?: number; // Time-to-live in ms
}

Complete Example

import { Enclave, createWorkerPoolAdapter } 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 };
  },

  // AI Scoring
  scoringGate: {
    scorer: 'rule-based',
    blockThreshold: 70,
    warnThreshold: 40,
    onScore: (result) => {
      console.log('Score:', result.score);
    },
  },

  // Worker pool isolation
  adapter: createWorkerPoolAdapter({
    poolSize: 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);

// Clean up
enclave.dispose();