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

# AgentScript Preset

> Purpose-built preset for validating LLM-generated orchestration code

The AgentScript preset is purpose-built for validating LLM-generated orchestration code. It's the default preset used by [enclave-vm](https://docs.agentfront.dev/enclave/core-libraries/enclave-vm/overview.md) and provides the strictest validation for AI-generated code.

## Basic Usage

```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(`
  const users = await callTool('users:list', { limit: 10 });
  return users.filter(u => u.active);
`);
```

## Configuration Options

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const validator = new JSAstValidator(createAgentScriptPreset({
  // Require at least one callTool() invocation (default: false)
  requireCallTool: true,

  // Customize allowed globals
  allowedGlobals: ['callTool', 'getTool', 'Math', 'JSON', 'Array', 'Object'],

  // Allow arrow functions for array methods (default: true)
  allowArrowFunctions: true,

  // Configure allowed loop types
  allowedLoops: {
    allowFor: true,      // for (let i = 0; ...) - default: true
    allowForOf: true,    // for (const x of arr) - default: true
    allowWhile: false,   // while (cond) - default: false
    allowDoWhile: false, // do {} while (cond) - default: false
    allowForIn: false,   // for (key in obj) - default: false
  },

  // Additional identifiers to block
  additionalDisallowedIdentifiers: ['customDangerous'],
}));
```

## Option Reference

| Option | Type | Default | Description |
| - | - | - | - |
| `securityLevel` | `string` | `'STANDARD'` | Selects the default allowed globals: `STRICT`, `SECURE`, `STANDARD`, `PERMISSIVE` |
| `requireCallTool` | `boolean` | `false` | Require at least one `callTool()` invocation in the code |
| `allowedGlobals` | `string[]` | By `securityLevel` | Identifiers that can be referenced without declaration |
| `hostObjectGlobals` | `string[]` | `[]` | The names in `allowedGlobals` that are objects of the host and not strings (tool namespaces, object globals). A method called `match`, `matchAll` or `search` on one of them is accepted with any argument; on every other value those three are refused |
| `allowArrowFunctions` | `boolean` | `true` | Allow arrow functions for array methods |
| `allowedLoops` | `object` | `for` and `for-of` | Configure which loop types are allowed |
| `additionalDisallowedIdentifiers` | `string[]` | `[]` | Additional identifiers to block |
| `reservedPrefixes` | `string[]` | `[]` | Prefixes to reserve in addition to `__ag_` and `__safe_`, which are always reserved |
| `staticCallTarget` | `object` | `{ enabled: true }` | Require the tool name of `callTool` to be a string literal; `allowedToolNames` restricts the names |
| `callToolValidation` | `object` | - | Argument count and types of `callTool` (`minArgs`, `maxArgs`, `expectedTypes`) |
| `requireDirectRegexMethodCalls` | `boolean` | `false` | Refuse `match` / `matchAll` / `search` as anything but a direct call (see [Regular-Expression Methods](#regular-expression-methods)) |
| `additionalAllowedSyntax` | `string[]` | `[]` | Constructs to allow beyond the syntax allowlist (see [Syntax Allowlist](#syntax-allowlist)) |
| `allowDynamicArrayFill` | `boolean` | `false` | Allow `Array(n).fill()` with a size that is not a literal; only for a runtime that bounds memory itself |

> [!TIP]
>
> Use `requireCallTool: true` to ensure AgentScript code actually interacts with tools rather than just performing local computations.

## What AgentScript Blocks

| Category | Blocked Constructs | Why |
| - | - | - |
| **Code execution** | `eval`, `Function`, `AsyncFunction`, `GeneratorFunction` | Prevents dynamic code injection |
| **System access** | `process`, `require`, `module`, `__dirname`, `__filename`, `Buffer` | Prevents Node.js API access |
| **Global objects** | `window`, `globalThis`, `global`, `self`, `this` | Prevents sandbox escape |
| **Timers** | `setTimeout`, `setInterval`, `setImmediate` | Prevents timing attacks and async escape |
| **Prototype** | `__proto__`, `constructor`, `prototype` | Prevents prototype pollution |
| **Metaprogramming** | `Proxy`, `Reflect` | Prevents interception and reflection |
| **Network** | `fetch`, `XMLHttpRequest`, `WebSocket` | Prevents network access |
| **Storage** | `localStorage`, `sessionStorage`, `indexedDB` | Prevents data persistence |
| **Native code** | `WebAssembly`, `Worker`, `SharedWorker` | Prevents native execution |
| **Weak references** | `WeakMap`, `WeakSet`, `WeakRef` | Prevents reference manipulation |
| **User functions** | `function foo() {}`, `const f = function() {}` | Prevents recursion (arrow functions allowed) |
| **Unbounded loops** | `while`, `do-while`, `for-in` | Prevents infinite loops and prototype walking |

## Syntax Allowlist

The table above lists names. The preset also has an allowlist of syntax (`AllowedSyntaxRule`, `AGENTSCRIPT_ALLOWED_NODE_TYPES`): a script may only contain the node types on it, so a construct no rule names is refused as well. Not on the list are `this`, classes, `new.target`, `import.meta`, `debugger`, `with`, `yield`, dynamic `import()` and module declarations.

Four constructs share their node type with an allowed one and are constructs of their own. They are refused, and allowed only when listed under their own name:

| Construct | Name |
| - | - |
| `using x = ...` | `UsingDeclaration` |
| `await using x = ...` | `AwaitUsingDeclaration` |
| `for await (const x of ...)` | `ForAwaitStatement` |
| `function* () {}` | `GeneratorFunction` |

Listing `ForOfStatement` allows `for…of`, not `for await…of`.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Only for a host that does not run untrusted code
const validator = new JSAstValidator(createAgentScriptPreset({
  additionalAllowedSyntax: ['ForAwaitStatement'],
}));
```

