@enclave-vm/core 2.19.1 → 2.20.0-rc.1

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.
Files changed (53) hide show
  1. package/README.md +291 -105
  2. package/adapters/worker-pool/config.d.ts +15 -5
  3. package/adapters/worker-pool/protocol.d.ts +27 -1
  4. package/adapters/worker-pool/worker-pool-adapter.d.ts +24 -0
  5. package/adapters/worker-pool/worker-slot.d.ts +35 -6
  6. package/async-context.d.ts +34 -0
  7. package/babel/babel-wrapper.d.ts +21 -12
  8. package/babel/multi-file-transform.d.ts +3 -0
  9. package/babel/text-scan.d.ts +54 -0
  10. package/bounded-json.d.ts +33 -0
  11. package/deadline-guard.d.ts +16 -0
  12. package/dynamic-import.d.ts +25 -0
  13. package/enclave-options.d.ts +62 -0
  14. package/enclave.d.ts +35 -8
  15. package/esm/index.mjs +5520 -917
  16. package/esm/worker.mjs +2777 -195
  17. package/execution-deadline.d.ts +6 -0
  18. package/global-function-gate.d.ts +34 -1
  19. package/index.d.ts +3 -3
  20. package/index.js +5562 -959
  21. package/interpreter/interpreter.d.ts +207 -10
  22. package/memory-tracker.d.ts +7 -0
  23. package/package.json +3 -3
  24. package/portable-enclave.d.ts +51 -0
  25. package/portable-globals.d.ts +2 -0
  26. package/realm-airlock.d.ts +6 -1
  27. package/realm-memory.d.ts +89 -0
  28. package/realm-regex-backstop.d.ts +18 -0
  29. package/realm-stack.d.ts +25 -0
  30. package/safe-runtime.d.ts +2 -0
  31. package/sandbox-rejections.d.ts +3 -1
  32. package/scoring/feature-extractor.d.ts +52 -1
  33. package/scoring/index.d.ts +2 -1
  34. package/scoring/scorers/index.d.ts +2 -1
  35. package/scoring/scorers/local-llm.scorer.d.ts +9 -3
  36. package/scoring/scorers/progressive.scorer.d.ts +28 -1
  37. package/scoring/scorers/rule-based.scorer.d.ts +11 -1
  38. package/scoring/scoring-gate.d.ts +2 -0
  39. package/scoring/types.d.ts +36 -8
  40. package/secure-proxy.d.ts +17 -3
  41. package/session/session.d.ts +8 -1
  42. package/session-types.d.ts +6 -4
  43. package/sidecar/index.d.ts +1 -1
  44. package/sidecar/reference-config.d.ts +18 -1
  45. package/sidecar/reference-resolver.d.ts +26 -3
  46. package/sidecar/reference-sidecar.d.ts +37 -0
  47. package/src/adapters/worker-pool/package.json +3 -3
  48. package/src/adapters/worker-pool/worker-script.js +2835 -465
  49. package/thrown-value.d.ts +59 -0
  50. package/types.d.ts +85 -19
  51. package/value-sanitizer.d.ts +6 -1
  52. package/worker.d.ts +2 -0
  53. package/worker.js +2767 -195
