> ## 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** - Catches DoS attacks before parsing
* **AST validation** - Blocks dangerous constructs
* **Code transformation** - Wraps code for safe execution

### @enclave-vm/core

Runtime execution layer:

* **Sandboxed context** - Isolated JavaScript environment
* **Resource limits** - Timeout, iteration, memory limits
* **Tool routing** - Controlled external interactions

### Tools

Your application's capabilities exposed to scripts:

* **Type-safe handlers** - Validate inputs, sanitize outputs
* **Rate limiting** - Control how often tools are called
* **Audit logging** - Track all tool invocations

## Defense-in-Depth Layers

Enclave uses a 6-layer security model:

| Layer | Component           | Purpose                  |
| ----- | ------------------- | ------------------------ |
| 0     | Pre-Scanner         | Catch DoS before parsing |
| 1     | AST Validation      | Block dangerous syntax   |
| 2     | Code Transform      | Wrap in safe runtime     |
| 3     | AI Scoring Gate     | Detect attack patterns   |
| 4     | Runtime Sandbox     | Isolate execution        |
| 5     | Output Sanitization | Clean return values      |

Each layer provides independent protection. Even if one layer is bypassed, subsequent layers catch the attack.

## 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 (Process Isolation)

Code runs in separate worker threads for stronger 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:** Multi-tenant applications, untrusted code, memory isolation.

### Distributed (3-Tier with EnclaveJS)

For production applications with streaming and real-time features:

```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["useEnclave"]
        C2["Session"]
    end
    subgraph broker["Broker (Express)"]
        B1["Tool Router"]
        B2["Session Mgr"]
    end
    subgraph runtime["Runtime (Worker)"]
        R1["@enclave-vm/core"]
    end
    client -->|HTTP| broker
    broker -->|WS| runtime
    style client fill:#f0b865,stroke:#c78935,color:#333
    style broker fill:#e8a045,stroke:#c78935,color:#fff
    style runtime fill:#e8a045,stroke:#c78935,color:#fff
```

* **Client** - React hooks for real-time streaming UI
* **Broker** - HTTP API, tool registry, session management
* **Runtime** - Isolated code execution worker

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

const broker = createBroker({
  mode: 'extracted',
  runtimeUrl: 'ws://runtime:3001',
});

broker.tool('users:list', {
  handler: async () => db.users.findAll(),
});
```

**Best for:** Production SaaS, real-time UIs, horizontal scaling.

## 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/>(DoS protection)"]
    S2 --> S3["3. AST validation<br/>(blocked constructs)"]
    S3 --> S4["4. Code transformation<br/>(wrapping)"]
    S4 --> S5["5. AI scoring<br/>(optional, attack detection)"]
    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            | Worker Pool or Distributed      |
| Real-time UI with streaming  | Distributed                     |
| Edge/serverless deployment   | Distributed (Runtime as Lambda) |

## Related

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