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

> API reference for the EnclaveJS React SDK

API reference for the `@enclave-vm/react` package - React hooks and components for EnclaveJS.

## Installation

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

## EnclaveProvider

Provider component for the EnclaveJS context.

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

function App() {
  return (
    <EnclaveProvider
      config={{
        baseUrl: 'https://api.example.com',
        headers: { Authorization: 'Bearer your-token' },
      }}
    >
      <YourApp />
    </EnclaveProvider>
  );
}
```

### Props

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface EnclaveProviderProps {
  // Required
  config: EnclaveClientConfig;
  children: ReactNode;

  // Optional
  client?: EnclaveClient;
}
```

| Prop | Type | Description |
| - | - | - |
| `config` | `EnclaveClientConfig` | Configuration the provider builds its client from |
| `client` | `EnclaveClient` | A client created by you. The provider then builds none, and the context reports `config` as it is |

`config` takes exactly the options of [`EnclaveClient`](https://docs.agentfront.dev/enclave/api-reference/enclavejs-client#enclaveclientconfig): `baseUrl`, `headers`, `timeout`, `autoReconnect`, `maxReconnectAttempts`, `reconnectDelay`, `maxEventLength` and `fetch`. Any other option, such as `encryption`, `auth` or `serverUrl`, throws when the provider renders.

> [!NOTE]
>
> The client does not encrypt. Requests and events travel as plain JSON over HTTP and are protected only by the transport: use an `https:` base URL, and send credentials with `headers`.

### Configuration Changes

* When a render brings a `config` with other values, such as another `baseUrl` or a renewed token in `headers`, the provider builds a new client from it. The context then exposes that client together with that configuration.
* A render with an equal `config`, such as an object literal written inline, keeps the client. `headers` are compared entry by entry, every other option by identity, so pass the same `fetch` function on every render.
* A session that was started before the change finishes on the client it was started with.

## useEnclaveSession

Main hook for code execution.

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const {
  execute,
  cancel,
  state,
  isRunning,
  sessionId,
  result,
  error,
  stdout,
  events,
  reset,
} = useEnclaveSession(options);
```

### Options

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface UseEnclaveSessionOptions {
  sessionId?: SessionId;
  timeoutMs?: number;
  maxToolCalls?: number;
  heartbeatIntervalMs?: number;
  onStart?: () => void;
  onStdout?: (chunk: string) => void;
  onLog?: (level: string, message: string, data?: Record<string, unknown>) => void;
  onToolCall?: (callId: string, toolName: string, args: unknown) => void;
  onToolResultApplied?: (callId: string) => void;
  onComplete?: (result: SessionResult) => void;
  onError?: (error: { code?: string; message: string }) => void;
}
```

| Option | Description |
| - | - |
| `sessionId` | ID used for every execution of the hook. Generated per execution if not provided |
| `timeoutMs` | Maximum session duration requested from the broker, in ms |
| `maxToolCalls` | Maximum number of tool calls requested from the broker |
| `heartbeatIntervalMs` | Heartbeat interval requested from the broker, in ms |
| `onStart` | Called when `execute` is called |
| `onStdout` | Called for stdout output |
| `onLog` | Called for log messages |
| `onToolCall` | Called when a tool is being called |
| `onToolResultApplied` | Called when a tool result is applied |
| `onComplete` | Called with the result of every execution, whether it succeeded, failed or was cancelled |
| `onError` | Called for non-fatal errors that the session reports while it runs, when the execution fails, and with the code `CANCEL_FAILED` when the broker does not confirm a cancellation |

Tools run on the broker. The hook is told about tool calls; it executes nothing and has no API to handle them.

### Return Value

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface UseEnclaveSessionReturn<T = unknown> {
  execute: (code: string) => Promise<SessionResult<T>>;
  cancel: (reason?: string) => Promise<void>;
  state: SessionState;
  isRunning: boolean;
  sessionId: SessionId | null;
  result: SessionResult<T> | null;
  error: { code?: string; message: string } | null;
  stdout: string;
  events: StreamEvent[];
  reset: () => void;
}

type SessionState = 'idle' | 'running' | 'completed' | 'error' | 'cancelled';
```

| Value | Description |
| - | - |
| `execute` | Starts an execution and resolves with its `SessionResult`, also when it fails or is cancelled |
| `cancel` | Cancels the running session: it ends in the client as cancelled, and the broker is asked to end it |
| `state` | `'idle'` before the first execution and after `reset()`, `'running'` while a session runs, then `'completed'`, `'error'` or `'cancelled'` |
| `isRunning` | `true` while `state` is `'running'` |
| `sessionId` | ID of the latest session. `null` before the first execution and after `reset()` |
| `result` | The `SessionResult` of the latest execution, once it has ended |
| `error` | Code and message, when the latest execution failed |
| `stdout` | The stdout of the execution so far |
| `events` | The events of the execution so far |
| `reset` | Puts the hook back to `'idle'` and clears its values. It does not cancel a running session |

`stdout`, `events`, `result` and `error` are cleared when the next execution starts. The hook does not cancel a running session when the component unmounts.

### Example

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

function CodeRunner() {
  const { execute, cancel, isRunning, stdout, result, error } = useEnclaveSession();

  const runCode = () => {
    execute(`
      return 42;
    `);
  };

  return (
    <div>
      <button onClick={runCode} disabled={isRunning}>
        Run
      </button>
      {isRunning && (
        <button onClick={() => cancel()}>Cancel</button>
      )}

      <pre>{stdout}</pre>

      {result?.success && <div>Result: {JSON.stringify(result.value)}</div>}
      {error && <div style={{ color: 'red' }}>{error.message}</div>}
    </div>
  );
}
```

## useEnclaveClient

Get direct access to the client instance.

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const client = useEnclaveClient();
```

### Example

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import { useState } from 'react';
import { useEnclaveClient } from '@enclave-vm/react';
import type { SessionId } from '@enclave-vm/react';

function SessionStatus({ sessionId }: { sessionId: SessionId }) {
  const client = useEnclaveClient();
  const [status, setStatus] = useState<string | null>(null);

  const refresh = async () => {
    try {
      const info = await client.getSession(sessionId);
      setStatus(info ? info.state : 'not found');
    } catch {
      setStatus('unavailable');
    }
  };

  return (
    <div>
      <button onClick={refresh}>Refresh</button>
      Status: {status}
    </div>
  );
}
```

## useEnclaveContext

Get the context value: the client, and the configuration it was built from.

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const { client, config } = useEnclaveContext();
```

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
interface EnclaveContextValue {
  client: EnclaveClient;
  config: EnclaveClientConfig;
}
```

`useEnclaveContext`, `useEnclaveClient` and `useEnclaveSession` throw when they are used outside an `EnclaveProvider`.

## Complete Example

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

interface ToolCall {
  callId: string;
  toolName: string;
  args: unknown;
}

function CodePlayground() {
  const [code, setCode] = useState(`
    const users = await callTool('users:list', { limit: 5 });
    return users;
  `);
  const [toolCalls, setToolCalls] = useState<ToolCall[]>([]);

  const { execute, cancel, state, isRunning, stdout, result, error } = useEnclaveSession({
    onStart: () => setToolCalls([]),
    onToolCall: (callId, toolName, args) => {
      setToolCalls((prev) => [...prev, { callId, toolName, args }]);
    },
  });

  return (
    <div style={{ padding: '20px' }}>
      <h1>Code Playground</h1>

      {/* Code Editor */}
      <textarea
        value={code}
        onChange={(e) => setCode(e.target.value)}
        style={{ width: '100%', height: '150px', fontFamily: 'monospace' }}
        disabled={isRunning}
      />

      {/* Actions */}
      <div style={{ margin: '10px 0' }}>
        <button onClick={() => execute(code)} disabled={isRunning}>
          {isRunning ? 'Running...' : 'Execute'}
        </button>
        {isRunning && (
          <button onClick={() => cancel()} style={{ marginLeft: '10px' }}>
            Cancel
          </button>
        )}
      </div>

      {/* Status */}
      <div>Status: {state}</div>
      {error && <div style={{ color: 'red' }}>{error.message}</div>}

      {/* Output */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '20px' }}>
        <div>
          <h3>Stdout</h3>
          <pre>{stdout}</pre>
        </div>

        <div>
          <h3>Tool Calls</h3>
          <ul>
            {toolCalls.map((call) => (
              <li key={call.callId}>
                {call.toolName}: {JSON.stringify(call.args)}
              </li>
            ))}
          </ul>
        </div>
      </div>

      {/* Result */}
      {result?.success && (
        <div style={{ marginTop: '20px' }}>
          <h3>Result</h3>
          <pre style={{ background: '#f5f5f5', padding: '10px' }}>
            {JSON.stringify(result.value, null, 2)}
          </pre>
        </div>
      )}
    </div>
  );
}

