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

# Architecture

> System overview and deployment architectures for Enclave

Enclave provides a layered security architecture for executing untrusted JavaScript code. This page explains the system components and how they work together.

## Core Components

```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 app["Your Application"]
        A["@enclave-vm/ast<br/>• Validate<br/>• Pre-scan"] --> B["@enclave-vm/core<br/>• Transform<br/>• Sandbox"]
        B --> C["Tools<br/>• Execute<br/>• Return"]
    end
    style A fill:#e8a045,stroke:#c78935,color:#fff
    style B fill:#e8a045,stroke:#c78935,color:#fff
    style C fill:#f0b865,stroke:#c78935,color:#333
```

### @enclave-vm/ast

Static analysis and validation layer:

* **Pre-scanner** - Checks size, nesting and literals before parsing
* **AST validation** - Blocks dangerous constructs
* **Code transformation** - Wraps code for safe execution

### @enclave-vm/core

Runtime execution layer:

* **Sandboxed context** - A realm that holds only the allowed globals, behind a membrane
* **Resource limits** - Timeout, iteration and tool-call limits, and memory accounting. In process the timeout and the memory limit are the enclave's own accounting; the worker pool adds the engine's heap limit and a hard stop
* **Tool routing** - Controlled external interactions

### Tools

Your application's capabilities exposed to scripts:

* **Your handlers** - Validate inputs and decide what a script may do; this is your code
* **Call limits** - `maxToolCalls` and the operation rate limit of the double VM bound how often tools are called
* **Audit logging** - Every tool call passes through your `toolHandler`, where you can log it

## Defense-in-Depth Layers

Enclave uses a 6-layer security model:

| Layer | Component | Purpose |
| - | - | - |
| 0 | Pre-Scanner | Bound the input before parsing |
| 1 | AST Validation | Block dangerous syntax |
| 2 | Code Transform | Wrap in safe runtime |
| 3 | AI Scoring Gate | Optional heuristic risk score |
| 4 | Runtime Sandbox | Isolate execution |
| 5 | Output Sanitization | Clean return values |