The one function declaration a script may contain is the wrapper the transformer puts around it: the first top-level `async function __ag_main() { ... }` without parameters. Every other function declaration is refused, also one that carries that name.

## `Object` Is Used Directly

The preset refuses the reflection functions by property name, wherever they are read and on whatever object: `getPrototypeOf`, `setPrototypeOf`, `defineProperty`, `defineProperties`, `getOwnPropertyDescriptor`, `getOwnPropertyDescriptors`, `getOwnPropertySymbols` and the legacy accessor methods (`__defineGetter__`, `__lookupGetter__`, ...). `Object.create` is refused on `Object`. So that this holds, the global `Object` may only be used directly (the `requireDirectObjectUse` option of `NoGlobalAccessRule`, which the preset switches on):

```js theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Accepted
Object.keys(data);
Object(value);
new Object();
typeof Object;
value instanceof Object;

// Refused with OBJECT_INDIRECT_USE
const O = Object;          // an alias
helper(Object);            // passing it as a value
const { keys } = Object;   // destructuring from it
Object[name];              // a member name computed at run time
Object.valueOf();           // returns Object itself
```

A variable of the script that is called `Object` is not the global and is left alone.

## Regular-Expression Methods

AgentScript has no regular expressions: regex literals are refused, and so are `match`, `matchAll` and `search` on a value of the script, with any argument, because a string passed to them is compiled into a regular expression. The check sees the call in every static spelling of the method name (`x.match`, `x['match']`, a template literal without substitutions), through `call` / `apply` / `bind`, as a template tag and without an argument.

A method of that name on a global the host declared as an object (`hostObjectGlobals`: a tool namespace such as `docs.search(args)`) is the host's own method and is accepted.

With `requireDirectRegexMethodCalls: true` the three methods cannot be read as a value or taken by destructuring either. That also refuses reading a field of ordinary data with one of these names (`params.search`), so it is off by default. It is for a host where the validator is the only thing between a script and the regular-expression engine; `@enclave-vm/core` by default runs scripts in a realm where a regular expression cannot run whatever a script does.

## Reserved Names

A script cannot declare, assign or use as a property target a name that starts with `__ag_` or `__safe_`, the prefixes of the runtime. `reservedPrefixes` adds prefixes to those two; it does not replace them. `__maxIterations`, the runtime's name for the iteration limit, is reserved as well.

## What AgentScript Allows