// App with provider
function App() {
  return (
    <EnclaveProvider config={{ baseUrl: 'https://api.example.com' }}>
      <CodePlayground />
    </EnclaveProvider>
  );
}

export default App;
```

## TypeScript

All hooks and components are fully typed.

```tsx theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
import type {
  SessionState,
  UseEnclaveSessionOptions,
  UseEnclaveSessionReturn,
  EnclaveProviderProps,
  EnclaveContextValue,
} from '@enclave-vm/react';

// Re-exported from @enclave-vm/client
import type {
  EnclaveClient,
  EnclaveClientConfig,
  SessionResult,
  SessionHandle,
  StreamEvent,
  SessionId,
} from '@enclave-vm/react';

// Types are exported for use
const handleResult = (result: UseEnclaveSessionReturn['result']) => {
  console.log(result?.value);
};
```

`EnclaveClient` is exported from `@enclave-vm/react` as a type. To create a client, import the class from `@enclave-vm/client`.

## Related

* [React Code Editor Guide](https://docs.agentfront.dev/enclave/guides/react-code-editor.md) - Full implementation
* [@enclave-vm/client](https://docs.agentfront.dev/enclave/api-reference/enclavejs-client.md) - Client SDK
* [Streaming UI Example](https://docs.agentfront.dev/enclave/examples/streaming-ui.md) - Example code


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