@enclave-vm/core 2.15.2 → 2.16.0

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/types.d.ts CHANGED
@@ -282,7 +282,10 @@ export interface ToolBridgeConfig {
282
282
  }
283
283
  export interface EnclaveConfig {
284
284
  /**
285
- * Maximum execution time in milliseconds
285
+ * Maximum execution time in milliseconds. A tool call in progress when it passes is not cut
286
+ * off and its result is delivered; the script's next tool call then fails with "Execution
287
+ * aborted". A handler that never settles keeps `run()` waiting, so bound slow tools in the
288
+ * handler. @enclave-vm/browser follows the same rules.
286
289
  * Default: 30000 (30 seconds)
287
290
  */
288
291
  timeout?: number;
@@ -309,7 +312,9 @@ export interface EnclaveConfig {
309
312
  */
310
313
  maxIterations?: number;
311
314
  /**
312
- * Sandbox adapter to use
315
+ * Sandbox adapter to use. Takes effect only with `doubleVm: { enabled: false }`: with the double
316
+ * VM on (the default), scripts run in the double VM whatever this says. To run scripts with an
317
+ * adapter of your own, pass `sandboxAdapter`.
313
318
  * Default: 'vm'
314
319
  */
315
320
  adapter?: 'vm' | 'isolated-vm' | 'worker_threads';
@@ -348,8 +353,51 @@ export interface EnclaveConfig {
348
353
  }
349
354
  /**
350
355
  * Tool call handler function
356
+ *
357
+ * Called for every `callTool(name, args)` and every `toolNamespaces` method call that passes the
358
+ * enclave's checks. The script's `callTool` options (see {@link CallToolOptions}) are applied
359
+ * inside the enclave and are not passed to the handler.
351
360
  */
352
361
  export type ToolHandler = (toolName: string, args: Record<string, unknown>) => Promise<unknown>;
362
+ /**
363
+ * Options a script may pass as the third argument of `callTool(name, args, options)`, or as the
364
+ * second argument of a `toolNamespaces` method (`mail.send(args, options)`).
365
+ */
366
+ export interface CallToolOptions {
367
+ /**
368
+ * When `false`, a failing tool does not throw into the script: the call resolves to
369
+ * `{ success: false, error }` instead, and a successful call resolves to `{ success: true, data }`
370
+ * (see {@link ToolCallResult}). A failing tool is one whose handler threw or rejected, or whose
371
+ * result could not be delivered (unsafe or oversized). Refusals by the enclave itself (abort,
372
+ * `maxToolCalls`, rate limit, operation-name and suspicious-sequence checks, invalid or oversized
373
+ * arguments) always throw.
374
+ *
375
+ * @default true
376
+ */
377
+ throwOnError?: boolean;
378
+ }
379
+ /**
380
+ * Error details a script receives for a failing tool when `throwOnError` is `false`.
381
+ * Plain data created inside the sandbox: no stack, no host object.
382
+ */
383
+ export interface ToolCallErrorInfo {
384
+ name: string;
385
+ message: string;
386
+ /** Error code reported by the tool, when it is a string */
387
+ code?: string;
388
+ /** Name of the tool that failed */
389
+ toolName: string;
390
+ }
391
+ /**
392
+ * What `callTool(name, args, { throwOnError: false })` resolves to inside the sandbox.
393
+ */
394
+ export type ToolCallResult<T = unknown> = {
395
+ success: true;
396
+ data: T;
397
+ } | {
398
+ success: false;
399
+ error: ToolCallErrorInfo;
400
+ };
353
401
  /**
354
402
  * Safe runtime context provided to AgentScript code
355
403
  */
@@ -358,7 +406,7 @@ export interface SafeRuntimeContext {
358
406
  * Safe tool call function
359
407
  * Tracks calls, enforces limits, and delegates to the tool handler
360
408
  */
361
- __safe_callTool: (toolName: string, args: Record<string, unknown>) => Promise<unknown>;
409
+ __safe_callTool: (toolName: string, args: Record<string, unknown>, options?: CallToolOptions) => Promise<unknown>;
362
410
  /**
363
411
  * Safe for-of loop iterator
364
412
  * Enforces iteration limits
@@ -412,6 +460,7 @@ import type { ReferenceConfig } from './sidecar/reference-config';
412
460
  import type { ScoringGateConfig, ScoringGateResult } from './scoring/types';
413
461
  import type { WorkerPoolConfig } from './adapters/worker-pool/config';
414
462
  import type { DoubleVmConfig, PartialDoubleVmConfig, ParentValidationConfig } from './double-vm/types';
463
+ import type { NormalizedToolNamespace, ToolNamespaces } from '@enclave-vm/ast';
415
464
  /**
416
465
  * Internal execution context (tracks state during execution)
417
466
  */
@@ -424,7 +473,16 @@ export interface ExecutionContext {
424
473
  sanitizeStackTraces: boolean;
425
474
  maxSanitizeDepth: number;
426
475
  maxSanitizeProperties: number;
476
+ /**
477
+ * Cap on calls into host functions passed in `globals`
478
+ * (defaults to 10 × `maxToolCalls` when absent)
479
+ */
480
+ maxGlobalFunctionCalls?: number;
427
481
  };
482
+ /**
483
+ * Validated tool namespaces to bind in the sandbox (see `CreateEnclaveOptions.toolNamespaces`)
484
+ */
485
+ toolNamespaces?: readonly NormalizedToolNamespace[];
428
486
  /**
429
487
  * Statistics tracker
430
488
  */
@@ -588,16 +646,72 @@ export interface CreateEnclaveOptions extends EnclaveConfig {
588
646
  * Whether to allow functions in custom globals
589
647
  * Default: Determined by securityLevel (false for STRICT/SECURE/STANDARD)
590
648
  *
649
+ * Every call the script makes into such a function goes through the enclave's gate: it is
650
+ * refused once the execution is aborted, counts toward {@link maxGlobalFunctionCalls} (not
651
+ * `maxToolCalls`), shares the double VM's operation rate limit
652
+ * (`doubleVm.parentValidation.maxOperationsPerSecond`) with tool calls, and its return value is
653
+ * sanitized like a tool result (functions, symbols and values beyond the sanitize limits are
654
+ * refused; the script receives a plain-data copy). Errors it throws reach the script as plain
655
+ * errors without the host stack, and calling it with `new` is refused.
656
+ * The suspicious-sequence detectors only look at tool calls: expose tools with
657
+ * {@link toolNamespaces} or `callTool()`, not as functions.
658
+ * The `worker_threads` adapter never passes functions into the sandbox.
659
+ *
660
+ * Functions (and objects with methods, such as class instances) are refused inside arrays,
661
+ * Maps and Sets in `globals`, whatever this option says: the built-in methods of those
662
+ * collections (forEach, iteration, get) hand elements to the script directly, which would skip
663
+ * the gate. Promises, WeakMaps, iterators and generators are refused anywhere in `globals`.
664
+ *
591
665
  * Security Warning: Functions can leak host scope via closures.
592
666
  * Only enable if you understand the security implications.
593
667
  */
594
668
  allowFunctionsInGlobals?: boolean;
669
+ /**
670
+ * Maximum number of calls the script may make into functions passed in `globals`
671
+ * (including functions nested in objects), per execution.
672
+ *
673
+ * Default: 10 × `maxToolCalls`
674
+ */
675
+ maxGlobalFunctionCalls?: number;
676
+ /**
677
+ * Tool namespaces: expose tools to the script as namespaced functions.
678
+ *
679
+ * With `{ mail: ['list', 'send'] }`, `await mail.list(args, options)` inside the sandbox is exactly
680
+ * `await callTool('mail.list', args, options)`: it counts toward `maxToolCalls`, is rate-limited
681
+ * and pattern-checked, its result is sanitized, and it reaches the `toolHandler`. A method can
682
+ * name its tool explicitly: `{ users: { list: 'users:list' } }`. `args` defaults to `{}`.
683
+ *
684
+ * Each namespace is a frozen, null-prototype object created inside the sandbox, so aliasing
685
+ * (`const m = mail; m.list()`) and destructuring work and no host object is exposed.
686
+ *
687
+ * The constructor throws a `TypeError` for names that are not identifiers, prototype keys,
688
+ * names starting with `__`, reserved words and sandbox globals used as namespaces, identifiers
689
+ * the AgentScript validator refuses, namespaces that collide with a custom global, duplicated
690
+ * methods, and empty tool names.
691
+ *
692
+ * @example
693
+ * ```typescript
694
+ * const enclave = new Enclave({
695
+ * toolHandler,
696
+ * toolNamespaces: { mail: ['list', 'send'], users: { get: 'users:get' } },
697
+ * });
698
+ * await enclave.run(`
699
+ * const inbox = await mail.list({ unread: true });
700
+ * const r = await users.get({ id: inbox[0].from }, { throwOnError: false });
701
+ * return r.success ? r.data.name : r.error.message;
702
+ * `);
703
+ * ```
704
+ */
705
+ toolNamespaces?: ToolNamespaces;
595
706
  /**
596
707
  * Whether to sanitize stack traces in error messages
597
708
  * Default: Determined by securityLevel (true for STRICT/SECURE)
598
709
  *
599
710
  * When enabled, file paths and line numbers are removed from stack traces
600
- * to prevent information leakage about the host system.
711
+ * to prevent information leakage about the host system. This applies to every
712
+ * error `run()` returns, whichever stage raised it (validation, transformation,
713
+ * compilation, execution, tool calls) and on every adapter: stack frames become
714
+ * `at [REDACTED]` and paths in the remaining lines are redacted.
601
715
  */
602
716
  sanitizeStackTraces?: boolean;
603
717
  /**
@@ -693,6 +807,24 @@ export interface CreateEnclaveOptions extends EnclaveConfig {
693
807
  * ```
694
808
  */
695
809
  workerPoolConfig?: Partial<WorkerPoolConfig>;
810
+ /**
811
+ * Run scripts with this adapter instead of the double VM and the `adapter` option, for hosts
812
+ * without `node:vm` (a browser worker, an edge runtime): for example an `InterpreterAdapter`,
813
+ * or an adapter that hands the script to `@enclave-vm/browser`.
814
+ *
815
+ * The enclave still validates and transforms every script first, but isolation is then the
816
+ * adapter's job: it receives the transformed code and the `ExecutionContext` (limits, tool
817
+ * handler, stats, abort signal) and must enforce them. The caller owns the adapter:
818
+ * `Enclave.dispose()` does not dispose it, so one adapter can serve several enclaves.
819
+ *
820
+ * @example
821
+ * ```typescript
822
+ * import { Enclave, InterpreterAdapter } from '@enclave-vm/core';
823
+ *
824
+ * const enclave = new Enclave({ sandboxAdapter: new InterpreterAdapter() });
825
+ * ```
826
+ */
827
+ sandboxAdapter?: SandboxAdapter;
696
828
  /**
697
829
  * Secure proxy configuration override
698
830
  *
@@ -766,6 +898,12 @@ export type { WorkerPoolConfig };
766
898
  * @see {@link ParentValidationConfig} Parent VM validation settings
767
899
  */
768
900
  export type { DoubleVmConfig, PartialDoubleVmConfig, ParentValidationConfig };
901
+ /**
902
+ * Re-exported tool namespace types
903
+ * @see {@link ToolNamespaces} The `toolNamespaces` configuration
904
+ * @see {@link NormalizedToolNamespace} A validated namespace
905
+ */
906
+ export type { ToolNamespaces, NormalizedToolNamespace };
769
907
  /**
770
908
  * Default double VM configuration
771
909
  *
@@ -34,6 +34,12 @@ export interface SanitizeOptions {
34
34
  * @default true
35
35
  */
36
36
  allowErrors?: boolean;
37
+ /**
38
+ * Returns the object to check for a Date, Map, Set or RegExp in place of a wrapper around it
39
+ * (the single VM's secure proxy, which has no internal slots). Only builtins are read from the
40
+ * unwrapped object; everything else is still read through `value`.
41
+ */
42
+ unwrap?: (value: object) => object;
37
43
  }
38
44
  /**
39
45
  * Property counter for tracking total properties across recursive calls
package/worker.js CHANGED
@@ -631,6 +631,157 @@ function applyBinary(op, l, r) {
631
631
  }
632
632
  }
633
633
 
634
+ // libs/core/src/stack-trace.ts
635
+ var SENSITIVE_STACK_PATTERNS = [
636
+ // Unix file system paths
637
+ /\/Users\/[^/]+\/[^\s):]*/gi,
638
+ // macOS home directories
639
+ /\/home\/[^/]+\/[^\s):]*/gi,
640
+ // Linux home directories
641
+ /\/var\/[^\s):]*/gi,
642
+ // System var directories
643
+ /\/opt\/[^\s):]*/gi,
644
+ // Optional software
645
+ /\/tmp\/[^\s):]*/gi,
646
+ // Temporary files
647
+ /\/etc\/[^\s):]*/gi,
648
+ // System configuration
649
+ /\/root\/[^\s):]*/gi,
650
+ // Root home directory
651
+ /\/mnt\/[^\s):]*/gi,
652
+ // Mount points
653
+ /\/srv\/[^\s):]*/gi,
654
+ // Service data
655
+ /\/data\/[^\s):]*/gi,
656
+ // Data directories
657
+ /\/app\/[^\s):]*/gi,
658
+ // Application directories
659
+ /\/proc\/[^\s):]*/gi,
660
+ // Process information
661
+ /\/sys\/[^\s):]*/gi,
662
+ // System files
663
+ // Windows paths
664
+ /\\\\[^\s):]*/g,
665
+ // UNC paths
666
+ /[A-Z]:\\[^\s):]+/gi,
667
+ // Windows drive paths
668
+ // URL-based paths
669
+ /file:\/\/[^\s):]+/gi,
670
+ // File URLs
671
+ /webpack:\/\/[^\s):]+/gi,
672
+ // Webpack paths
673
+ /%2F[^\s):]+/gi,
674
+ // URL-encoded paths
675
+ // Package managers and node
676
+ /node_modules\/[^\s):]+/gi,
677
+ // Node modules paths
678
+ /\/nix\/store\/[^\s):]*/gi,
679
+ // Nix store paths
680
+ /\.npm\/[^\s):]*/gi,
681
+ // NPM cache
682
+ /\.yarn\/[^\s):]*/gi,
683
+ // Yarn cache
684
+ /\.pnpm\/[^\s):]*/gi,
685
+ // PNPM cache
686
+ // Container and orchestration
687
+ /\/run\/secrets\/[^\s):]*/gi,
688
+ // Docker/K8s secrets
689
+ /\/var\/run\/[^\s):]*/gi,
690
+ // Runtime directories
691
+ /\/docker\/[^\s):]*/gi,
692
+ // Docker paths
693
+ /\/containers\/[^\s):]*/gi,
694
+ // Container paths
695
+ /\/kubelet\/[^\s):]*/gi,
696
+ // Kubernetes kubelet
697
+ // CI/CD systems
698
+ /\/github\/workspace\/[^\s):]*/gi,
699
+ // GitHub Actions
700
+ /\/runner\/[^\s):]*/gi,
701
+ // GitHub/GitLab runner
702
+ /\/builds\/[^\s):]*/gi,
703
+ // CI builds
704
+ /\/workspace\/[^\s):]*/gi,
705
+ // Generic workspace
706
+ /\/pipeline\/[^\s):]*/gi,
707
+ // CI pipelines
708
+ /\/jenkins\/[^\s):]*/gi,
709
+ // Jenkins
710
+ /\/bamboo\/[^\s):]*/gi,
711
+ // Bamboo
712
+ /\/teamcity\/[^\s):]*/gi,
713
+ // TeamCity
714
+ /\/circleci\/[^\s):]*/gi,
715
+ // CircleCI
716
+ // Cloud providers
717
+ /\/aws\/[^\s):]*/gi,
718
+ // AWS paths
719
+ /\/gcloud\/[^\s):]*/gi,
720
+ // Google Cloud
721
+ /\/azure\/[^\s):]*/gi,
722
+ // Azure paths
723
+ /s3:\/\/[^\s):]+/gi,
724
+ // S3 URIs
725
+ /gs:\/\/[^\s):]+/gi,
726
+ // GCS URIs
727
+ // Secrets and credentials (patterns that might appear in paths or errors)
728
+ /[A-Z0-9]{20,}/g,
729
+ // AWS-style access keys (20+ uppercase chars)
730
+ /sk-[a-zA-Z0-9]{32,}/g,
731
+ // OpenAI/Stripe-style secret keys
732
+ /ghp_[a-zA-Z0-9]{36,}/g,
733
+ // GitHub personal access tokens
734
+ /gho_[a-zA-Z0-9]{36,}/g,
735
+ // GitHub OAuth tokens
736
+ /github_pat_[a-zA-Z0-9_]{22,}/g,
737
+ // GitHub fine-grained tokens
738
+ /xox[baprs]-[a-zA-Z0-9-]+/g,
739
+ // Slack tokens
740
+ /Bearer\s+[a-zA-Z0-9._-]+/gi,
741
+ // Bearer tokens
742
+ /Basic\s+[a-zA-Z0-9+/=]+/gi,
743
+ // Basic auth
744
+ // Internal network info
745
+ /(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
746
+ // Private IPs
747
+ /[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
748
+ // Internal hostnames
749
+ /localhost:\d+/gi,
750
+ // Localhost with port
751
+ /127\.0\.0\.1:\d+/gi,
752
+ // Loopback with port
753
+ // User information
754
+ /\/u\/[^/]+\//gi,
755
+ // User subdirectories
756
+ /~[a-z_][a-z0-9_-]*/gi,
757
+ // Unix user home shorthand
758
+ // Anything else that is still shaped like a location: an absolute path of two or more
759
+ // segments, a URL, or a script location such as `agentscript.js:3` / `index.mjs:10:5`.
760
+ /[a-z][a-z0-9+.-]*:\/\/[^\s)]+/gi,
761
+ // Other URLs (http://host/bundle.js:1:2)
762
+ /(?:\/[\w.@%+-]+){2,}\/?/g,
763
+ // Remaining absolute paths
764
+ /[\w.@-]+\.(?:[cm]?[jt]sx?|json|node|wasm)(?::\d+){1,2}/gi
765
+ // file.ext:line[:column]
766
+ ];
767
+ var FRAME_LINE = /^\s*at\s/;
768
+ var MAX_STACK_LENGTH = 16 * 1024;
769
+ var MAX_LINE_LENGTH = 1e3;
770
+ var REDACTED_FRAME = " at [REDACTED]";
771
+ function redactLine(line) {
772
+ let out = line.length > MAX_LINE_LENGTH ? `${line.slice(0, MAX_LINE_LENGTH)}\u2026` : line;
773
+ for (const pattern of SENSITIVE_STACK_PATTERNS) {
774
+ pattern.lastIndex = 0;
775
+ out = out.replace(pattern, "[REDACTED]");
776
+ }
777
+ return out;
778
+ }
779
+ function sanitizeStackTrace(stack, sanitize = true) {
780
+ if (typeof stack !== "string" || !stack || !sanitize) return stack;
781
+ const bounded = stack.length > MAX_STACK_LENGTH ? stack.slice(0, MAX_STACK_LENGTH) : stack;
782
+ return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
783
+ }
784
+
634
785
  // libs/core/src/adapters/interpreter-adapter.ts
