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

# EnclaveJS Streaming Runtime

> Real-time streaming execution environment for AI agents with tool orchestration

# EnclaveJS Streaming Runtime

EnclaveJS is a streaming runtime layer built on top of `@enclave-vm/core` that enables real-time code execution with tool orchestration, session management, and client SDKs for browser and React applications.

## Architecture

EnclaveJS provides a distributed architecture for executing AI-generated code with streaming results:

```mermaid theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#e8a045', 'primaryTextColor': '#fff', 'primaryBorderColor': '#c78935', 'lineColor': '#c78935', 'secondaryColor': '#f0b865', 'tertiaryColor': '#fff5e6'}}}%%
flowchart LR
    subgraph react["React App<br/>(@enclave-vm/react)"]
        R1["useEnclaveSession"]
        R2["EnclaveProvider"]
    end
    subgraph broker["Broker<br/>(@enclave-vm/broker)"]
        B1["Tool Registry"]
        B2["Session Manager"]
    end
    subgraph runtime["Runtime<br/>(@enclave-vm/runtime)"]
        RT1["@enclave-vm/core"]
        RT2["Sandboxed Code"]
    end
    react -->|HTTP| broker
    broker -->|WS| runtime
    style react fill:#f0b865,stroke:#c78935,color:#333
    style broker fill:#e8a045,stroke:#c78935,color:#fff
    style runtime fill:#e8a045,stroke:#c78935,color:#fff
```

## Packages

<CardGroup cols={2}>
  <Card title="@enclave-vm/types" icon="code" href="/enclave/enclavejs/types">
    Protocol types and Zod schemas for the streaming runtime
  </Card>

  <Card title="@enclave-vm/stream" icon="wave-pulse" href="/enclave/enclavejs/stream">
    NDJSON streaming, encryption, and reconnection handling
  </Card>

  <Card title="@enclave-vm/broker" icon="server" href="/enclave/enclavejs/broker">
    Tool broker with session management and HTTP API
  </Card>

  <Card title="@enclave-vm/client" icon="plug" href="/enclave/enclavejs/client">
    Browser and Node.js client SDK
  </Card>

  <Card title="@enclave-vm/react" icon="react" href="/enclave/enclavejs/react">
    React hooks and components
  </Card>

  <Card title="@enclave-vm/runtime" icon="microchip" href="/enclave/enclavejs/runtime">
    Standalone deployable runtime worker
  </Card>
</CardGroup>

## Key Features

* **Real-time Streaming**: NDJSON-based protocol for streaming stdout, logs, and tool calls
* **Tool Orchestration**: Define tools with Zod schemas, handle tool calls during execution
* **Session Management**: Track execution sessions with limits, stats, and lifecycle management
* **End-to-end Encryption**: Optional ECDH + AES-256-GCM encryption for sensitive workloads
* **Automatic Reconnection**: Built-in reconnection with sequence tracking and event buffering
* **React Integration**: First-class React hooks for building interactive code execution UIs

## Quick Start

### Server Setup (Broker)

```typescript theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { Broker, createBroker } from '@enclave-vm/broker';
import { z } from 'zod';

const broker = createBroker({
  securityLevel: 'SECURE',
});

// Register a tool
broker.tool('getCurrentTime', {
  description: 'Get the current time',
  argsSchema: z.object({
    timezone: z.string().optional(),
  }),
  handler: async ({ timezone }) => {
    return new Date().toLocaleString('en-US', { timeZone: timezone });
  },
});

// Execute code with streaming
const stream = broker.execute(`
  const time = await tools.getCurrentTime({ timezone: 'America/New_York' });
  console.log('Current time:', time);
  return time;
`);

for await (const event of stream) {
  console.log(event.type, event.payload);
}
```

### Client Setup (React)

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { EnclaveProvider, useEnclaveSession } from '@enclave-vm/react';

function App() {
  return (
    <EnclaveProvider brokerUrl="http://localhost:3000">
      <CodeExecutor />
    </EnclaveProvider>
  );
}

function CodeExecutor() {
  const { execute, state, stdout, result, error } = useEnclaveSession();

  const runCode = async () => {
    await execute(`
      console.log('Hello from the sandbox!');
      return 42;
    `);
  };

  return (
    <div>
      <button onClick={runCode} disabled={state === 'running'}>
        {state === 'running' ? 'Running...' : 'Run Code'}
      </button>
      <pre>{stdout}</pre>
      {result && <div>Result: {JSON.stringify(result)}</div>}
      {error && <div>Error: {error.message}</div>}
    </div>
  );
}
```

## Deployment Modes

### Embedded Mode

The broker runs the sandbox directly (simplest setup):

```typescript theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const broker = createBroker({ mode: 'embedded' });
```

### Extracted Mode

The broker connects to a separate runtime worker via WebSocket (for isolation/scaling):

```typescript theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Broker
const broker = createBroker({
  mode: 'extracted',
  runtimeUrl: 'ws://localhost:3001',
});

// Runtime Worker
import { createRuntimeWorker } from '@enclave-vm/runtime';

const worker = createRuntimeWorker({ port: 3001 });
await worker.start();
```

## Stream Events

The streaming protocol emits these event types:

| Event Type            | Description                         |
| --------------------- | ----------------------------------- |
| `session_init`        | Session started with config         |
| `stdout`              | Console output chunk                |
| `log`                 | Log message (debug/info/warn/error) |
| `tool_call`           | Tool execution request              |
| `tool_result_applied` | Tool result acknowledgment          |
| `heartbeat`           | Keep-alive message                  |
| `final`               | Session completed with stats        |
| `error`               | Execution error                     |

## Links

* [GitHub](https://github.com/agentfront/enclave)
* [npm @enclave-vm](https://www.npmjs.com/org/enclave-vm)
