@enclave-vm/core 2.15.2 → 2.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -91,10 +91,15 @@ interface CreateEnclaveOptions {
91
91
 
92
92
  // Tool execution
93
93
  toolHandler?: ToolHandler; // Function to execute tool calls
94
+ toolNamespaces?: ToolNamespaces; // Expose tools as `ns.method(args)` (see "Tool Namespaces")
94
95
 
95
96
  // Custom globals
96
97
  globals?: Record<string, unknown>; // Additional globals for the VM
97
98
  allowFunctionsInGlobals?: boolean; // Allow functions in globals (default: false)
99
+ maxGlobalFunctionCalls?: number; // Cap on calls into functions from globals (default: 10 × maxToolCalls)
100
+
101
+ // Errors
102
+ sanitizeStackTraces?: boolean; // Redact paths/frames in every returned error (default: by security level)
98
103
 
99
104
  // Sidecar (large data handling)
100
105
  sidecar?: ReferenceSidecarOptions;
@@ -562,6 +567,65 @@ const malicious = ref + '__proto__'; // Attempting prototype pollution
562
567
 
563
568
  Set `allowComposites: true` only if you need to concatenate strings and understand the security implications.
564
569
 
570
+ ## Tool Namespaces
571
+
572
+ Expose tools to scripts as namespaced functions instead of (or alongside) `callTool()`:
573
+
574
+ ```typescript
575
+ const enclave = new Enclave({
576
+ toolHandler: async (name, args) => callMyTool(name, args),
577
+ toolNamespaces: {
578
+ mail: ['list', 'send'], // mail.list(args) calls the tool 'mail.list'
579
+ users: { get: 'users:get' }, // users.get(args) calls the tool 'users:get'
580
+ },
581
+ });
582
+
583
+ const result = await enclave.run(`
584
+ const inbox = await mail.list({ unread: true });
585
+ const sender = await users.get({ id: inbox[0].from });
586
+ return sender.name;
587
+ `);
588
+ ```
589
+
590
+ A namespace method call **is** a `callTool()` call: `mail.list(args, options)` behaves exactly like
591
+ `callTool('mail.list', args, options)`. It counts toward `maxToolCalls`, goes through the double VM's
592
+ rate limit, operation-name and suspicious-sequence checks, its result is sanitized, and it reaches your
593
+ `toolHandler`. `args` defaults to `{}`. Each namespace is a frozen, null-prototype object created
594
+ inside the sandbox, so aliasing (`const m = mail; m.list()`) and destructuring work and no host object
595
+ is exposed.
596
+
597
+ The constructor throws a `TypeError` (`Invalid toolNamespaces: ...`) for names that are not identifiers,
598
+ prototype keys (`__proto__`, `constructor`, `prototype`), names starting with `__`, reserved words and
599
+ sandbox globals used as namespaces (`callTool`, `Math`, `console`, ...), identifiers the AgentScript
600
+ validator refuses (`process`, `fetch`, ...), namespaces that collide with a custom global, duplicated
601
+ methods, and tool names every adapter cannot carry (empty, over 256 characters, or outside letters, digits,
602
+ `:`, `.`, `_` and `-` starting with a letter, including a generated `<namespace>.<method>` name).
603
+
604
+ Prefer namespaces over exposing tools as functions in `globals`: functions in `globals` are gated and
605
+ sanitized (see "Custom Globals"), but the suspicious-sequence detectors only see tool calls.
606
+
607
+ ## callTool Options
608
+
609
+ Scripts can pass options as the third argument of `callTool` (or the second argument of a namespace
610
+ method):
611
+
612
+ ```javascript
613
+ const r = await callTool('users:get', { id }, { throwOnError: false });
614
+ if (r.success) {
615
+ return r.data;
616
+ }
617
+ return { failed: r.error.message }; // r.error: { name, message, code?, toolName }
618
+ ```
619
+
620
+ | Option | Default | Description |
621
+ | -------------- | ------- | ---------------------------------------------------------------------------------------------------------------------- |
622
+ | `throwOnError` | `true` | `false`: resolve to `{ success: true, data }` or, when the tool fails, `{ success: false, error }` instead of throwing |
623
+
624
+ Only failures of the tool itself (the handler threw or rejected, or its result could not be delivered)
625
+ are returned this way; the error object is plain data with no stack. Refusals by the enclave (abort,
626
+ `maxToolCalls`, rate limit, operation-name and suspicious-sequence checks, invalid arguments) always
627
+ throw. Options are applied inside the sandbox and are not passed to the `toolHandler`.
628
+
565
629
  ## Custom Globals
566
630
 
567
631
  You can provide custom globals to the VM:
@@ -589,6 +653,31 @@ const result = await enclave.run(`
589
653
 
590
654
  **Security Note**: Set `allowFunctionsInGlobals: true` only when you intentionally provide functions. Functions in globals can potentially leak host scope via closures.
591
655
 
656
+ Every call from the script into a function from `globals` (including functions nested in objects) goes
657
+ through the enclave's gate:
658
+
659
+ - it is refused once the execution is aborted, and counts toward `maxGlobalFunctionCalls`
660
+ (default: 10 × `maxToolCalls`), not toward `maxToolCalls`;
661
+ - in the double VM (the default) it shares the operation rate limit
662
+ (`doubleVm.parentValidation.maxOperationsPerSecond`) with tool calls;
663
+ - its return value is sanitized like a tool result: the script receives a plain-data copy, and a
664
+ value containing functions or symbols, or exceeding the sanitize depth/size limits, is refused;
665
+ - an error it throws reaches the script as a plain error without the host stack;
666
+ - calling it with `new` is refused.
667
+
668
+ The suspicious-sequence detectors only look at tool calls, so expose tools with `toolNamespaces` or
669
+ `callTool()`, not as functions. The `worker_threads` adapter never passes functions into the sandbox.
670
+
671
+ Inside arrays, Maps and Sets only plain data is allowed (primitives, plain objects, arrays, Maps, Sets,
672
+ Dates, RegExps, typed arrays): the built-in methods of those collections (`forEach`, iteration, `get`)
673
+ hand elements to the script directly, so a function (or an object with methods) stored there would be
674
+ called without the gate. The constructor refuses it with an error naming the path, e.g.
675
+ `Custom global "cfg" contains a function inside a collection at hooks.0.run`. Every own entry counts there,
676
+ enumerable or not, and Map and Set subclasses are refused inside collections. Arrays anywhere in `globals`
677
+ must be plain arrays (no Proxy, no custom prototype), since those can hide entries from validation.
678
+ Promises, WeakMaps, iterators and generators are refused anywhere in `globals`, since their contents cannot
679
+ be validated.
680
+
592
681
  ## Execution Result
593
682
 
594
683
  ```typescript
@@ -610,6 +699,11 @@ interface ExecutionResult<T> {
610
699
  }
611
700
  ```
612
701
 
702
+ With `sanitizeStackTraces` on (the default for `STRICT` and `SECURE`), every returned `error.stack` is
703
+ sanitized, whichever stage raised the error (validation, transformation, compilation, execution, tool
704
+ calls) and whichever adapter ran the script: stack frames become `at [REDACTED]` and paths, URLs and
705
+ file locations in the remaining lines are redacted.
706
+
613
707
  ### Error Codes
614
708
 
615
709
  | Code | Description |
@@ -713,6 +807,10 @@ class Enclave {
713
807
  type ToolHandler = (toolName: string, args: Record<string, unknown>) => Promise<unknown>;
714
808
  ```
715
809
 
810
+ Called for every `callTool()` and `toolNamespaces` method call that passes the enclave's checks. The
811
+ script's `callTool` options (`CallToolOptions`) are applied inside the sandbox and are not passed to
812
+ the handler.
813
+
716
814
  ## Testing
717
815
 
718
816
  ```bash
@@ -7,6 +7,7 @@
7
7
  * @packageDocumentation
8
8
  */
9
9
  import { z } from 'zod';
10
+ import { type NormalizedToolNamespace } from '@enclave-vm/ast';
10
11
  import type { ResourceUsage } from './config';
11
12
  /**
12
13
  * Serialized error format for cross-thread communication
@@ -65,6 +66,11 @@ export interface SerializedConfig {
65
66
  * Used for defense-in-depth with AST guard
66
67
  */
67
68
  securityLevel: 'STRICT' | 'SECURE' | 'STANDARD' | 'PERMISSIVE';
69
+ /**
70
+ * Validated tool namespaces to bind in the sandbox (`mail.list(args)` calls the tool
71
+ * `mail.list` through the worker's callTool)
72
+ */
73
+ toolNamespaces?: NormalizedToolNamespace[];
68
74
  }
69
75
  /**
70
76
  * Execute code in the worker
@@ -91,6 +97,12 @@ export interface ToolResponseMessage {
91
97
  result?: unknown;
92
98
  /** Error (if failed) */
93
99
  error?: SerializedError;
100
+ /**
101
+ * Set when the error is a failure of the tool itself (its handler threw or rejected), as
102
+ * opposed to the host refusing the call. A script's `callTool(..., { throwOnError: false })`
103
+ * receives only such failures as a result object.
104
+ */
105
+ toolError?: boolean;
94
106
  }
95
107
  /**
96
108
  * Request memory usage report from worker
@@ -10,6 +10,7 @@
10
10
  *
11
11
  * @packageDocumentation
12
12
  */
13
+ import type { NormalizedToolNamespace } from '@enclave-vm/ast';
13
14
  import type { SerializableParentValidationConfig, SerializableSuspiciousPattern } from './types';
14
15
  import type { SecurityLevel } from '../types';
15
16
  /**
@@ -53,6 +54,13 @@ export interface ParentVmBootstrapOptions {
53
54
  memoryLimit?: number;
54
55
  /** Whether to throw errors instead of returning undefined for blocked properties */
55
56
  throwOnBlocked?: boolean;
57
+ /**
58
+ * Maximum number of calls into host functions passed in `globals`
59
+ * @default 1000
60
+ */
61
+ maxGlobalFunctionCalls?: number;
62
+ /** Validated tool namespaces to bind in the inner VM */
63
+ toolNamespaces?: readonly NormalizedToolNamespace[];
56
64
  }
57
65
  /**
58
66
  * Generate the parent VM bootstrap script
package/enclave.d.ts CHANGED
@@ -49,6 +49,7 @@ export declare class Enclave {
49
49
  private readonly scoringGate?;
50
50
  private readonly doubleVmConfig;
51
51
  private readonly customGlobalNames;
52
+ private readonly toolNamespaces;
52
53
  private adapter?;
53
54
  constructor(options?: CreateEnclaveOptions);
54
55
  /**
@@ -67,11 +68,23 @@ export declare class Enclave {
67
68
  /**
68
69
  * Execute AgentScript code
69
70
  *
71
+ * Every error returned obeys `sanitizeStackTraces`, whichever stage raised it.
72
+ *
70
73
  * @param code AgentScript code to execute
71
74
  * @param toolHandler Optional tool handler (overrides constructor config)
72
75
  * @returns Execution result
73
76
  */
74
77
  run<T = unknown>(code: string, toolHandler?: ToolHandler): Promise<ExecutionResult<T>>;
78
+ /**
79
+ * Single exit for returned errors: with `sanitizeStackTraces` on, strip host paths, file
80
+ * locations and frames from the stack, whichever stage (validation, transform, compile,
81
+ * execution, tool call) and adapter produced the error.
82
+ */
83
+ private applyStackTracePolicy;
84
+ /**
85
+ * Transform, validate and execute. `run` applies the stack-trace policy to what this returns.
86
+ */
87
+ private execute;
75
88
  /**
76
89
  * Apply memory tracking transforms to code
77
90
  *