635
786
  var SAFE_GLOBALS = Object.freeze({ Math, JSON });
636
787
  var DEFAULT_MAX_STEPS = 5e6;
@@ -642,6 +793,7 @@ var InterpreterAdapter = class {
642
793
  async execute(code, context) {
643
794
  const startTime = Date.now();
644
795
  let toolCallCount = 0;
796
+ const sanitizeStacks = context.config.sanitizeStackTraces === true;
645
797
  const maxToolCalls = context.config.maxToolCalls ?? Number.POSITIVE_INFINITY;
646
798
  const toolHandler = context.toolHandler ?? context.config.toolHandler;
647
799
  const __safe_callTool = async (name, args) => {
@@ -658,7 +810,7 @@ var InterpreterAdapter = class {
658
810
  try {
659
811
  program = acorn.parse(code, { ecmaVersion: "latest", sourceType: "script" });
660
812
  } catch (error) {
661
- return this.fail(error, startTime, toolCallCount, 0, "SyntaxError");
813
+ return this.fail(error, startTime, toolCallCount, 0, sanitizeStacks, "SyntaxError");
662
814
  }
663
815
  const timeout = context.config.timeout;
664
816
  const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
@@ -683,6 +835,7 @@ var InterpreterAdapter = class {
683
835
  startTime,
684
836
  toolCallCount,
685
837
  interpreter.stepCount,
838
+ sanitizeStacks,
686
839
  "TimeoutError",
687
840
  "EXECUTION_TIMEOUT"
688
841
  );
@@ -694,7 +847,7 @@ var InterpreterAdapter = class {
694
847
  };
695
848
  } catch (error) {
696
849
  const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
697
- return this.fail(error, startTime, toolCallCount, interpreter.stepCount, void 0, code2);
850
+ return this.fail(error, startTime, toolCallCount, interpreter.stepCount, sanitizeStacks, void 0, code2);
698
851
  } finally {
699
852
  if (timer) clearTimeout(timer);
700
853
  if (timeoutHandle) clearTimeout(timeoutHandle);
@@ -706,12 +859,13 @@ var InterpreterAdapter = class {
706
859
  const endTime = Date.now();
707
860
  return { duration: endTime - startTime, toolCallCount, iterationCount, startTime, endTime };
708
861
  }
709
- fail(error, startTime, toolCallCount, iterationCount, name, code) {
862
+ fail(error, startTime, toolCallCount, iterationCount, sanitizeStacks, name, code) {
710
863
  const err = error instanceof Error ? error : new Error(String(error));
864
+ const stack = sanitizeStackTrace(err.stack, sanitizeStacks);
711
865
  const execError = {
712
866
  message: err.message,
713
867
  name: name ?? err.name,
714
- ...err.stack ? { stack: err.stack } : {},
868
+ ...stack ? { stack } : {},
715
869
  ...code ? { code } : {}
716
870
  };
717
871
  return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };