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

# Security Model

> 6-layer defense-in-depth architecture for secure code execution

Enclave uses a defense-in-depth approach with 6 independent security layers. Each layer provides protection even if other layers are bypassed.

## The 6 Layers

```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
    L0["Layer 0: Pre-Scanner<br/>• Input size and line limits<br/>• Nesting depth limits<br/>• Regex literals refused or analyzed<br/>• Unicode that hides code"]
    L1["Layer 1: AST Validation<br/>• Block dangerous constructs<br/>• Enforce allowed globals<br/>• Restrict control flow"]
    L2["Layer 2: Code Transformation<br/>• Wrap in safe runtime<br/>• Proxy tool calls<br/>• Instrument loops"]
    L3["Layer 3: AI Scoring Gate (Optional)<br/>• Heuristic risk score<br/>• Exfiltration-like tool sequences<br/>• Thresholds"]
    L4["Layer 4: Runtime Sandbox<br/>• Isolated vm context<br/>• Controlled globals<br/>• Resource limits enforced"]
    L5["Layer 5: Output Sanitization<br/>• Result copied into plain data<br/>• Errors as bounded text<br/>• Result size check"]

    L0 --> L1 --> L2 --> L3 --> L4 --> L5

    style L0 fill:#e8a045,stroke:#c78935,color:#fff
    style L1 fill:#e8a045,stroke:#c78935,color:#fff
    style L2 fill:#e8a045,stroke:#c78935,color:#fff
    style L3 fill:#f0b865,stroke:#c78935,color:#333
    style L4 fill:#e8a045,stroke:#c78935,color:#fff
    style L5 fill:#e8a045,stroke:#c78935,color:#fff
```

## Layer 0: Pre-Scanner

Runs on the script as it was written, before anything parses it, so that no parser is handed input it cannot cope with. `Enclave` runs the pre-scanner with the preset named like the AST preset:

