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

A blocked name is refused as a property as well, however the key is spelled: `obj.process`, `obj['process']`, `obj['pro' + 'cess']`. To read a field of your data that has such a name, take the key from a run-time value (a parameter, a field of a tool result); with `@enclave-vm/ast` on its own under the STRICT or SECURE preset, a key held in a variable is read as its value too.

### Property key that cannot be resolved

**Message:** `Computed property key cannot be resolved. It is made of constants, so it names one fixed property, and the validator cannot tell which. Write the property name directly.` (code `STATIC_KEY_UNRESOLVED`)

**Cause:** A computed key (`obj[...]`, or a computed key of a destructuring pattern) is built only from constants, and in a way the validator does not evaluate. Such a key has one fixed value. A validator that cannot read it cannot tell that it is not a blocked name, so it does not accept it. The usual cases:

* The key goes through something the validator does not run: a `Map`, a class, a regular expression, a function called in place whose body has a loop or assigns to a variable.
* Something inside the key assigns to a variable or to a property, or calls a function the validator does not follow. The key is then not computed at all, whatever it reads afterwards.
* The key goes through a built-in (`Math.max(...)`, `'AB'.toLowerCase()`, `[...].join('')`) in a script that can change a built-in: one that assigns to a built-in (`Math.max = f`), or that hands one on (`const M = Math`) and also writes to an object the validator cannot tell apart from it (`M.max = f`). Passing `Number` to `map`, or keeping `Object.keys` under another name, does not count.
* The key depends on the engine the script runs in (`typeof Math`, whether a newer method such as `Array.prototype.toSorted` exists), or costs more to compute than the validator spends on one key.
* With a preset that follows variables (STRICT, SECURE, STANDARD), the key is read through a variable whose values cost more to follow than the validator spends: for example a key built in a loop over a large table the script holds, or a script with very many such keys. Following it is how the validator knows that no value is a blocked name, so a key it could not follow to its end is refused, not left to run time. Keep large data out of the script (pass it in through a tool or a global) or write the names directly.

**Solution:** Write the name the key evaluates to:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Refused: the key is fixed, and not evaluated
const value = row[new Map([['k', 'total']]).get('k')];

// Accepted
const direct = row.total;
const quoted = row['total'];
const joined = row['to' + 'tal'];         // evaluated: 'total'
const chosen = row[field];                // a run-time value: checked where the script runs
```

A key that the expression would build to more than 4096 characters (`row['ab'.repeat(5000)]`) is refused the same way, with `STATIC_KEY_TOO_LONG`, without being built. The limit is on what is built: a string literal, or a template literal without a substitution, is read as it is written, however long it is.

### Timer used as a value

**Message:** `Use of setTimeout as a value is not allowed (it can then be called with a string, which acts like eval)` (code `NO_EVAL`)

**Cause:** `setTimeout` or `setInterval` is stored under another name, passed to a function, or called through `.call`, `.apply` or `.bind`. A timer compiles a string argument into code, and the validator can only check the argument where the timer is called by its name. The same holds for `eval` and `Function`. A first argument that can never be a function (a template, a list, an object, `value.toString()`) is refused where the timer is called, with the message `Use of setTimeout with string argument is not allowed`.

**Solution:** Call the timer where it is named, with a function:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Refused
const later = setTimeout;
const wait = promisify(setTimeout);

// Accepted
setTimeout(() => tick(), 100);
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
```

### Source nested too deeply

**Message:** `Source is nested too deeply to be validated` (code `SOURCE_TOO_DEEP`)

**Cause:** An expression is nested (or chained, as in `a.b.c.d...`) several thousand levels deep, deeper than a rule can walk. The source is not validated, so it is refused. The pre-scanner refuses most such sources earlier (see [Nesting depth exceeded](#nesting-depth-exceeded)).

This is reported for a source that nests deeply. If a custom rule runs out of stack on a source that does not, the rule ran out by itself, and `validate()` throws its `RangeError`.

**Solution:** Split the expression into statements.

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