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

# Common Errors

> Error codes, causes, and solutions for Enclave

This page documents error codes you may encounter when using Enclave, along with their causes and solutions.

## Execution Errors

`run()` does not reject for a failing script. It resolves with `success: false` and an `error` that has a `name`, a `message` and a `code`. The message says what happened; the code says which stage reported it. See [Error Codes](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/configuration.md#error-codes) for the complete list.

### VALIDATION\_ERROR

**Cause:** Code failed AST validation: a blocked construct was used. Also returned for a script of more than 5,242,880 characters, or one that is not a string.

**Example:**

```
AgentScript validation failed:
UNKNOWN_GLOBAL (line 2): Unknown identifier "fetch". All identifiers must be either declared locally or in the allowed globals list. ...
```

**Solution:**

* Review the [AgentScript](https://docs.agentfront.dev/enclave/concepts/agentscript.md) language definition
* Remove blocked constructs from your code
* Check the validation issues for specific lines

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
if (!result.success && result.error?.code === 'VALIDATION_ERROR') {
  console.log('Validation failed:', result.error.message);
  console.log('Issues:', result.error.data?.issues); // { code, severity, message, location? }
}
```

### Errors of the running script

A script that fails while it runs has the code `DOUBLE_VM_EXECUTION_ERROR` (or `VM_EXECUTION_ERROR` with `doubleVm: { enabled: false }`), whatever the reason. Tell the reasons apart by the message.

#### Timeout

**Message:** starts with `Script execution timed out`, for example `Script execution timed out after 5000ms`

**Cause:** Execution exceeded the configured timeout.

**Solutions:**

1. Optimize slow tool calls
2. Reduce iteration count
3. Increase timeout (if appropriate)

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const enclave = new Enclave({
  timeout: 30000, // Increase to 30s
});
```

In process the deadline is cooperative: it is checked between the steps of the script's own code. With `adapter: 'worker_threads'`, a script that is still running five seconds after its timeout is terminated with its worker, and the error is `WorkerTimeoutError` with the code `EXECUTION_ERROR`.

#### Tool call limit

**Message:** `Maximum tool call limit exceeded (50). This limit prevents runaway script execution.`

**Cause:** Script made too many tool calls.

**Solutions:**

1. Batch operations in tools instead of individual calls
2. Increase maxToolCalls limit
3. Review script logic for unnecessary calls

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Bad: Many individual calls
for (const id of ids) {
  await callTool('users:get', { id });
}

// Better: Batch call
await callTool('users:getMany', { ids });
```

#### Iteration limit

**Message:** starts with `Maximum iteration limit exceeded`

**Cause:** Loop iterations exceeded the limit.

**Solutions:**

1. Use pagination or limits in data fetching
2. Process data in chunks
3. Increase maxIterations (carefully)

#### A tool failed

**Cause:** A tool handler threw an error, and the script did not catch it. The message is the handler's.

**Solutions:**

1. Check tool inputs are valid
2. Throw errors with meaningful messages from tool handlers
3. Let the script handle the failure: `try` / `catch`, or `callTool(name, args, { throwOnError: false })`, which resolves to `{ success: false, error }` instead of throwing

```js theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const r = await callTool('users:get', { id }, { throwOnError: false });
if (!r.success) {
  return { failed: r.error.message };
}
return r.data;
```

### MEMORY\_LIMIT\_EXCEEDED

**Cause:** Script used more memory than `memoryLimit` allows, as the enclave counts it. The default limit is 1 MB.

**Example:**

```
Memory limit exceeded: 1.20MB used > 1.00MB limit
```

`error.data` holds `usedBytes` and `limitBytes`.

**Solutions:**

1. Process large data in chunks
2. Pass large strings between tools by reference with the [Reference Sidecar](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/reference-sidecar.md)
3. Increase memory limit

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const enclave = new Enclave({
  memoryLimit: 64 * 1024 * 1024, // 64MB
});
```

A used amount far above anything the script holds (`38.15MB used` for a short script, or gigabytes) points at an array's length, not at its contents: an array is counted by its slots, 8 bytes each, whether they hold anything or not. The usual causes are an array used as a sparse map (`seen[userId] = true`), an assignment to `length`, `Array(n)` with a large `n`, and an array method called on an object with a large `length`. Use an object or a `Map` for keys that are not small consecutive indexes.

A returned value that is larger than the memory limit allows fails with `SERIALIZATION_LIMIT_EXCEEDED`.

### SECURITY\_VIOLATION

**Cause:** The script contains a dynamic import (`import()` or `import.meta`), which is refused before the script runs, also with `validate: false`. At `STRICT` and `SECURE` the code is also returned when the runtime recorded a blocked operation during the run.

**Solution:** Remove the construct. A script reaches the outside through tools only.

### SCORING\_BLOCKED

**Cause:** The AI Scoring Gate gave the script a score at or above `blockThreshold`, or it could not score the script and `failOpen` is `false`.

**Example:**

```
Script blocked by AI scoring (score: 75): EXFIL_PATTERN: Potential data exfiltration: users:list → email:send; ...
```

`error.data` holds `totalScore`, `riskLevel` and `signals`.

**Solutions:**

1. Review code for exfiltration patterns
2. Avoid list→send sequences
3. Use specific queries instead of wildcards
4. Adjust scoring thresholds if false positive: the score is a heuristic

### ENCLAVE\_ERROR

**Cause:** A failure outside the sandbox before the script ran. The most common one is a syntax error: `Failed to parse AgentScript code: ...`.

**Solution:** Fix the syntax of the script.

## Validation Issues

### Unknown global

**Message:** `Unknown identifier "xyz". All identifiers must be either declared locally or in the allowed globals list.` (code `UNKNOWN_GLOBAL`)

**Cause:** Code references an identifier not in the allowed globals list.

**Solution:** Use a tool instead, or give the enclave the value as a custom global:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const enclave = new Enclave({
  globals: { context: { userId: 'user-123' } },
});
```

With `@enclave-vm/ast` on its own, list the name in `allowedGlobals` of the preset.

### Blocked identifier

**Message:** `Identifier 'process' is not allowed`

**Cause:** Code uses a blocked identifier like `process`, `eval`, etc.

**Solution:** Remove the blocked identifier or use an allowed alternative.

### Invalid loop type

**Message:** `'while' loops are not allowed`

**Cause:** Code uses a blocked loop type.

**Solution:** Use `for` or `for-of` instead:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Bad: while loop
while (hasMore) { /* ... */ }

// Good: for loop
for (let i = 0; i < maxIterations && hasMore; i++) { /* ... */ }
```

### User-defined function

**Message:** `User-defined functions are not allowed`

**Cause:** Code declares a function.

**Solution:** Use arrow functions in array methods or inline logic:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Bad: function declaration
function process(item) { return item.value; }

// Good: arrow in array method
items.map(item => item.value);
```

## Pre-Scanner Errors

The enclave runs the pre-scanner with the preset named like its AST preset, so by default with `agentscript`: 100 KB of script in at most 1,000 lines of at most 2,000 characters, nesting depth 20, string literals of at most 10 KB, no regular-expression literal, no bidirectional or invisible control character. A script that needs more room gets it through the `preScan` option, for example `preScan: { preset: 'standard' }` (5 MB, 10,000 lines, nesting depth 50) or `preScan: { config: { maxStringLength: 512 * 1024, maxLineLength: 100000 } }`.

### Input size exceeded

**Message:** `Input size (...) exceeds maximum allowed (...)` (code `PRESCANNER_INPUT_TOO_LARGE`)

**Solution:** Reduce code size.

### Nesting depth exceeded

**Message:** `Bracket nesting depth (51) exceeds maximum allowed (50)` (code `PRESCANNER_NESTING_OVERFLOW`)

**Solution:** Simplify nested expressions.

### Regular expression

**Code:** `PRESCANNER_REDOS` (a regex literal the pre-scanner rates as vulnerable), `NO_REGEX_LITERAL` or `NO_REGEX_METHOD` (the AgentScript rules)

**Solution:** AgentScript has no regular expressions. Use string methods with plain strings (`includes`, `startsWith`, `split(',')`), or let a tool do the matching.

### Look-alike letter

**Code:** `PRESCANNER_HOMOGRAPH`

**Cause:** The script contains a letter from another script that looks like an ASCII letter (for example a Cyrillic `а`), anywhere in its text, string literals included.

**Solution:** Replace the letter. Text in such a script reaches a script through a tool result, not as a literal.

## Connection Errors

### Connection refused

**Cause:** The client cannot connect to the broker.

**Solutions:**

1. Check the server is running
2. Verify the URL is correct
3. Check network/firewall settings

### Session not found

**Cause:** Referencing an expired or invalid session.

**Solutions:**

1. Sessions expire after completion
2. Create a new session
3. Check session ID is correct

## Debugging Tips

### Read the whole error

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const result = await enclave.run(code);

if (!result.success) {
  console.log(result.error?.code, result.error?.name);
  console.log(result.error?.message);
  console.log(result.error?.data); // validation issues, scoring signals, memory figures
}
```

An error made inside the sandbox has no `stack`. The message is where the information is.

### Log validation results

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

const validator = new JSAstValidator(createAgentScriptPreset());
const result = await validator.validate(code);

if (!result.valid) {
  console.log('Validation issues:');
  for (const issue of result.issues) {
    console.log(`  ${issue.code}: ${issue.message}`);
    if (issue.location) {
      console.log(`    at line ${issue.location.line}, column ${issue.location.column}`);
    }
  }
}
```

### Track execution stats

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const result = await enclave.run(code);

console.log('Execution stats:', {
  duration: result.stats.duration,
  toolCalls: result.stats.toolCallCount,
  iterations: result.stats.iterationCount,
  memory: result.stats.memoryUsage,
});
```

## Related

* [Debugging](https://docs.agentfront.dev/enclave/troubleshooting/debugging.md) - Debug techniques
* [FAQ](https://docs.agentfront.dev/enclave/troubleshooting/faq.md) - Frequently asked questions
* [Security Model](https://docs.agentfront.dev/enclave/concepts/security-model.md) - Understanding restrictions


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