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

> Type definitions and Zod schemas for EnclaveJS

Type definitions and Zod schemas for the EnclaveJS streaming protocol. The package holds types, constants, schemas and type guards; it sends and receives nothing.

## Installation

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

## Protocol Constants and Identifiers

| Export | Value | Description |
| - | - | - |
| `PROTOCOL_VERSION` | `2` | Current protocol version |
| `PROTOCOL_VERSION_V1` | `1` | Previous version, still accepted by the schemas |
| `SESSION_ID_PREFIX` | `'s_'` | Prefix of a session id |
| `CALL_ID_PREFIX` | `'c_'` | Prefix of a tool call id |
| `REF_ID_PREFIX` | `'ref_'` | Prefix of a reference id |

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
type ProtocolVersion = 2 | 1;
type SessionId = `s_${string}`;
type CallId = `c_${string}`;
type RefId = `ref_${string}`;

function generateSessionId(): SessionId; // 's_' + a UUID
function generateCallId(): CallId;
function generateRefId(): RefId;

function isSessionId(value: string): value is SessionId; // checks the prefix
function isCallId(value: string): value is CallId;
function isRefId(value: string): value is RefId;
```

## Stream Events

### BaseEvent

Every event has these fields. There is no timestamp field.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface BaseEvent {
  protocolVersion: ProtocolVersion;
  sessionId: SessionId;
  seq: number; // Sequence number, for ordering and reconnection
}
```

### StreamEvent

Union type of all possible stream events.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
type StreamEvent =
  | SessionInitEvent
  | StdoutEvent
  | LogEvent
  | ToolCallEvent
  | ToolResultAppliedEvent
  | FinalEvent
  | HeartbeatEvent
  | ErrorEvent
  | PartialResultEvent
  | ToolProgressEvent
  | DeadlineExceededEvent
  | CatalogChangedEvent;
```

`EventType` holds the `type` values: `SessionInit` (`'session_init'`), `Stdout`, `Log`, `ToolCall` (`'tool_call'`), `ToolResultApplied` (`'tool_result_applied'`), `Final`, `Heartbeat`, `Error`, `PartialResult` (`'partial_result'`), `ToolProgress` (`'tool_progress'`), `DeadlineExceeded` (`'deadline_exceeded'`), `CatalogChanged` (`'catalog_changed'`) and `Encrypted` (`'enc'`).

### SessionInitEvent

Session initialization event.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface SessionInitEvent extends BaseEvent {
  type: 'session_init';
  payload: {
    cancelUrl: string;
    expiresAt: string; // ISO date
    encryption: { enabled: boolean; keyId?: string };
    replayUrl?: string;
  };
}
```

### StdoutEvent

Console output event.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface StdoutEvent extends BaseEvent {
  type: 'stdout';
  payload: {
    chunk: string;
  };
}
```

### LogEvent

Structured log event.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface LogEvent extends BaseEvent {
  type: 'log';
  payload: {
    level: 'debug' | 'info' | 'warn' | 'error';
    message: string;
    data?: Record<string, unknown>;
  };
}
```

### ToolCallEvent

Tool call event.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ToolCallEvent extends BaseEvent {
  type: 'tool_call';
  payload: {
    callId: CallId;
    toolName: string;
    args: unknown;
  };
}
```

### ToolResultAppliedEvent

Tool result confirmation event.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ToolResultAppliedEvent extends BaseEvent {
  type: 'tool_result_applied';
  payload: {
    callId: CallId;
  };
}
```

### HeartbeatEvent

Keep-alive event.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface HeartbeatEvent extends BaseEvent {
  type: 'heartbeat';
  payload: {
    ts: string; // ISO date
  };
}
```

### FinalEvent

The last event of a session.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface FinalEvent extends BaseEvent {
  type: 'final';
  payload: {
    ok: boolean;
    result?: unknown;
    error?: ErrorInfo; // { message, code?, stack? }
    errors?: ErrorPayload[];
    stats?: SessionStats;
  };
}

interface SessionStats {
  durationMs: number;
  toolCallCount: number;
  stdoutBytes: number;
}
```

### ErrorEvent