```js theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
// Tool calls
const result = await callTool('users:list', { limit: 10 });

// Variables
const users = result.items;
let count = 0;

// Conditionals
if (users.length > 0) { count = users.length; }

// Bounded loops
for (let i = 0; i < users.length; i++) { /* ... */ }
for (const user of users) { /* ... */ }

// Array methods with arrow functions
const active = users.filter(u => u.active);
const names = users.map(u => u.name);
const total = users.reduce((sum, u) => sum + u.score, 0);

// Safe globals
const max = Math.max(1, 2, 3);
const parsed = JSON.parse('{"a":1}');
const keys = Object.keys(obj);

// Return values
return { count, active, names };
```

## Default Allowed Globals

The AgentScript preset allows these globals by default (`securityLevel: 'STANDARD'`):

* `callTool` - Tool invocation
* `Math` - Mathematical operations
* `JSON` - `JSON.parse` and `JSON.stringify`, as direct calls without a reviver or replacer function
* `Array` - Array constructor and methods
* `Object` - Object methods, used directly (see above)
* `String` - String methods
* `Number` - Number methods
* `Date` - Date operations
* `undefined`, `NaN`, `Infinity` - Constants
* `parseInt`, `parseFloat`, `isNaN`, `isFinite`, `encodeURI`, `decodeURI`, `encodeURIComponent`, `decodeURIComponent` - Not at `STRICT`
* `console` - Only at `PERMISSIVE`

`getAgentScriptGlobals(securityLevel)` returns the list for a level.

## Customizing Allowed Globals

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const validator = new JSAstValidator(createAgentScriptPreset({
  allowedGlobals: [
    // Standard
    'callTool', 'Math', 'JSON', 'Array', 'Object',

    // Custom additions
    'context',      // Your context object
    'formatDate',   // Custom utility
  ],
}));
```

### Precedence Rules

When `allowedGlobals` and `additionalDisallowedIdentifiers` are both provided, the following precedence applies:

1. **`allowedGlobals` removes from the dangerous list** — If an identifier like `process` is normally blocked but you include it in `allowedGlobals`, it will be removed from the built-in dangerous identifiers blocklist and allowed.
2. **`additionalDisallowedIdentifiers` always wins** — If an identifier appears in both `allowedGlobals` and `additionalDisallowedIdentifiers`, it remains **blocked**. This lets you grant broad access while force-blocking specific identifiers.

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const validator = new JSAstValidator(createAgentScriptPreset({
  allowedGlobals: ['callTool', 'process', 'safeApi', 'dangerousApi'],
  additionalDisallowedIdentifiers: ['dangerousApi'],
}));

// 'process' — normally blocked, but allowedGlobals removes it → allowed
// 'safeApi' — custom global, not in any blocklist → allowed
// 'dangerousApi' — in allowedGlobals BUT also in additionalDisallowedIdentifiers → blocked
```

> [!WARNING]
>
> Be careful when adding normally-blocked identifiers like `process` or `eval` to `allowedGlobals`. Only do so when the sandbox runtime provides safe wrappers for these APIs.

## Loop Configuration

Control which loop types are allowed:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const validator = new JSAstValidator(createAgentScriptPreset({
  allowedLoops: {
    allowFor: true,      // for (let i = 0; i < n; i++)
    allowForOf: true,    // for (const item of array)
    allowWhile: false,   // while (condition)
    allowDoWhile: false, // do {} while (condition)
    allowForIn: false,   // for (key in object)
  },
}));
```

> [!WARNING]
>
> `for-in` loops are blocked by default because they iterate over prototype properties, which can lead to unexpected behavior and security issues.

## Requiring Tool Calls

Ensure scripts actually use tools:

```ts theme={"theme":{"light":"snazzy-light","dark":"dark-plus"}}
const validator = new JSAstValidator(createAgentScriptPreset({
  requireCallTool: true,
}));

// This passes:
validator.validate('const x = await callTool("test", {}); return x;');

// This fails:
validator.validate('return 1 + 2;'); // No callTool
```

## Related

* [Overview](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/overview.md) - Getting started
* [Pre-Scanner](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/pre-scanner.md) - Layer 0 defense
* [Security Rules](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/security-rules.md) - Rule reference
* [Code Transform](https://docs.agentfront.dev/enclave/core-libraries/ast-guard/code-transform.md) - AST transformations


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