The layers are built to hold independently of each other: the runtime does not rely on the validator having refused a script. What the sandbox does not deliver is listed in the [Security Model](https://docs.agentfront.dev/enclave/concepts/security-model.md#what-enclave-does-not-protect-against).

## Deployment Architectures

### Single Process (Embedded)

Simplest deployment - everything runs in one process:

```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 TB
    subgraph app["Your Application"]
        subgraph enclave["@enclave-vm/core"]
            VM["vm context"]
        end
    end
    style app fill:#fff5e6,stroke:#c78935,color:#333
    style enclave fill:#f0b865,stroke:#c78935,color:#333
    style VM fill:#e8a045,stroke:#c78935,color:#fff
```

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

const enclave = new Enclave({
  toolHandler: async (name, args) => executeLocalTool(name, args),
});
```

**Best for:** Internal tools, low traffic, simplicity.

### Worker Pool (Worker Threads)

Code runs in the same sandbox, inside worker threads. A worker adds a heap limit that the engine enforces and a stop that does not depend on the script. A worker thread shares the process with your application: it is not process isolation.

```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 TB
    subgraph app["Your Application"]
        subgraph pool["Worker Pool"]
            subgraph w1["Worker"]
                VM1["vm"]
            end
            subgraph w2["Worker"]
                VM2["vm"]
            end
            subgraph w3["..."]
                VM3["vm"]
            end
        end
    end
    style app fill:#fff5e6,stroke:#c78935,color:#333
    style pool fill:#f0b865,stroke:#c78935,color:#333
    style w1 fill:#e8a045,stroke:#c78935,color:#fff
    style w2 fill:#e8a045,stroke:#c78935,color:#fff
    style w3 fill:#e8a045,stroke:#c78935,color:#fff
    style VM1 fill:#c78935,stroke:#c78935,color:#fff
    style VM2 fill:#c78935,stroke:#c78935,color:#fff
    style VM3 fill:#c78935,stroke:#c78935,color:#fff
```

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

const enclave = new Enclave({
  adapter: 'worker_threads',
  workerPoolConfig: {
    minWorkers: 2,
    maxWorkers: 8,
    memoryLimitPerWorker: 256 * 1024 * 1024,
  },
});
```

**Best for:** Untrusted code that must be stoppable, and a heap limit per worker as a backstop. For tenants that must not share a process, or a host that must survive whatever a script allocates, run one enclave per process or container.

### Client and Broker (EnclaveJS)

For applications with a browser client and streamed events:

```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 client["Client (React)"]
        C1["useEnclaveSession"]
        C2["EnclaveClient"]
    end
    subgraph broker["Broker (Express)"]
        B1["Tool Registry"]
        B2["Session Manager"]
        B3["Sandbox (@enclave-vm/core)"]
    end
    client -->|"HTTP (NDJSON)"| broker
    style client fill:#f0b865,stroke:#c78935,color:#333
    style broker fill:#e8a045,stroke:#c78935,color:#fff
```

* **Client** - `@enclave-vm/client` and the React hooks of `@enclave-vm/react`: send a script, follow the events
* **Broker** - `@enclave-vm/broker`: HTTP routes, tool registry, session management, and the sandbox, in one process

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Broker
import express from 'express';
import { createBroker, createSessionHandler, registerExpressRoutes } from '@enclave-vm/broker';
import type { SessionId } from '@enclave-vm/types';
import { z } from 'zod';

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

broker.tool('users:list', {
  description: 'List users',
  argsSchema: z.object({ limit: z.number().optional() }),
  handler: async ({ limit }, context) => {
    // A handler is not handed the caller. It gets the id of its session, and the session
    // holds the caller that `identify` (below) returned for the request that created it.
    const caller = broker.getSession(context.sessionId as SessionId)?.owner;
    if (!caller) throw new Error('This session has no caller');
    return db.users.findAll({ visibleTo: caller, limit });
  },
});

const app = express();
app.use(express.json());
app.use(authenticate); // your authentication: the broker has none
registerExpressRoutes(
  app,
  createSessionHandler({
    broker,
    identify: (request) => (request.raw as { user?: { id: string } }).user?.id,
  }),
);
```

The broker does not authenticate callers, limit request rates or encrypt sessions, and the client does not encrypt either: use HTTPS, put your authentication in front of the routes, and give the routes an `identify` hook so that a session belongs to the caller that created it.

The hook separates sessions, not data. Every caller that may create a session can run a script that calls any registered tool, and a tool handler receives the arguments and a context (`sessionId`, `callId`, `secrets`, `signal`), not the caller. A tool that reads data restricted per caller has to apply that restriction itself, as `users:list` does above with the owner of its session, or the data store has to enforce it. A session created in process has no owner unless it is created with `owner`.

A third tier, in which the broker hands execution to a separate runtime worker, is not implemented: the broker has no option for it, and `@enclave-vm/runtime` does not execute scripts yet. To scale out, run several brokers (a session lives in the broker that created it, so a reconnect has to reach the same one).

**Best for:** Real-time UIs with tool calls on the server.

## Data Flow

### Request Flow

```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 TD
    S1["1. Code submitted"] --> S2["2. Pre-scanner checks<br/>(size, nesting)"]
    S2 --> S3["3. Code transformation<br/>(wrapping)"]
    S3 --> S4["4. AST validation<br/>(blocked constructs)"]
    S4 --> S5["5. AI scoring<br/>(optional, heuristic)"]
    S5 --> S6["6. Sandbox execution"]
    S6 --> S7["7. Tool calls routed<br/>to handlers"]
    S7 --> S8["8. Output sanitization"]
    S8 --> S9["9. Result returned"]
    style S1 fill:#f0b865,stroke:#c78935,color:#333
    style S2 fill:#e8a045,stroke:#c78935,color:#fff
    style S3 fill:#e8a045,stroke:#c78935,color:#fff
    style S4 fill:#e8a045,stroke:#c78935,color:#fff
    style S5 fill:#f0b865,stroke:#c78935,color:#333
    style S6 fill:#e8a045,stroke:#c78935,color:#fff
    style S7 fill:#e8a045,stroke:#c78935,color:#fff
    style S8 fill:#e8a045,stroke:#c78935,color:#fff
    style S9 fill:#f0b865,stroke:#c78935,color:#333
```

### Tool Call Flow

```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 TD
    T1["Script: callTool('users:list', { limit: 10 })"] --> T2["Sandbox: intercept and validate"]
    T2 --> T3["Double VM: pattern detection (optional)"]
    T3 --> T4["Host: toolHandler invoked"]
    T4 --> T5["Your Code: execute and return"]
    T5 --> T6["Sandbox: sanitize response"]
    T6 --> T7["Script: receives result"]
    style T1 fill:#f0b865,stroke:#c78935,color:#333
    style T2 fill:#e8a045,stroke:#c78935,color:#fff
    style T3 fill:#e8a045,stroke:#c78935,color:#fff
    style T4 fill:#e8a045,stroke:#c78935,color:#fff
    style T5 fill:#f0b865,stroke:#c78935,color:#333
    style T6 fill:#e8a045,stroke:#c78935,color:#fff
    style T7 fill:#f0b865,stroke:#c78935,color:#333
```

## When to Use Each Architecture

| Scenario | Recommended Architecture |
| - | - |
| Prototyping | Single Process |
| Internal tools | Single Process |
| User scripts (single tenant) | Worker Pool |
| Multi-tenant SaaS | One enclave (or broker) per process or container for tenants that must not share a process |
| Real-time UI with streaming | Client and Broker |

## Related

* [Security Model](https://docs.agentfront.dev/enclave/concepts/security-model.md) - 6-layer defense explained
* [AgentScript](https://docs.agentfront.dev/enclave/concepts/agentscript.md) - Language subset definition
* [enclave-vm](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/overview.md) - Core library documentation
* [EnclaveJS](https://docs.agentfront.dev/enclave/enclavejs/overview.md) - Streaming runtime


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