@@ -0,0 +1,59 @@
1
+ /**
2
+ * What a thrown value says about itself, as text of the host
3
+ *
4
+ * A script can throw anything: an object whose `message` is another object, a function, a Proxy,
5
+ * `null`. Whatever it is, the caller of `run()` gets `result.error` with `name`, `message` and
6
+ * `stack` as the strings they are declared to be, of bounded length: an application logs them,
7
+ * concatenates them and serializes the result, and none of that may run code of the script or
8
+ * depend on the size of what was thrown.
9
+ *
10
+ * A member of the thrown value is read once and used only if it is a string. Nothing is called
11
+ * on the value and nothing is converted: an object in the place of a string is not asked for its
12
+ * text, it is left out.
13
+ *
14
+ * @packageDocumentation
15
+ */
16
+ /** The longest `name` reported for a thrown value. */
17
+ export declare const MAX_THROWN_NAME_LENGTH = 256;
18
+ /** The longest `message` reported for a thrown value. */
19
+ export declare const MAX_THROWN_MESSAGE_LENGTH: number;
20
+ /** The longest `stack` taken from a thrown value (the stack-trace policy cuts further). */
21
+ export declare const MAX_THROWN_STACK_LENGTH: number;
22
+ /** What {@link describeThrown} could read. A member that was not a string is absent. */
23
+ export interface ThrownDescription {
24
+ name?: string;
25
+ message?: string;
26
+ stack?: string;
27
+ }
28
+ /**
29
+ * The name, message and stack of a thrown value, each only if the value holds it as a string.
30
+ *
31
+ * - A thrown string is the message.
32
+ * - `null`, `undefined` and the other primitives are named in the message.
33
+ * - An object or function is asked for `name`, `message` and `stack`; what is not a string there
34
+ * is absent from the result, and the caller puts its own default in its place.
35
+ */
36
+ export declare function describeThrown(thrown: unknown): ThrownDescription;
37
+ /**
38
+ * Whether a thrown value carries the code of the memory-limit error (read once, nothing called).
39
+ * That alone does not make it one: the caller also asks its memory tracker.
40
+ */
41
+ export declare function isMemoryLimitPayload(thrown: unknown): boolean;
42
+ /** The message for a thrown object or function that has no message of its own. */
43
+ export declare const THROWN_WITHOUT_MESSAGE = "The script threw a value that is not an error";
44
+ /**
45
+ * `result.error` as plain text, whoever built it: `name` and `message` are strings of bounded
46
+ * length, `stack` and `code` are strings or absent. An adapter that is not one of the built-in
47
+ * ones (`sandboxAdapter`) hands back what it likes; this is applied to every result.
48
+ */
49
+ export declare function normalizeErrorText<T extends {
50
+ name?: unknown;
51
+ message?: unknown;
52
+ stack?: unknown;
53
+ code?: unknown;
54
+ }>(error: T): T & {
55
+ name: string;
56
+ message: string;
57
+ stack?: string;
58
+ code?: string;
59
+ };
package/types.d.ts CHANGED
@@ -125,17 +125,18 @@ export interface SecurityLevelConfig {
125
125
  */
126
126
  sanitizeStackTraces: boolean;
127
127
  /**
128
- * Whether to block Date.now() and performance timing APIs
129
- * (prevents timing attacks)
128
+ * Descriptive only: nothing in the runtime reads this value, and setting it changes nothing.
129
+ * What a script can reach of `Date` and timing APIs follows from the realm's globals.
130
130
  */
131
131
  blockTimingAPIs: boolean;
132
132
  /**
133
- * Whether to allow while/do-while loops
134
- * (false = only bounded for/for-of loops allowed)
133
+ * Descriptive only: nothing in the runtime reads this value, and setting it changes nothing.
134
+ * Which loops a script may use is decided by the AST preset (`preset`).
135
135
  */
136
136
  allowUnboundedLoops: boolean;
137
137
  /**
138
- * Whether to check for Unicode security attacks in code
138
+ * Descriptive only: nothing in the runtime reads this value, and setting it changes nothing.
139
+ * The Unicode checks are those of the pre-scanner preset the validation runs with.
139
140
  */
140
141
  unicodeSecurityCheck: boolean;
141
142
  /**
@@ -227,7 +228,9 @@ export interface ExecutionStats {
227
228
  * tracked during execution. Tracking monitors String and Array allocations.
228
229
  *
229
230
  * Note: This is an estimate based on allocation tracking, not actual V8 heap usage.
230
- * For precise memory isolation, use the worker_threads adapter with `--max-old-space-size`.
231
+ * Where the engine's own bound is needed, use the `worker_threads` adapter: each worker has a
232
+ * heap limit of the engine (`workerPoolConfig.memoryLimitPerWorker`). Do not set the process
233
+ * flag `--max-old-space-size` for that: it replaces the limits of the workers.
231
234
  */
232
235
  memoryUsage?: number;
233
236
  /**
@@ -296,10 +299,13 @@ export interface EnclaveConfig {
296
299
  * When set, the VM adapter tracks String and Array allocations and throws
297
300
  * a MemoryLimitError if the limit is exceeded. Tracking adds ~5-10% overhead.
298
301
  *
299
- * Note: This is enforced via allocation tracking, not V8 heap limits.
300
- * For precise memory isolation, use the worker_threads adapter.
302
+ * Note: This is enforced via allocation tracking, not V8 heap limits. The VM adapter counts
303
+ * operations that make text and arrays grow; copies, objects, Maps and Sets are not counted.
304
+ * The portable interpreter additionally charges copied host-function results and tool responses
305
+ * by serialized size.
306
+ * For the engine's own limit, use the worker_threads adapter.
301
307
  *
302
- * Default: 128 * 1024 * 1024 (128MB)
308
+ * Default: 1 * 1024 * 1024 (1 MB); 0 switches the tracking off
303
309
  */
304
310
  memoryLimit?: number;
305
311
  /**
@@ -470,7 +476,7 @@ import type { ReferenceConfig } from './sidecar/reference-config';
470
476
  import type { ScoringGateConfig, ScoringGateResult } from './scoring/types';
471
477
  import type { WorkerPoolConfig } from './adapters/worker-pool/config';
472
478
  import type { DoubleVmConfig, PartialDoubleVmConfig, ParentValidationConfig } from './double-vm/types';
473
- import type { NormalizedToolNamespace, ToolNamespaces } from '@enclave-vm/ast';
479
+ import type { NormalizedToolNamespace, PartialPreScannerConfig, PreScannerPresetLevel, ToolNamespaces } from '@enclave-vm/ast';
474
480
  import type { ConsoleHandler, ConsoleLevel } from './console-handler';
475
481
  import type { HostActivity } from './execution-deadline';
476
482
  /**
@@ -517,6 +523,14 @@ export interface ExecutionContext {
517
523
  * Tool handler
518
524
  */
519
525
  toolHandler?: ToolHandler;
526
+ /** Synchronous policy: return true to allow the copied request, or throw/return false to refuse. */
527
+ beforeToolCall?: (name: string, args: Record<string, unknown>) => boolean;
528
+ /** Synchronous policy: return true before a custom host global function may run. */
529
+ beforeGlobalCall?: () => boolean;
530
+ /** Called when a successful host tool result is refused before it reaches the script. */
531
+ onToolBridgeFailure?: () => void;
532
+ /** Optional host limit on the JSON bytes of one sanitized tool result. */
533
+ maxToolResultBytes?: number;
520
534
  /**
521
535
  * What the host has in flight for this execution: tool calls and async functions from
522
536
  * `globals` (see ./execution-deadline). Set by the enclave, which ends the execution once the
@@ -599,6 +613,12 @@ export interface ReferenceSidecarOptions {
599
613
  * @default Determined by securityLevel
600
614
  */
601
615
  maxResolvedSize?: number;
616
+ /**
617
+ * Maximum size, in bytes, of everything one execution resolves for its tool calls in total.
618
+ * A stored value counts once, a concatenation of references every time it is built.
619
+ * @default Twice `maxTotalSize`
620
+ */
621
+ maxTotalResolvedSize?: number;
602
622
  /**
603
623
  * Whether to allow composite handles from string concatenation
604
624
  * If false, concatenating references throws an error
@@ -667,6 +687,49 @@ export interface CreateEnclaveOptions extends EnclaveConfig {
667
687
  * ```
668
688
  */
669
689
  preset?: AstPreset;
690
+ /**
691
+ * The pre-scanner (layer 0): what is checked in the text of a script before anything parses
692
+ * it. Its size, the length and number of its lines, how deep it nests, its regular-expression
693
+ * and string literals, and Unicode that hides code.
694
+ *
695
+ * By default it runs with the pre-scanner preset named like the AST preset (`preset`):
696
+ * `agentscript`, `strict`, `secure`, `standard` or `permissive`. The `babel` preset runs with
697
+ * `standard`. The `agentscript` pre-scanner takes scripts of up to 100 KB in at most 1,000
698
+ * lines of at most 2,000 characters, string literals of up to 10 KB each, no
699
+ * regular-expression literal, and no bidirectional or invisible control character.
700
+ *
701
+ * - `preset` picks another pre-scanner preset.
702
+ * - `config` changes single limits of the preset in force (see `PreScannerConfig` of
703
+ * `@enclave-vm/ast`); the pre-scanner's own absolute maximums still hold.
704
+ *
705
+ * A host that stores large string literals in the reference sidecar, or that runs scripts
706
+ * above these sizes, sets the limits it needs here. With `validate: false` the pre-scanner
707
+ * does not run; the maximum size of a script (5,242,880 characters) holds in any case.
708
+ *
709
+ * @example
710
+ * ```typescript
711
+ * // The limits enclaves had before 2.19.2, whatever the AST preset
712
+ * const enclave = new Enclave({ preScan: { preset: 'standard' } });
713
+ *
714
+ * // The agentscript pre-scanner with room for larger string literals. The limit on one
715
+ * // literal and the limit on all literals together are separate: raise both. (A line is at
716
+ * // most 100,000 characters under any configuration.)
717
+ * const enclave = new Enclave({
718
+ * preScan: {
719
+ * config: {
720
+ * maxInputSize: 1024 * 1024,
721
+ * maxLineLength: 100000,
722
+ * maxStringLength: 512 * 1024,
723
+ * maxTotalStringContent: 1024 * 1024,
724
+ * },
725
+ * },
726
+ * });
727
+ * ```
728
+ */
729
+ preScan?: {
730
+ preset?: PreScannerPresetLevel;
731
+ config?: PartialPreScannerConfig;
732
+ };
670
733
  /**
671
734
  * Whether to validate AgentScript code before execution
672
735
  * Default: true
@@ -787,7 +850,7 @@ export interface CreateEnclaveOptions extends EnclaveConfig {
787
850
  *
788
851
  * Supported by the double VM (default), the `vm` adapter and the `worker_threads` adapter. A
789
852
  * `sandboxAdapter` receives the handler as `ExecutionContext.consoleHandler`; the built-in
790
- * `InterpreterAdapter` has no `console`, so a script that uses it fails there.
853
+ * `InterpreterAdapter` gives the script a `console` when a handler is set, and none without one.
791
854
  *
792
855
  * @example
793
856
  * ```typescript
@@ -825,10 +888,12 @@ export interface CreateEnclaveOptions extends EnclaveConfig {
825
888
  * - Extracts large strings from code and stores them in a sidecar
826
889
  * - Transforms concatenation to detect reference IDs
827
890
  * - Resolves references at the callTool boundary
828
- * - Lifts large tool results back to the sidecar
891
+ * - Stores a tool result that is one large string in the sidecar and hands the script its
892
+ * reference (a string inside an object or an array is not stored)
829
893
  *
830
- * This enables scripts to manipulate large data (videos, PDFs, images)
831
- * without loading them into the JavaScript sandbox.
894
+ * A script can pass such data (videos, PDFs, images) from one tool to another, and concatenate
895
+ * references where the level allows it, without the data entering the JavaScript sandbox. It
896
+ * cannot read or change the data: nothing is resolved for the script itself.
832
897
  *
833
898
  * @example
834
899
  * ```typescript
@@ -845,11 +910,11 @@ export interface CreateEnclaveOptions extends EnclaveConfig {
845
910
  /**
846
911
  * AI Scoring Gate configuration
847
912
  *
848
- * Adds semantic security analysis that detects attack patterns
849
- * beyond what static AST validation can catch:
913
+ * A heuristic that scores what a script's tool calls look like, as a signal on top of the
914
+ * AST validation, not a boundary:
850
915
  * - Data exfiltration patterns (list→send)
851
916
  * - Excessive access (high limits, wildcards)
852
- * - Fan-out attacks (tool calls in loops)
917
+ * - Fan-out (tool calls in loops)
853
918
  * - Sensitive data access (passwords, tokens)
854
919
  *
855
920
  * Runs AFTER AST validation but BEFORE code execution.
@@ -864,7 +929,7 @@ export interface CreateEnclaveOptions extends EnclaveConfig {
864
929
  * },
865
930
  * });
866
931
  *
867
- * // External API scorer (best detection)
932
+ * // External API scorer (the score is whatever the service returns)
868
933
  * const enclave = new Enclave({
869
934
  * scoringGate: {
870
935
  * scorer: 'external-api',
@@ -881,7 +946,8 @@ export interface CreateEnclaveOptions extends EnclaveConfig {
881
946
  * Worker Pool Adapter configuration
882
947
  *
883
948
  * Only used when adapter is set to 'worker_threads'.
884
- * Provides OS-level memory isolation via worker threads with:
949
+ * Runs each script in a worker thread: an isolate of the engine with its own heap limit, in
950
+ * the same process (not a boundary of the operating system), with:
885
951
  * - Pool management (min/max workers, scaling)
886
952
  * - Memory monitoring and enforcement
887
953
  * - Hard halt capability via worker.terminate()
@@ -48,7 +48,12 @@ interface PropertyCounter {
48
48
  count: number;
49
49
  }
50
50
  /**
51
- * Internal context for tracking visited objects (circular reference detection)
51
+ * Internal context of one sanitization: the property count, and the objects on the way from the
52
+ * root down to the value being copied (circular reference detection).
53
+ *
54
+ * Only an object that contains itself is a circle. An object that is referenced twice without
55
+ * containing itself is copied twice: each copy counts against the property limit, so a value
56
+ * that is small as a graph and large as a tree is bounded like any other large value.
52
57
  */
53
58
  interface SanitizeContext {
54
59
  propCount: PropertyCounter;
package/worker.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  export { InterpreterAdapter } from './adapters/interpreter-adapter';
2
2
  export type { InterpreterAdapterOptions } from './adapters/interpreter-adapter';
3
+ export { PortableEnclave, AgentScriptRunner } from './portable-enclave';
4
+ export type { PortableEnclaveOptions, PortableRunOptions, AgentScriptRunnerOptions } from './portable-enclave';
3
5
  export { Interpreter, InterpreterError, StepLimitError } from './interpreter/interpreter';
4
6
  export type { InterpreterOptions } from './interpreter/interpreter';
5
7
  export type { ExecutionContext, ExecutionResult, ExecutionError, ExecutionStats, ToolHandler } from './types';