Skip to main content

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:

Packages

@enclave-vm/types

Protocol types and Zod schemas for the streaming runtime

@enclave-vm/stream

NDJSON streaming, encryption, and reconnection handling

@enclave-vm/broker

Tool broker with session management and HTTP API

@enclave-vm/client

Browser and Node.js client SDK

@enclave-vm/react

React hooks and components

@enclave-vm/runtime

Standalone deployable runtime worker

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)

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)

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):
const broker = createBroker({ mode: 'embedded' });

Extracted Mode

The broker connects to a separate runtime worker via WebSocket (for isolation/scaling):
// 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 TypeDescription
session_initSession started with config
stdoutConsole output chunk
logLog message (debug/info/warn/error)
tool_callTool execution request
tool_result_appliedTool result acknowledgment
heartbeatKeep-alive message
finalSession completed with stats
errorExecution error