| AST preset | Pre-scanner preset | Script | Lines | String literals | Regex literals | Bidirectional controls | Invisible characters |
| - | - | - | - | - | - | - | - |
| `agentscript` (default) | `agentscript` | 100 KB, nesting 20 | 1,000 of at most 2,000 chars | 10 KB each, 100 KB in total | refused | refused | refused |
| `strict` | `strict` | 500 KB, nesting 30 | 2,000 of at most 5,000 chars | 50 KB each, 500 KB in total | 10 of at most 100 chars, analyzed for ReDoS | refused | refused |
| `secure` | `secure` | 1 MB, nesting 40 | 5,000 of at most 8,000 chars | 100 KB each, 1 MB in total | 20 of at most 200 chars, analyzed | refused | allowed |
| `standard`, `babel` | `standard` | 5 MB, nesting 50 | 10,000 of at most 10,000 chars | 500 KB each, 5 MB in total | 30 of at most 500 chars, analyzed | allowed | allowed |
| `permissive` | `permissive` | 5,242,880 chars (the enclave's maximum), nesting 100 | 100,000 of at most 50,000 chars | 1 MB each, 10 MB in total | allowed | allowed | allowed |

Every preset except `permissive` also refuses a null byte and a fixed list of look-alike letters (Cyrillic, Greek and full-width forms of letters such as `a`, `e` and `o`), anywhere in the script. The bidirectional control characters are the characters of Trojan Source (CVE-2021-42574). The `preScan` option picks another [pre-scanner preset](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/pre-scanner.md) or changes single limits; with `validate: false` the pre-scanner does not run.

A script is also limited to 5,242,880 characters, checked before anything parses it.

## Layer 1: AST Validation

Static analysis of the parsed AST to block dangerous patterns:

### Blocked Categories

| Category | Examples | Risk |
| - | - | - |
| Code execution | `eval`, `Function`, `setTimeout(string)` | Arbitrary code injection |
| System access | `process`, `require`, `import` | Host system access |
| Globals | `window`, `global`, `globalThis` | Sandbox escape |
| Prototype | `__proto__`, `constructor` | Prototype pollution |
| Metaprogramming | `Proxy`, `Reflect` | Interception |
| User functions | `function foo(){}` | Recursion bombs |

### Enforcement

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// These are blocked by AST validation:
eval('malicious');           // ❌ eval blocked
new Function('return 1')();  // ❌ Function constructor blocked
process.exit();              // ❌ process access blocked
obj.__proto__.pollute = 1;   // ❌ prototype access blocked
```

## Layer 2: Code Transformation

Valid code is transformed for safe execution:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Original code:
const users = await callTool('users:list', {});
for (const user of users) {
  console.log(user.name);
}

// Transformed code:
async function __ag_main() {
  const users = await __safe_callTool('users:list', {});
  for (const user of __safe_forOf(users)) {
    __safe_console.log(user.name);
  }
}
```

Transformations include:

* **Main wrapper** - Entry point for execution
* **Safe callTool** - Proxied through host with counting
* **Safe loops** - Iteration limits enforced
* **Safe console** - Rate-limited with output capture

## Layer 3: AI Scoring Gate

An optional heuristic: it scores a script by its tool calls (names, argument names, literal values, order, loops) and refuses it at a threshold. It flags patterns that look risky; a low score does not show that a script is safe.

| Pattern | Score | Example |
| - | - | - |
| Data exfiltration | 50 | list → send sequence |
| Sensitive field access | 35 | Query for passwords/tokens |
| Excessive limits | 25 | `limit: 1000000` |
| Loop tool calls | 25 | `callTool` inside for loop |
| Dynamic tool names | 20 | Variable as tool name |

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const enclave = new Enclave({
  scoringGate: {
    scorer: 'rule-based',
    blockThreshold: 70,
    warnThreshold: 40,
  },
});
```

## Layer 4: Runtime Sandbox

Code executes in an isolated Node.js vm context:

* **Fresh context** - No access to host scope
* **Controlled globals** - Only whitelisted APIs available
* **Resource limits** - Timeout, memory accounting, iterations, tool calls
* **Optional worker pool** - A heap limit per worker thread and a stop that does not depend on the script

### What's Available in the Sandbox

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Available in sandbox:
Math.random()               // ✓ Safe math
JSON.parse('{"a":1}')       // ✓ JSON handling
[1,2,3].map(x => x * 2)     // ✓ Array methods
await callTool('api', {})   // ✓ Tool calls (proxied)
console.log('debug')        // ✓ Console, with a consoleHandler or at PERMISSIVE (rate-limited)

// NOT available:
process.env.SECRET          // ✗ No process access
require('fs')               // ✗ No require
fetch('http://evil.com')    // ✗ No network
```

## Layer 5: Output Sanitization

Results are sanitized before returning to the caller:

* **Plain data** - The returned value is copied into plain host data; functions, symbols and prototype keys are dropped
* **Size check** - A value larger than the memory limit allows is refused
* **Errors as text** - `result.error` holds a `name` and a `message` of bounded length. An error made inside the sandbox has no stack; for the errors that have one, `sanitizeStackTraces` removes paths and frames

## Security Level Presets

Enclave provides preset configurations:

| Level | Timeout | Iterations | Tool Calls | Use Case |
| - | - | - | - | - |
| STRICT | 5s | 1K | 10 | Untrusted code |
| SECURE | 15s | 5K | 50 | Semi-trusted |
| STANDARD | 30s | 10K | 100 | Internal tools |
| PERMISSIVE | 60s | 100K | 1K | Testing |

## What Enclave Protects Against

* **Code injection** - Blocked by AST validation
* **Infinite loops** - Limited by maxIterations
* **Resource exhaustion** - Limited by the timeout, the memory accounting and the other limits (see below for what they cover)
* **Prototype pollution** - Blocked by AST validation and by the runtime
* **Sandbox escape** - Blocked by controlled globals
* **Information leakage** - Errors made in the sandbox carry no stack; host stacks can be sanitized
* **ReDoS attacks** - AgentScript has no regular expressions, and with the default preset the script's realm cannot run one

## What Enclave Does NOT Protect Against

* **Tool abuse** - Scripts can call allowed tools; limit what's available
* **Algorithmic complexity** - O(n²) algorithms run within limits
* **Business logic attacks** - Tool-level validation required
* **Side effects** - Tool calls have real effects
* **A hard time or memory bound in process** - In process, the timeout and `memoryLimit` are the enclave's own accounting, not the engine's. The deadline is checked between the steps of the script's own code, so one call into a built-in is not bounded by `timeout`; `memoryLimit` counts the operations that make text and arrays grow, not copies, objects, Maps or Sets. For the engine's own bounds, use the [worker pool](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/worker-pool.md), or a child process or container with limits of the operating system
* **A host process that survives whatever a worker allocates** - A worker thread shares the process; its heap limit is a backstop, not a guarantee
* **Misleading text in a script, with the looser pre-scanner presets** - The `agentscript` (default) and `strict` presets refuse bidirectional control characters and invisible characters in a script. `secure` does not refuse invisible characters, and `standard` (also what the `babel` AST preset runs with) and `permissive` refuse neither

## Best Practices

1. **Use STRICT for untrusted code** - AI-generated, user-submitted
2. **Limit available tools** - Only expose what's needed
3. **Validate tool inputs** - Check arguments before execution
4. **Monitor execution** - Log tool calls and durations
5. **Set appropriate limits** - Tune for your use case
6. **Keep updated** - Security improvements in new versions

## Related

* [Architecture](https://docs.agentfront.dev/enclave/concepts/architecture.md) - System overview
* [AgentScript](https://docs.agentfront.dev/enclave/concepts/agentscript.md) - Language definition
* [Security Levels](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/security-levels.md) - Preset details


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