AST Validation
Block dangerous constructs before execution using ast-guard’s AgentScript preset
Code Transformation
Automatically transform code for safe execution with proxied functions and loop limits
Runtime Sandboxing
Execute in isolated Node.js vm context with controlled globals and resource limits
When to Use Enclave
Enclave is designed for scenarios where you need to execute JavaScript code from untrusted sources:- LLM-generated code - Execute code written by AI models safely
- User-provided scripts - Run user scripts in a controlled environment
- Plugin/extension systems - Allow third-party code to run securely
- Workflow automation - Execute orchestration logic with tool access
Enclave is used internally by the CodeCall Plugin to execute JavaScript execution plans. You can also use it directly for custom use cases.
Installation
Enclave is available as a separate package:Quick Start
Security Level Presets
Enclave provides pre-configured security profiles that balance functionality against risk:Security Level Comparison
| Setting | STRICT | SECURE | STANDARD | PERMISSIVE |
|---|---|---|---|---|
| timeout | 5s | 15s | 30s | 60s |
| maxIterations | 1,000 | 5,000 | 10,000 | 100,000 |
| maxToolCalls | 10 | 50 | 100 | 1,000 |
| maxConsoleCalls | 100 | 500 | 1,000 | 10,000 |
| maxConsoleOutputBytes | 64KB | 256KB | 1MB | 10MB |
| sanitizeStackTraces | YES | YES | NO | NO |
| blockTimingAPIs | YES | NO | NO | NO |
| allowUnboundedLoops | NO | NO | YES | YES |
| unicodeSecurityCheck | YES | YES | NO | NO |
Defense-in-Depth Security Model
Enclave uses a four-layer security approach:Layer 1: AST Validation
Before any code runs, Enclave validates the AST using ast-guard’s AgentScript preset:| Category | Blocked Constructs |
|---|---|
| Eval-like | eval, Function, setTimeout, setInterval |
| Globals | process, require, window, document, global, globalThis |
| Context access | this, self, parent, top, frames |
| Prototype manipulation | __proto__, constructor, prototype access |
Layer 2: Code Transformation
Valid code is transformed for safe execution:- Main wrapper: Wrap code in
async function __ag_main()for top-level await - Safe callTool: Transform
callTool→__safe_callTool(proxied through Enclave) - Safe loops: Transform
for,while,do-while→ safe versions with iteration limits - Safe console: Transform
console→__safe_console(captured for logging with rate limiting)
Layer 3: Runtime Sandboxing
Code executes in an isolated Node.js vm context:- Isolated context: Fresh context with no access to host environment
- Controlled globals: Only whitelisted globals available (
Math,JSON,Array, etc.) - Resource limits: Timeout, iteration count, tool call limits, and console rate limits enforced
- Stack sanitization: Error stack traces sanitized to prevent information leakage
Layer 4: Reference Sidecar (Optional)
When enabled, large data is handled separately:- Large data extraction: Strings exceeding the threshold are stored in sidecar storage
- Reference tokens: Large strings are replaced with safe reference tokens (
__ref_abc123) - Lazy resolution: Data is only resolved when explicitly accessed
- Composite blocking: String concatenation with references can be blocked (
allowComposites: false)
Configuration Options
Maximum execution time in milliseconds (default 30 seconds)
Maximum number of tool calls allowed per execution
Maximum loop iterations allowed (prevents infinite loops)
Async function that handles
callTool() invocations from the script.
Signature: (toolName: string, args: Record<string, unknown>) => Promise<unknown>Additional globals to make available in the script context
Whether to validate code with ast-guard before execution
Whether to transform code before execution
Allow functions in the
globals object. Required when providing callback functions or utilities.Maximum total console output in bytes. Prevents I/O flood attacks via excessive logging.
Defaults vary by security level: STRICT=64KB, SECURE=256KB, STANDARD=1MB, PERMISSIVE=10MB.
Maximum number of console calls allowed. Prevents I/O flood attacks via rapid-fire logging.
Defaults vary by security level: STRICT=100, SECURE=500, STANDARD=1000, PERMISSIVE=10000.
Configuration for handling large data via reference tokens
Reference Sidecar
The sidecar is a powerful feature for handling large data in AgentScript without embedding it in the script. This keeps script size small for reliable AST validation while allowing tools to return large datasets.How It Works
- Extraction: When a tool returns data with large strings (>
extractionThreshold), those strings are stored in the sidecar and replaced with reference tokens (__ref_abc123) - Lazy Resolution: When script code accesses a reference token, it’s resolved just-in-time to the actual data
- Safe Property Access: Only explicit property accesses trigger resolution, preventing data exfiltration
Security: allowComposites
TheallowComposites: false setting (default) blocks string concatenation with reference tokens:
allowComposites: false unless you specifically need string concatenation with large data.
AI Scoring Gate
The Scoring Gate adds semantic security analysis that detects attack patterns beyond static AST validation:- Data exfiltration - list→send or query→export sequences
- Excessive access - High limits, wildcard queries
- Fan-out attacks - Tool calls inside loops
- Sensitive data access - Passwords, tokens, PII fields
Scorer Types
| Type | Latency | Dependencies | Detection |
|---|---|---|---|
disabled | 0ms | None | None |
rule-based | ~1ms | None | Good |
local-llm | ~5-10ms | Model download | Better |
external-api | ~100ms | Network | Best |
Detection Rules
The rule-based scorer detects these patterns:| Rule | Score | Description |
|---|---|---|
SENSITIVE_FIELD | 35 | Queries password/token/secret fields |
EXCESSIVE_LIMIT | 25 | limit > 10,000 |
WILDCARD_QUERY | 20 | query=”*” or filter= |
LOOP_TOOL_CALL | 25 | callTool inside for/for-of loop |
EXFIL_PATTERN | 50 | list→send or query→export sequence |
EXTREME_VALUE | 30 | Numeric arg > 1,000,000 |
DYNAMIC_TOOL | 20 | Variable tool name (not static string) |
BULK_OPERATION | 15 | Tool name contains bulk/batch/all |
Caching
Results are cached by code hash (default: 5 minutes, 1000 entries):Worker Pool Adapter
For OS-level memory isolation, use the worker threads adapter:Worker Pool Features
- Pool management - Auto-scaling with min/max workers
- Memory monitoring - Workers recycled when exceeding limits
- Hard halt - Force terminate via
worker.terminate() - Rate limiting - Message flood protection
- Dual-layer sandbox - Worker thread + VM context isolation
Worker Pool Presets
| Setting | STRICT | SECURE | STANDARD | PERMISSIVE |
|---|---|---|---|---|
| maxWorkers | 4 | 8 | 16 | 32 |
| memoryLimitPerWorker | 64MB | 128MB | 256MB | 512MB |
| maxExecutionsPerWorker | 100 | 500 | 1,000 | 5,000 |
| maxQueueSize | 20 | 50 | 100 | 500 |
| maxMessagesPerSecond | 100 | 500 | 1,000 | 5,000 |
Worker Pool Configuration
Minimum warm workers to keep in the pool
Maximum workers in the pool
Memory limit per worker (workers exceeding this are recycled)
Executions before a worker is recycled (prevents memory leaks)
Maximum pending executions in the queue
Rate limit for messages from a single worker (prevents flooding)
Execution Results
Enclave returns a structured result with success/error status and execution stats:Error Codes
| Code | Meaning | Action |
|---|---|---|
VALIDATION_ERROR | AST validation failed | Fix the code - blocked construct used |
EXECUTION_ERROR | Runtime error in script | Fix script logic |
TIMEOUT | Execution exceeded timeout | Optimize or increase timeout |
TOOL_ERROR | Tool call failed | Check tool input/availability |
Advanced Usage
Custom Globals
Provide custom globals for scripts to access:One-Shot Execution
For simple cases, use the convenience function:Tool Handler Integration
Integrate with your existing tool system:Security Considerations
What Enclave Protects Against
- Code injection - Blocked by AST validation
- Infinite loops - Limited by
maxIterations - Resource exhaustion - Limited by
timeoutandmaxToolCalls - I/O flood attacks - Limited by
maxConsoleOutputBytesandmaxConsoleCalls - Global access - Blocked by AST validation and isolated context
- Prototype pollution - Blocked by AST validation
- Information leakage - Stack traces sanitized
What Enclave Does NOT Protect Against
- Tool abuse - Scripts can call allowed tools; limit what’s available
- Algorithmic complexity - Scripts can run O(n²) algorithms within limits
- Memory exhaustion - Large arrays/objects within timeout
- Side effects - Tool calls have real effects; use read-only tools where possible