An error during a session that does not end it.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ErrorEvent extends BaseEvent {
  type: 'error';
  payload: {
    message: string;
    code?: string;
    recoverable?: boolean;
  };
}
```

### Events of protocol version 2

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface PartialResultEvent extends BaseEvent {
  type: 'partial_result';
  payload: { path: string[]; data?: unknown; error?: ErrorPayload; hasNext: boolean };
}

interface ToolProgressEvent extends BaseEvent {
  type: 'tool_progress';
  payload: {
    callId: CallId;
    phase: 'connecting' | 'sending' | 'receiving' | 'processing';
    bytesReceived?: number;
    totalBytes?: number;
    elapsedMs: number;
  };
}

interface DeadlineExceededEvent extends BaseEvent {
  type: 'deadline_exceeded';
  payload: { elapsedMs: number; budgetMs: number };
}

interface CatalogChangedEvent extends BaseEvent {
  type: 'catalog_changed';
  payload: { version: string; addedActions: string[]; removedActions: string[] };
}

interface ErrorPayload {
  code: string;
  message: string;
  path?: string[];
  details?: ErrorDetail[];
}
```

## Zod Schemas

### Event Schemas

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import {
  StreamEventSchema,
  SessionInitEventSchema,
  StdoutEventSchema,
  LogEventSchema,
  ToolCallEventSchema,
  ToolResultAppliedEventSchema,
  HeartbeatEventSchema,
  FinalEventSchema,
  ErrorEventSchema,
} from '@enclave-vm/types';
```

Each event type has a schema (`PartialResultEventSchema`, `ToolProgressEventSchema`, `DeadlineExceededEventSchema` and `CatalogChangedEventSchema` for the version 2 events), and each payload has one (`SessionInitPayloadSchema`, `FinalPayloadSchema`, ...).

### Usage

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

// Validate an event
const result = StreamEventSchema.safeParse(data);
if (result.success) {
  const event = result.data;
  // event is typed as StreamEvent
}

// The same, as a helper
const parsed = parseStreamEvent(data);

// Throws on a value that is not an event
const event = StreamEventSchema.parse(data);
```

| Helper | Validates |
| - | - |
| `parseStreamEvent(data)` | A stream event |
| `parseEncryptedEnvelope(data)` | An encrypted envelope |
| `parseStreamEventOrEncrypted(data)` | Either of the two |
| `parseRuntimeChannelMessage(data)` | A runtime channel message |
| `parseCreateSessionRequest(data)` | `CreateSessionRequestSchema`: `{ protocolVersion, code, limits?, encryption? }` |

