> ## 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/runtime

> API reference for the EnclaveJS runtime package

API reference for the `@enclave-vm/runtime` package - building blocks of a runtime worker: session bookkeeping and the channels between a worker and a broker.

> [!WARNING]
>
> This package is not a runnable service. It does not execute code, starts no server and opens no port. It has no authentication, no TLS, no CORS, no HTTP or WebSocket endpoints, no serverless entry points, and it reads no environment variables. An `execute` request never runs code: it ends with `RuntimeNotImplementedError`. To run scripts use [@enclave-vm/broker](https://docs.agentfront.dev/enclave/api-reference/enclavejs-broker.md) (sessions, tools and streaming over HTTP) or [@enclave-vm/core](https://docs.agentfront.dev/enclave/api-reference/enclave-vm.md) (the sandbox).

## Installation

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

## Runtime Worker

A runtime worker keeps the sessions of the requests that the embedding application hands to it. It has no network interface of its own.

### createRuntimeWorker(config?)

Create a runtime worker. The class of the returned object is exported as `RuntimeWorkerImpl`.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function createRuntimeWorker(config?: RuntimeConfig): RuntimeWorkerImpl
```

**Example:**

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { createRuntimeWorker, createMemoryChannel, RuntimeNotImplementedError } from '@enclave-vm/runtime';

const worker = createRuntimeWorker({ maxSessions: 10 });
await worker.start(); // marks the worker as running; nothing is listening

const channel = createMemoryChannel();

try {
  await worker.handleRequest({ type: 'execute', sessionId: 's_123', code: 'return 1 + 1' }, channel);
} catch (error) {
  if (error instanceof RuntimeNotImplementedError) {
    console.log(error.code); // 'NOT_IMPLEMENTED'
  }
}

console.log(channel.getEvents().map((event) => event.type)); // ['session_init', 'final']
console.log(worker.getSessions()); // []

await worker.stop();
```

### RuntimeConfig

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface RuntimeConfig {
  maxSessions?: number;
  debug?: boolean;
  defaultLimits?: Partial<SessionLimits>;
  heartbeatIntervalMs?: number;
  connectionTimeoutMs?: number;
  port?: number;
  host?: string;
  wsPath?: string;
}
```

| Property | Type | Default | Description |
| - | - | - | - |
| `maxSessions` | `number` | `10` | Maximum number of sessions the worker holds. A value that is not a positive integer throws a `RangeError` |
| `debug` | `boolean` | `false` | Log to the console |
| `defaultLimits` | `Partial<SessionLimits>` | `{}` | Accepted, not read by the worker |
| `heartbeatIntervalMs` | `number` | `15000` | Accepted, not read by the worker |
| `connectionTimeoutMs` | `number` | `30000` | Accepted, not read by the worker |
| `port` | `number` | `3001` | Not used: no server is started |
| `host` | `string` | `'127.0.0.1'` | Not used: no server is started |
| `wsPath` | `string` | `'/ws'` | Not used: no server is started |

### RuntimeWorkerImpl

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
class RuntimeWorkerImpl {
  constructor(config?: RuntimeConfig);

  readonly isRunning: boolean;

  start(): Promise<void>;
  stop(): Promise<void>;
  getStats(): RuntimeStats;
  getSessions(): RuntimeSession[];
  handleRequest(request: RuntimeRequest, channel: RuntimeChannel): Promise<void>;
}
```

#### start()

Mark the worker as running, so that `handleRequest()` accepts `execute` requests. No server is started and no port is opened. Throws when the worker is neither idle nor stopped.

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

#### stop()

Cancel and remove the sessions the worker holds.

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

#### getStats()

Get the worker's statistics.

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

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface RuntimeStats {
  state: RuntimeState;
  activeSessions: number;
  totalSessions: number;
  startedAt: number;
  uptimeMs: number;
  memoryUsage: {
    heapUsed: number;
    heapTotal: number;
    rss: number;
  };
}

type RuntimeState = 'idle' | 'starting' | 'running' | 'stopping' | 'stopped';
```

#### getSessions()

Get the sessions the worker holds.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
getSessions(): RuntimeSession[]
```

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface RuntimeSession {
  sessionId: SessionId;
  state: string;
  createdAt: number;
  expiresAt: number;
}
```

#### handleRequest(request, channel)

Handle one request from the embedding application. The caller is trusted: nothing authenticates a request or checks where it came from.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
async handleRequest(request: RuntimeRequest, channel: RuntimeChannel): Promise<void>
```

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
type RuntimeRequest = ExecuteRequest | CancelRequest | ToolResultRequest | PingRequest;

interface ExecuteRequest {
  type: 'execute';
  sessionId: SessionId;
  code: string;
  limits?: Partial<SessionLimits>;
}

interface CancelRequest {
  type: 'cancel';
  sessionId: SessionId;
  reason?: string;
}

interface ToolResultRequest {
  type: 'tool_result';
  sessionId: SessionId;
  callId: string;
  success: boolean;
  value?: unknown;
  error?: { code?: string; message: string };
}

interface PingRequest {
  type: 'ping';
  timestamp: number;
}
```

| Request | What happens |
| - | - |
| `execute` | The code is never run. A valid request rejects with `RuntimeNotImplementedError`: the channel receives `session_init`, then a `final` event with `ok: false` and `error.code: 'NOT_IMPLEMENTED'`, and the session is removed again. A request to a worker that is not running, or without a string `code`, rejects with another error |
| `cancel` | Cancels the session with that id if the worker holds it. Otherwise the request is ignored |
| `tool_result` | Passes the result to the session with that id if the worker holds it. Otherwise the request is ignored |
| `ping` | Accepted. Nothing is sent back |

## Session Executor

### SessionExecutor

Holds one session and forwards its events to a channel. It keeps the session's code and never runs it.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
class SessionExecutor {
  constructor(options: SessionExecutorOptions);

  readonly sessionId: SessionId;
  readonly state: string;
  readonly isTerminal: boolean;

  getInfo(): RuntimeSession;
  execute(): Promise<void>;
  submitToolResult(
    callId: CallId,
    success: boolean,
    value?: unknown,
    error?: { code?: string; message: string }
  ): Promise<void>;
  cancel(reason?: string): Promise<void>;
  dispose(): void;
}

interface SessionExecutorOptions {
  sessionId?: SessionId;
  code: string;
  limits?: Partial<SessionLimits>;
  channel: RuntimeChannel;
  debug?: boolean;
}
```

`execute()` always rejects with `RuntimeNotImplementedError`. The first call ends the session: the channel receives `session_init`, then a `final` event with `ok: false` and `error.code: 'NOT_IMPLEMENTED'`. `dispose()` stops forwarding events to the channel.

### createSessionExecutor(options)

Create a session executor.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function createSessionExecutor(options: SessionExecutorOptions): SessionExecutor
```

### RuntimeNotImplementedError

Thrown by the operations of this package that are not implemented.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
class RuntimeNotImplementedError extends Error {
  readonly code: 'NOT_IMPLEMENTED';
  constructor(operation: string);
}
```

## Channels

### RuntimeChannel

The interface between a worker and the other end of a session.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface RuntimeChannel {
  send(event: StreamEvent): void;
  onMessage(handler: (message: RuntimeChannelMessage) => void): () => void;
  close(): void;
  readonly isOpen: boolean;
}
```

### MemoryChannel

In-process channel that keeps the events sent to it.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
class MemoryChannel implements RuntimeChannel {
  readonly isOpen: boolean;

  send(event: StreamEvent): void;
  getEvents(): StreamEvent[];
  clearEvents(): void;
  onMessage(handler: (message: RuntimeChannelMessage) => void): () => void;
  injectMessage(message: RuntimeChannelMessage): void;
  close(): void;
}

function createMemoryChannel(): MemoryChannel
```

`send()` and `injectMessage()` throw when the channel is closed.

### createMemoryChannelPair()

Create two connected memory channels: what one sends, the message handlers of the other receive.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
function createMemoryChannelPair(): {
  client: MemoryChannel;
  server: MemoryChannel;
}
```

### WebSocketChannel

The client side of a WebSocket connection. It connects to a URL and nothing more: there is no WebSocket server in this package.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
class WebSocketChannel implements RuntimeChannel {
  constructor(config: WebSocketChannelConfig);

  readonly isOpen: boolean;
  readonly channelState: WebSocketChannelState;

  connect(): Promise<void>;
  send(event: StreamEvent): void;
  onMessage(handler: (message: RuntimeChannelMessage) => void): () => void;
  close(): void;
}

function createWebSocketChannel(config: WebSocketChannelConfig): WebSocketChannel

interface WebSocketChannelConfig {
  url: string;
  reconnect?: {
    enabled?: boolean;
    maxRetries?: number;
    initialDelayMs?: number;
    maxDelayMs?: number;
  };
  connectionTimeoutMs?: number;
  maxBufferedMessages?: number;
  debug?: boolean;
}

type WebSocketChannelState = 'connecting' | 'connected' | 'disconnected' | 'reconnecting' | 'closed';
```

| Property | Type | Default | Description |
| - | - | - | - |
| `url` | `string` | Required | WebSocket URL to connect to |
| `reconnect.enabled` | `boolean` | `true` | Reconnect after the connection is lost |
| `reconnect.maxRetries` | `number` | `5` | Reconnection attempts before the channel closes |
| `reconnect.initialDelayMs` | `number` | `1000` | Delay before the first attempt; doubled for each further attempt |
| `reconnect.maxDelayMs` | `number` | `30000` | Maximum delay between attempts |
| `connectionTimeoutMs` | `number` | `10000` | Time allowed for a connection to open |
| `maxBufferedMessages` | `number` | `1000` | Events kept while the channel is not connected. A value that is not a positive integer throws a `RangeError` |
| `debug` | `boolean` | `false` | Log to the console |

* The channel sends no credentials. Authenticate the connection in the server behind the URL.
* Incoming messages are parsed as JSON and handed to the handlers without validation against a schema. Validate them in the handler.
* While the channel is not connected, `send()` keeps at most `maxBufferedMessages` events and drops the rest. The kept events are sent when the channel connects.
* Where there is no global `WebSocket`, the channel needs the `ws` package, which is not installed with this package.

**Example:**

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

const channel = createWebSocketChannel({
  url: 'wss://worker.example.com/ws',
  maxBufferedMessages: 100,
});

channel.onMessage((message) => {
  // Validate the message before using it
});

await channel.connect();
```

## Command Line

The package installs an `enclave-runtime` program. It does not start a worker: it checks its arguments, prints that a standalone worker is not implemented, and exits with code 1.

```bash theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
npx enclave-runtime --help
```

| Option | Description |
| - | - |
| `--port <port>` | Checked (a whole number), not used |
| `--host <host>` | Checked, not used |
| `--max-sessions <n>` | Checked (a whole number of 1 or more), not used |
| `--debug` | Not used |
| `--help`, `-h` | Print the help and exit with code 0 |

An unknown option or an invalid value prints a message and exits with code 1.

## Other Types

`RuntimeWorker` is the interface of a worker without `handleRequest()`. `WebSocketServer` and `ConnectionHandler` are exported as types only: the package has no implementation of them.

## Related

* [Runtime Overview](https://docs.agentfront.dev/enclave/enclavejs/runtime.md) - What the package contains
* [@enclave-vm/broker](https://docs.agentfront.dev/enclave/api-reference/enclavejs-broker.md) - Broker API
* [@enclave-vm/core](https://docs.agentfront.dev/enclave/api-reference/enclave-vm.md) - Sandbox API


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