Each returns the result of `safeParse`. The schemas describe the wire format; a component may accept less. The body the broker accepts for `POST /sessions` is described with the [broker](https://docs.agentfront.dev/enclave/enclavejs/broker.md#the-request-body-of-post-sessions).

## Session Types

### SessionLimits

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface SessionLimits {
  sessionTtlMs?: number;        // Default 60000
  maxToolCalls?: number;        // Default 50
  maxStdoutBytes?: number;      // Default 262144
  maxToolResultBytes?: number;  // Default 5242880
  toolTimeoutMs?: number;       // Default 30000
  heartbeatIntervalMs?: number; // Default 15000
  deadlineMs?: number;          // Default 0 (none)
  perToolDeadlineMs?: number;   // Default 30000
  cancelOnFirstError?: boolean; // Default false
}
```

`DEFAULT_SESSION_LIMITS` holds the defaults, and `SessionLimitsSchema` validates the type. What each limit bounds is decided by the component that applies it: see the [limits of the broker](https://docs.agentfront.dev/enclave/enclavejs/broker.md#limits).

### SessionState

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const SessionState = {
  Starting: 'starting',
  Running: 'running',
  WaitingForTool: 'waiting_for_tool',
  Completed: 'completed',
  Cancelled: 'cancelled',
  Failed: 'failed',
} as const;

type SessionState = 'starting' | 'running' | 'waiting_for_tool' | 'completed' | 'cancelled' | 'failed';
```

### ToolConfig

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ToolConfig {
  timeout?: number;          // This tool's own timeout in milliseconds
  retryable?: boolean;
  maxRetries?: number;
  runtimeReadable?: boolean;
}
```

The broker applies `timeout`. It does not retry tools and does not read `runtimeReadable`.

## Encryption Types

These are type definitions for an optional encryption layer. `@enclave-vm/client`, `@enclave-vm/react`, `@enclave-vm/broker` and `@enclave-vm/runtime` do not encrypt: sessions are plain JSON protected by the transport. `@enclave-vm/stream` exports primitives for these types; its key exchange is not authenticated, and no package uses it.

### EncryptedEnvelope

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface EncryptedEnvelope {
  protocolVersion: ProtocolVersion;
  sessionId: SessionId;
  seq: number;
  type: 'enc';
  payload: {
    kid: string;           // Key id
    nonceB64: string;
    ciphertextB64: string;
    tagB64?: string;
  };
}
```

### Key Exchange

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ClientHello {
  protocolVersion: ProtocolVersion;
  clientEphemeralPubKeyB64: string;
  curve: 'P-256';
  supportedAlgorithms: 'AES-GCM-256'[];
}

interface ServerHello {
  protocolVersion: ProtocolVersion;
  serverEphemeralPubKeyB64: string;
  curve: 'P-256';
  selectedAlgorithm: 'AES-GCM-256';
  kdf: 'HKDF-SHA-256';
  keyId: string;
  signatureB64?: string; // Reserved: nothing creates or verifies it
}

interface EncryptionRequest {
  mode: 'disabled' | 'optional' | 'required';
  clientHello?: ClientHello;
}
```

`SupportedCurve`, `EncryptionAlgorithm`, `KeyDerivation`, `EncryptionMode`, `EncryptionErrorCode` and `HkdfInfo` hold the constants, next to `AES_GCM_NONCE_SIZE` (12), `AES_GCM_TAG_SIZE` (16), `AES_256_KEY_SIZE` (32) and `MAX_MESSAGES_PER_KEY` (2^30). `isEncryptedEnvelope(value)` is the type guard.

## Filter Types

### EventFilterConfig

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface EventFilterConfig {
  mode: 'include' | 'exclude';
  rules: FilterRule[];       // A filter matches when one of its rules does
  alwaysAllow?: EventType[]; // Default: ['session_init', 'final']
  regexTimeoutMs?: number;   // Default: 100
}

interface FilterRule {
  types?: { types: EventType[] };
  content?: {
    patterns: ContentPattern[];
    match?: 'any' | 'all';   // Default: 'any'
  };
}

interface ContentPattern {
  type: 'exact' | 'prefix' | 'regex' | 'glob';
  pattern: string;
  field?: string;
  caseInsensitive?: boolean;
}
```

`FilterMode` and `PatternType` hold the constants, and `DEFAULT_ALWAYS_ALLOW` the default of `alwaysAllow`. The broker applies a filter; see [Event Filtering](https://docs.agentfront.dev/enclave/enclavejs/broker.md#event-filtering).

## Runtime Channel Messages

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface ToolResultSubmitMessage {
  protocolVersion: ProtocolVersion;
  sessionId: SessionId;
  type: 'tool_result_submit';
  payload: { callId: CallId; ok: boolean; result?: unknown; error?: ErrorInfo };
}

interface CancelMessage {
  protocolVersion: ProtocolVersion;
  sessionId: SessionId;
  type: 'cancel';
  payload: { reason?: string };
}

type RuntimeChannelMessage = ToolResultSubmitMessage | CancelMessage;
```

## Reference Tokens

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface RefToken {
  $ref: { id: RefId };
}

function isRefToken(value: unknown): value is RefToken;
function createRefToken(id: RefId): RefToken;
```

The reference sidecar of `@enclave-vm/core` does not use this type: there a reference is a string of the form `__REF_<uuid>__`.

## Type Guards

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import {
  isSessionInitEvent,
  isStdoutEvent,
  isLogEvent,
  isToolCallEvent,
  isToolResultAppliedEvent,
  isHeartbeatEvent,
  isFinalEvent,
  isErrorEvent,
  isPartialResultEvent,
  isToolProgressEvent,
  isDeadlineExceededEvent,
  isCatalogChangedEvent,
} from '@enclave-vm/types';

function handleEvent(event: StreamEvent) {
  if (isStdoutEvent(event)) {
    console.log(event.payload.chunk);
  } else if (isToolCallEvent(event)) {
    console.log('Tool:', event.payload.toolName);
  } else if (isFinalEvent(event)) {
    console.log('Result:', event.payload.result);
  }
}
```

## Related

* [@enclave-vm/types](https://docs.agentfront.dev/enclave/enclavejs/types.md) - Usage examples
* [Streaming Protocol](https://docs.agentfront.dev/enclave/concepts/streaming-protocol.md) - Protocol details
* [@enclave-vm/stream](https://docs.agentfront.dev/enclave/api-reference/enclavejs-stream.md) - Stream utilities
* [@enclave-vm/client](https://docs.agentfront.dev/enclave/api-reference/enclavejs-client.md) - Client SDK


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