@enclave-vm/core 0.0.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 (169) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +732 -0
  3. package/SECURITY-AUDIT.md +916 -0
  4. package/package.json +59 -0
  5. package/src/adapters/vm-adapter.d.ts +32 -0
  6. package/src/adapters/vm-adapter.js +1140 -0
  7. package/src/adapters/vm-adapter.js.map +1 -0
  8. package/src/adapters/worker-pool/config.d.ts +149 -0
  9. package/src/adapters/worker-pool/config.js +129 -0
  10. package/src/adapters/worker-pool/config.js.map +1 -0
  11. package/src/adapters/worker-pool/errors.d.ts +109 -0
  12. package/src/adapters/worker-pool/errors.js +181 -0
  13. package/src/adapters/worker-pool/errors.js.map +1 -0
  14. package/src/adapters/worker-pool/execution-queue.d.ts +85 -0
  15. package/src/adapters/worker-pool/execution-queue.js +179 -0
  16. package/src/adapters/worker-pool/execution-queue.js.map +1 -0
  17. package/src/adapters/worker-pool/index.d.ts +48 -0
  18. package/src/adapters/worker-pool/index.js +73 -0
  19. package/src/adapters/worker-pool/index.js.map +1 -0
  20. package/src/adapters/worker-pool/memory-monitor.d.ts +106 -0
  21. package/src/adapters/worker-pool/memory-monitor.js +184 -0
  22. package/src/adapters/worker-pool/memory-monitor.js.map +1 -0
  23. package/src/adapters/worker-pool/protocol.d.ts +314 -0
  24. package/src/adapters/worker-pool/protocol.js +143 -0
  25. package/src/adapters/worker-pool/protocol.js.map +1 -0
  26. package/src/adapters/worker-pool/rate-limiter.d.ts +60 -0
  27. package/src/adapters/worker-pool/rate-limiter.js +101 -0
  28. package/src/adapters/worker-pool/rate-limiter.js.map +1 -0
  29. package/src/adapters/worker-pool/safe-deserialize.d.ts +50 -0
  30. package/src/adapters/worker-pool/safe-deserialize.js +141 -0
  31. package/src/adapters/worker-pool/safe-deserialize.js.map +1 -0
  32. package/src/adapters/worker-pool/worker-pool-adapter.d.ts +84 -0
  33. package/src/adapters/worker-pool/worker-pool-adapter.js +506 -0
  34. package/src/adapters/worker-pool/worker-pool-adapter.js.map +1 -0
  35. package/src/adapters/worker-pool/worker-script.d.ts +12 -0
  36. package/src/adapters/worker-pool/worker-script.js +770 -0
  37. package/src/adapters/worker-pool/worker-script.js.map +1 -0
  38. package/src/adapters/worker-pool/worker-slot.d.ts +116 -0
  39. package/src/adapters/worker-pool/worker-slot.js +301 -0
  40. package/src/adapters/worker-pool/worker-slot.js.map +1 -0
  41. package/src/babel/babel-wrapper.d.ts +118 -0
  42. package/src/babel/babel-wrapper.js +395 -0
  43. package/src/babel/babel-wrapper.js.map +1 -0
  44. package/src/babel/index.d.ts +9 -0
  45. package/src/babel/index.js +17 -0
  46. package/src/babel/index.js.map +1 -0
  47. package/src/babel/multi-file-transform.d.ts +122 -0
  48. package/src/babel/multi-file-transform.js +344 -0
  49. package/src/babel/multi-file-transform.js.map +1 -0
  50. package/src/double-vm/double-vm-wrapper.d.ts +65 -0
  51. package/src/double-vm/double-vm-wrapper.js +523 -0
  52. package/src/double-vm/double-vm-wrapper.js.map +1 -0
  53. package/src/double-vm/index.d.ts +31 -0
  54. package/src/double-vm/index.js +34 -0
  55. package/src/double-vm/index.js.map +1 -0
  56. package/src/double-vm/parent-vm-bootstrap.d.ts +63 -0
  57. package/src/double-vm/parent-vm-bootstrap.js +1695 -0
  58. package/src/double-vm/parent-vm-bootstrap.js.map +1 -0
  59. package/src/double-vm/suspicious-patterns.d.ts +57 -0
  60. package/src/double-vm/suspicious-patterns.js +304 -0
  61. package/src/double-vm/suspicious-patterns.js.map +1 -0
  62. package/src/double-vm/types.d.ts +178 -0
  63. package/src/double-vm/types.js +11 -0
  64. package/src/double-vm/types.js.map +1 -0
  65. package/src/double-vm/wrap-adapter.d.ts +36 -0
  66. package/src/double-vm/wrap-adapter.js +59 -0
  67. package/src/double-vm/wrap-adapter.js.map +1 -0
  68. package/src/enclave.d.ts +159 -0
  69. package/src/enclave.js +671 -0
  70. package/src/enclave.js.map +1 -0
  71. package/src/globals-validator.d.ts +80 -0
  72. package/src/globals-validator.js +206 -0
  73. package/src/globals-validator.js.map +1 -0
  74. package/src/index.d.ts +29 -0
  75. package/src/index.js +130 -0
  76. package/src/index.js.map +1 -0
  77. package/src/memory-proxy.d.ts +69 -0
  78. package/src/memory-proxy.js +310 -0
  79. package/src/memory-proxy.js.map +1 -0
  80. package/src/memory-tracker.d.ts +170 -0
  81. package/src/memory-tracker.js +230 -0
  82. package/src/memory-tracker.js.map +1 -0
  83. package/src/safe-error.d.ts +18 -0
  84. package/src/safe-error.js +76 -0
  85. package/src/safe-error.js.map +1 -0
  86. package/src/safe-runtime.d.ts +72 -0
  87. package/src/safe-runtime.js +656 -0
  88. package/src/safe-runtime.js.map +1 -0
  89. package/src/scoring/cache.d.ts +68 -0
  90. package/src/scoring/cache.js +158 -0
  91. package/src/scoring/cache.js.map +1 -0
  92. package/src/scoring/feature-extractor.d.ts +61 -0
  93. package/src/scoring/feature-extractor.js +366 -0
  94. package/src/scoring/feature-extractor.js.map +1 -0
  95. package/src/scoring/index.d.ts +33 -0
  96. package/src/scoring/index.js +53 -0
  97. package/src/scoring/index.js.map +1 -0
  98. package/src/scoring/scorer.interface.d.ts +65 -0
  99. package/src/scoring/scorer.interface.js +49 -0
  100. package/src/scoring/scorer.interface.js.map +1 -0
  101. package/src/scoring/scorers/disabled.scorer.d.ts +19 -0
  102. package/src/scoring/scorers/disabled.scorer.js +34 -0
  103. package/src/scoring/scorers/disabled.scorer.js.map +1 -0
  104. package/src/scoring/scorers/external-api.scorer.d.ts +29 -0
  105. package/src/scoring/scorers/external-api.scorer.js +141 -0
  106. package/src/scoring/scorers/external-api.scorer.js.map +1 -0
  107. package/src/scoring/scorers/index.d.ts +10 -0
  108. package/src/scoring/scorers/index.js +22 -0
  109. package/src/scoring/scorers/index.js.map +1 -0
  110. package/src/scoring/scorers/local-llm.scorer.d.ts +116 -0
  111. package/src/scoring/scorers/local-llm.scorer.js +474 -0
  112. package/src/scoring/scorers/local-llm.scorer.js.map +1 -0
  113. package/src/scoring/scorers/progressive.scorer.d.ts +77 -0
  114. package/src/scoring/scorers/progressive.scorer.js +199 -0
  115. package/src/scoring/scorers/progressive.scorer.js.map +1 -0
  116. package/src/scoring/scorers/rule-based.scorer.d.ts +66 -0
  117. package/src/scoring/scorers/rule-based.scorer.js +316 -0
  118. package/src/scoring/scorers/rule-based.scorer.js.map +1 -0
  119. package/src/scoring/scoring-gate.d.ts +76 -0
  120. package/src/scoring/scoring-gate.js +246 -0
  121. package/src/scoring/scoring-gate.js.map +1 -0
  122. package/src/scoring/types.d.ts +690 -0
  123. package/src/scoring/types.js +107 -0
  124. package/src/scoring/types.js.map +1 -0
  125. package/src/secure-proxy.d.ts +157 -0
  126. package/src/secure-proxy.js +609 -0
  127. package/src/secure-proxy.js.map +1 -0
  128. package/src/session/channels/embedded-channel.d.ts +76 -0
  129. package/src/session/channels/embedded-channel.js +130 -0
  130. package/src/session/channels/embedded-channel.js.map +1 -0
  131. package/src/session/channels/index.d.ts +9 -0
  132. package/src/session/channels/index.js +14 -0
  133. package/src/session/channels/index.js.map +1 -0
  134. package/src/session/index.d.ts +15 -0
  135. package/src/session/index.js +27 -0
  136. package/src/session/index.js.map +1 -0
  137. package/src/session/session-emitter.d.ts +119 -0
  138. package/src/session/session-emitter.js +253 -0
  139. package/src/session/session-emitter.js.map +1 -0
  140. package/src/session/session-state-machine.d.ts +108 -0
  141. package/src/session/session-state-machine.js +182 -0
  142. package/src/session/session-state-machine.js.map +1 -0
  143. package/src/session/session.d.ts +135 -0
  144. package/src/session/session.js +398 -0
  145. package/src/session/session.js.map +1 -0
  146. package/src/session-types.d.ts +313 -0
  147. package/src/session-types.js +39 -0
  148. package/src/session-types.js.map +1 -0
  149. package/src/sidecar/index.d.ts +12 -0
  150. package/src/sidecar/index.js +31 -0
  151. package/src/sidecar/index.js.map +1 -0
  152. package/src/sidecar/reference-config.d.ts +81 -0
  153. package/src/sidecar/reference-config.js +118 -0
  154. package/src/sidecar/reference-config.js.map +1 -0
  155. package/src/sidecar/reference-resolver.d.ts +115 -0
  156. package/src/sidecar/reference-resolver.js +262 -0
  157. package/src/sidecar/reference-resolver.js.map +1 -0
  158. package/src/sidecar/reference-sidecar.d.ts +161 -0
  159. package/src/sidecar/reference-sidecar.js +226 -0
  160. package/src/sidecar/reference-sidecar.js.map +1 -0
  161. package/src/tool-bridge.d.ts +4 -0
  162. package/src/tool-bridge.js +306 -0
  163. package/src/tool-bridge.js.map +1 -0
  164. package/src/types.d.ts +775 -0
  165. package/src/types.js +187 -0
  166. package/src/types.js.map +1 -0
  167. package/src/value-sanitizer.d.ts +133 -0
  168. package/src/value-sanitizer.js +421 -0
  169. package/src/value-sanitizer.js.map +1 -0
package/src/types.d.ts ADDED
@@ -0,0 +1,775 @@
1
+ /**
2
+ * Enclave Types and Interfaces
3
+ *
4
+ * Core types for the AgentScript execution environment.
5
+ *
6
+ * @packageDocumentation
7
+ */
8
+ /**
9
+ * Security levels for Enclave configuration
10
+ *
11
+ * These levels provide pre-configured security profiles that balance
12
+ * functionality against security risk. Higher levels are more restrictive.
13
+ *
14
+ * @example
15
+ * ```typescript
16
+ * // Use STRICT for untrusted AI-generated code
17
+ * const enclave = new Enclave({ securityLevel: 'STRICT' });
18
+ *
19
+ * // Use STANDARD for trusted internal tools
20
+ * const enclave = new Enclave({ securityLevel: 'STANDARD' });
21
+ * ```
22
+ */
23
+ export type SecurityLevel = 'STRICT' | 'SECURE' | 'STANDARD' | 'PERMISSIVE';
24
+ /**
25
+ * AST validation preset for code validation
26
+ *
27
+ * Controls which validation rules are applied to code before execution.
28
+ * Each preset is designed for different security/functionality trade-offs.
29
+ *
30
+ * @example
31
+ * ```typescript
32
+ * // Use agentscript preset for AI-generated tool orchestration (default)
33
+ * const enclave = new Enclave({ preset: 'agentscript' });
34
+ *
35
+ * // Use strict preset for maximum security
36
+ * const enclave = new Enclave({ preset: 'strict' });
37
+ *
38
+ * // Use babel preset for TSX/JSX transformation support
39
+ * const enclave = new Enclave({ preset: 'babel' });
40
+ * ```
41
+ */
42
+ export type AstPreset = 'agentscript' | 'strict' | 'secure' | 'standard' | 'permissive' | 'babel';
43
+ /**
44
+ * Secure proxy configuration per security level
45
+ *
46
+ * Controls which dangerous properties are blocked at runtime via JavaScript Proxies.
47
+ * This provides defense-in-depth against computed property access attacks that
48
+ * bypass static AST analysis.
49
+ */
50
+ export interface SecureProxyLevelConfig {
51
+ /**
52
+ * Whether to block 'constructor' property access
53
+ * Prevents: obj['const' + 'ructor'] attacks for code execution
54
+ * @default true (blocks constructor for security)
55
+ *
56
+ * Set to false in PERMISSIVE mode for development/debugging
57
+ */
58
+ blockConstructor: boolean;
59
+ /**
60
+ * Whether to block prototype access (__proto__, prototype)
61
+ * Prevents: prototype chain manipulation attacks
62
+ * @default true (always recommended to keep true)
63
+ */
64
+ blockPrototype: boolean;
65
+ /**
66
+ * Whether to block legacy getter/setter methods
67
+ * Blocks: __defineGetter__, __defineSetter__, __lookupGetter__, __lookupSetter__
68
+ * @default true
69
+ */
70
+ blockLegacyAccessors: boolean;
71
+ /**
72
+ * Maximum depth for recursive proxying
73
+ * Limits how deep nested objects are wrapped in secure proxies
74
+ * @default 10
75
+ */
76
+ proxyMaxDepth: number;
77
+ /**
78
+ * Whether to throw an error when blocked properties are accessed.
79
+ *
80
+ * Security level defaults:
81
+ * - STRICT/SECURE/STANDARD: `true` (throws error)
82
+ * - PERMISSIVE: `false` (returns undefined)
83
+ *
84
+ * When true, accessing blocked properties like 'constructor', '__proto__',
85
+ * 'prototype' will throw a SecurityError instead of returning undefined.
86
+ * This makes security violations explicit and easier to detect.
87
+ *
88
+ * **Breaking change note**: Prior versions returned undefined for all security levels.
89
+ * Set to `false` for backward compatibility (returns undefined for blocked properties).
90
+ */
91
+ throwOnBlocked: boolean;
92
+ }
93
+ /**
94
+ * Security level configuration presets
95
+ *
96
+ * Each level adjusts:
97
+ * - Resource limits (timeout, iterations, tool calls)
98
+ * - Validation strictness
99
+ * - Stack trace sanitization
100
+ * - Value sanitization depth
101
+ */
102
+ export interface SecurityLevelConfig {
103
+ /**
104
+ * Maximum execution time in milliseconds
105
+ */
106
+ timeout: number;
107
+ /**
108
+ * Maximum number of loop iterations
109
+ */
110
+ maxIterations: number;
111
+ /**
112
+ * Maximum number of tool calls
113
+ */
114
+ maxToolCalls: number;
115
+ /**
116
+ * Maximum depth for value sanitization
117
+ */
118
+ maxSanitizeDepth: number;
119
+ /**
120
+ * Maximum properties per object in sanitized values
121
+ */
122
+ maxSanitizeProperties: number;
123
+ /**
124
+ * Whether to sanitize stack traces (remove file paths, line numbers)
125
+ */
126
+ sanitizeStackTraces: boolean;
127
+ /**
128
+ * Whether to block Date.now() and performance timing APIs
129
+ * (prevents timing attacks)
130
+ */
131
+ blockTimingAPIs: boolean;
132
+ /**
133
+ * Whether to allow while/do-while loops
134
+ * (false = only bounded for/for-of loops allowed)
135
+ */
136
+ allowUnboundedLoops: boolean;
137
+ /**
138
+ * Whether to check for Unicode security attacks in code
139
+ */
140
+ unicodeSecurityCheck: boolean;
141
+ /**
142
+ * Whether to allow functions in custom globals
143
+ */
144
+ allowFunctionsInGlobals: boolean;
145
+ /**
146
+ * Maximum total console output in bytes
147
+ * Prevents I/O flood attacks via console.log spam
148
+ */
149
+ maxConsoleOutputBytes: number;
150
+ /**
151
+ * Maximum number of console calls (log, warn, error, info)
152
+ * Prevents I/O flood attacks via excessive console calls
153
+ */
154
+ maxConsoleCalls: number;
155
+ /**
156
+ * Secure proxy configuration for runtime property access protection
157
+ * Controls which dangerous properties are blocked via JavaScript Proxies
158
+ */
159
+ secureProxy: SecureProxyLevelConfig;
160
+ }
161
+ /**
162
+ * Pre-defined security level configurations
163
+ */
164
+ export declare const SECURITY_LEVEL_CONFIGS: Record<SecurityLevel, SecurityLevelConfig>;
165
+ /**
166
+ * Result of executing AgentScript code
167
+ */
168
+ export interface ExecutionResult<T = unknown> {
169
+ /**
170
+ * Whether execution was successful
171
+ */
172
+ success: boolean;
173
+ /**
174
+ * Return value from the script (if successful)
175
+ */
176
+ value?: T;
177
+ /**
178
+ * Error that occurred during execution (if failed)
179
+ */
180
+ error?: ExecutionError;
181
+ /**
182
+ * Execution statistics
183
+ */
184
+ stats: ExecutionStats;
185
+ /**
186
+ * AI scoring result (if scoring gate is enabled)
187
+ */
188
+ scoringResult?: ScoringGateResult;
189
+ }
190
+ /**
191
+ * Execution error details
192
+ */
193
+ export interface ExecutionError {
194
+ /**
195
+ * Error message
196
+ */
197
+ message: string;
198
+ /**
199
+ * Error name/type
200
+ */
201
+ name: string;
202
+ /**
203
+ * Stack trace (if available)
204
+ */
205
+ stack?: string;
206
+ /**
207
+ * Error code (for structured errors)
208
+ */
209
+ code?: string;
210
+ /**
211
+ * Additional error data
212
+ */
213
+ data?: Record<string, unknown>;
214
+ }
215
+ /**
216
+ * Execution statistics
217
+ */
218
+ export interface ExecutionStats {
219
+ /**
220
+ * Execution duration in milliseconds
221
+ */
222
+ duration: number;
223
+ /**
224
+ * Peak tracked memory usage in bytes
225
+ *
226
+ * When `memoryLimit` is configured, this reports the peak memory usage
227
+ * tracked during execution. Tracking monitors String and Array allocations.
228
+ *
229
+ * 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
+ */
232
+ memoryUsage?: number;
233
+ /**
234
+ * Number of tool calls made
235
+ */
236
+ toolCallCount: number;
237
+ /**
238
+ * Number of loop iterations executed
239
+ */
240
+ iterationCount: number;
241
+ /**
242
+ * Timestamp when execution started
243
+ */
244
+ startTime: number;
245
+ /**
246
+ * Timestamp when execution ended
247
+ */
248
+ endTime: number;
249
+ }
250
+ /**
251
+ * Configuration for Enclave execution
252
+ */
253
+ export type ToolBridgeMode = 'string' | 'direct';
254
+ /**
255
+ * Tool bridge configuration between the sandbox and host runtime.
256
+ *
257
+ * By default, tool calls use a JSON string request/response envelope to avoid
258
+ * leaking host-realm objects (Errors, Promises, Functions) into the sandbox.
259
+ *
260
+ * SECURITY WARNING: `mode: 'direct'` disables the string bridge and passes
261
+ * objects directly across realms. This is riskier and requires an explicit
262
+ * acknowledgement.
263
+ */
264
+ export interface ToolBridgeConfig {
265
+ /**
266
+ * Bridge mode.
267
+ * @default 'string'
268
+ */
269
+ mode?: ToolBridgeMode;
270
+ /**
271
+ * Maximum size (in bytes) of a tool request or response payload.
272
+ * @default 5 * 1024 * 1024 (5MB)
273
+ */
274
+ maxPayloadBytes?: number;
275
+ /**
276
+ * Required acknowledgement to enable insecure direct bridging.
277
+ *
278
+ * When `mode` is set to `'direct'`, enclave construction throws unless this
279
+ * field is explicitly set to `true`.
280
+ */
281
+ acknowledgeInsecureDirect?: boolean;
282
+ }
283
+ export interface EnclaveConfig {
284
+ /**
285
+ * Maximum execution time in milliseconds
286
+ * Default: 30000 (30 seconds)
287
+ */
288
+ timeout?: number;
289
+ /**
290
+ * Maximum memory usage in bytes
291
+ *
292
+ * When set, the VM adapter tracks String and Array allocations and throws
293
+ * a MemoryLimitError if the limit is exceeded. Tracking adds ~5-10% overhead.
294
+ *
295
+ * Note: This is enforced via allocation tracking, not V8 heap limits.
296
+ * For precise memory isolation, use the worker_threads adapter.
297
+ *
298
+ * Default: 128 * 1024 * 1024 (128MB)
299
+ */
300
+ memoryLimit?: number;
301
+ /**
302
+ * Maximum number of tool calls allowed
303
+ * Default: 100
304
+ */
305
+ maxToolCalls?: number;
306
+ /**
307
+ * Maximum number of loop iterations (per loop)
308
+ * Default: 10000
309
+ */
310
+ maxIterations?: number;
311
+ /**
312
+ * Sandbox adapter to use
313
+ * Default: 'vm'
314
+ */
315
+ adapter?: 'vm' | 'isolated-vm' | 'worker_threads';
316
+ /**
317
+ * Whether to allow access to Node.js built-ins
318
+ * Default: false
319
+ */
320
+ allowBuiltins?: boolean;
321
+ /**
322
+ * Custom globals to inject into the sandbox
323
+ */
324
+ globals?: Record<string, unknown>;
325
+ /**
326
+ * Tool call handler
327
+ * This function is called when the script calls __safe_callTool
328
+ */
329
+ toolHandler?: ToolHandler;
330
+ /**
331
+ * Tool bridge configuration between the sandbox and host.
332
+ *
333
+ * Default: `{ mode: 'string', maxPayloadBytes: 5MB }`
334
+ */
335
+ toolBridge?: ToolBridgeConfig;
336
+ /**
337
+ * Maximum total console output in bytes
338
+ * Default: Determined by securityLevel (1MB for STANDARD)
339
+ * Prevents I/O flood attacks via console.log spam
340
+ */
341
+ maxConsoleOutputBytes?: number;
342
+ /**
343
+ * Maximum number of console calls (log, warn, error, info)
344
+ * Default: Determined by securityLevel (1000 for STANDARD)
345
+ * Prevents I/O flood attacks via excessive console calls
346
+ */
347
+ maxConsoleCalls?: number;
348
+ }
349
+ /**
350
+ * Tool call handler function
351
+ */
352
+ export type ToolHandler = (toolName: string, args: Record<string, unknown>) => Promise<unknown>;
353
+ /**
354
+ * Safe runtime context provided to AgentScript code
355
+ */
356
+ export interface SafeRuntimeContext {
357
+ /**
358
+ * Safe tool call function
359
+ * Tracks calls, enforces limits, and delegates to the tool handler
360
+ */
361
+ __safe_callTool: (toolName: string, args: Record<string, unknown>) => Promise<unknown>;
362
+ /**
363
+ * Safe for-of loop iterator
364
+ * Enforces iteration limits
365
+ */
366
+ __safe_forOf: <T>(iterable: Iterable<T>) => Iterable<T>;
367
+ /**
368
+ * Safe for loop wrapper
369
+ * Enforces iteration limits
370
+ */
371
+ __safe_for: (init: () => void, test: () => boolean, update: () => void, body: () => void) => void;
372
+ /**
373
+ * Safe while loop wrapper
374
+ * Enforces iteration limits
375
+ */
376
+ __safe_while: (test: () => boolean, body: () => void) => void;
377
+ /**
378
+ * Safe do-while loop wrapper
379
+ * Enforces iteration limits
380
+ */
381
+ __safe_doWhile: (body: () => void, test: () => boolean) => void;
382
+ /**
383
+ * Safe string concatenation
384
+ * Detects reference IDs and handles them appropriately
385
+ */
386
+ __safe_concat: (left: unknown, right: unknown) => unknown;
387
+ /**
388
+ * Safe template literal interpolation
389
+ * Detects reference IDs in interpolated values
390
+ */
391
+ __safe_template: (quasis: string[], ...values: unknown[]) => unknown;
392
+ /**
393
+ * Whitelisted safe globals
394
+ */
395
+ Math: typeof Math;
396
+ JSON: typeof JSON;
397
+ Array: typeof Array;
398
+ Object: typeof Object;
399
+ String: typeof String;
400
+ Number: typeof Number;
401
+ Date: typeof Date;
402
+ NaN: typeof NaN;
403
+ Infinity: typeof Infinity;
404
+ undefined: typeof undefined;
405
+ isNaN: typeof isNaN;
406
+ isFinite: typeof isFinite;
407
+ parseInt: typeof parseInt;
408
+ parseFloat: typeof parseFloat;
409
+ }
410
+ import type { ReferenceSidecar } from './sidecar/reference-sidecar';
411
+ import type { ReferenceConfig } from './sidecar/reference-config';
412
+ import type { ScoringGateConfig, ScoringGateResult } from './scoring/types';
413
+ import type { WorkerPoolConfig } from './adapters/worker-pool/config';
414
+ import type { DoubleVmConfig, PartialDoubleVmConfig, ParentValidationConfig } from './double-vm/types';
415
+ /**
416
+ * Internal execution context (tracks state during execution)
417
+ */
418
+ export interface ExecutionContext {
419
+ /**
420
+ * Configuration
421
+ */
422
+ config: Omit<Required<EnclaveConfig>, 'toolHandler'> & {
423
+ toolHandler?: ToolHandler;
424
+ sanitizeStackTraces: boolean;
425
+ maxSanitizeDepth: number;
426
+ maxSanitizeProperties: number;
427
+ };
428
+ /**
429
+ * Statistics tracker
430
+ */
431
+ stats: ExecutionStats;
432
+ /**
433
+ * Abort controller for cancellation
434
+ */
435
+ abortController: AbortController;
436
+ /**
437
+ * Whether execution has been aborted
438
+ */
439
+ aborted: boolean;
440
+ /**
441
+ * Tool handler
442
+ */
443
+ toolHandler?: ToolHandler;
444
+ /**
445
+ * Reference sidecar for pass-by-reference support (per-execution)
446
+ * Created and disposed by the Enclave for each run
447
+ */
448
+ sidecar?: ReferenceSidecar;
449
+ /**
450
+ * Reference configuration for sidecar
451
+ */
452
+ referenceConfig?: ReferenceConfig;
453
+ /**
454
+ * Secure proxy configuration for runtime property blocking
455
+ */
456
+ secureProxyConfig?: SecureProxyLevelConfig;
457
+ }
458
+ /**
459
+ * Sandbox adapter interface
460
+ * Different sandboxing strategies (isolated-vm, vm2, worker_threads) implement this
461
+ */
462
+ export interface SandboxAdapter {
463
+ /**
464
+ * Execute code in the sandbox
465
+ *
466
+ * @param code Transformed AgentScript code to execute
467
+ * @param context Execution context
468
+ * @returns Execution result
469
+ */
470
+ execute<T = unknown>(code: string, context: ExecutionContext): Promise<ExecutionResult<T>>;
471
+ /**
472
+ * Cleanup the sandbox
473
+ */
474
+ dispose(): void;
475
+ }
476
+ /**
477
+ * Options for reference sidecar (pass-by-reference) support
478
+ */
479
+ export interface ReferenceSidecarOptions {
480
+ /**
481
+ * Enable pass-by-reference support
482
+ * When enabled, large strings are automatically lifted to a sidecar
483
+ * and replaced with reference IDs.
484
+ * @default false
485
+ */
486
+ enabled: boolean;
487
+ /**
488
+ * Maximum total size of all stored references in bytes
489
+ * Prevents memory exhaustion from excessive data storage
490
+ * @default Determined by securityLevel
491
+ */
492
+ maxTotalSize?: number;
493
+ /**
494
+ * Maximum size of a single reference in bytes
495
+ * @default Determined by securityLevel
496
+ */
497
+ maxReferenceSize?: number;
498
+ /**
499
+ * Threshold in bytes to trigger extraction from source code
500
+ * Strings larger than this are lifted to the sidecar
501
+ * @default Determined by securityLevel
502
+ */
503
+ extractionThreshold?: number;
504
+ /**
505
+ * Maximum expanded size when resolving references for tool calls
506
+ * @default Determined by securityLevel
507
+ */
508
+ maxResolvedSize?: number;
509
+ /**
510
+ * Whether to allow composite handles from string concatenation
511
+ * If false, concatenating references throws an error
512
+ * @default Determined by securityLevel (false for STRICT/SECURE)
513
+ */
514
+ allowComposites?: boolean;
515
+ /**
516
+ * Maximum number of references in a single execution
517
+ * @default Determined by securityLevel
518
+ */
519
+ maxReferenceCount?: number;
520
+ }
521
+ /**
522
+ * Options for creating an Enclave instance
523
+ */
524
+ export interface CreateEnclaveOptions extends EnclaveConfig {
525
+ /**
526
+ * Security level preset
527
+ *
528
+ * Pre-configured security profiles that balance functionality against risk.
529
+ * Individual options (timeout, maxIterations, etc.) override the preset values.
530
+ *
531
+ * Levels:
532
+ * - STRICT: Maximum security for untrusted AI-generated code
533
+ * - SECURE: High security with more headroom for trusted AI code
534
+ * - STANDARD: Balanced security and functionality (DEFAULT)
535
+ * - PERMISSIVE: Minimal restrictions (development only)
536
+ *
537
+ * @default 'STANDARD'
538
+ *
539
+ * @example
540
+ * ```typescript
541
+ * // Use STRICT for untrusted code
542
+ * const enclave = new Enclave({ securityLevel: 'STRICT' });
543
+ *
544
+ * // Override specific values from the preset
545
+ * const enclave = new Enclave({
546
+ * securityLevel: 'SECURE',
547
+ * timeout: 20000, // Override SECURE's 15s default
548
+ * });
549
+ * ```
550
+ */
551
+ securityLevel?: SecurityLevel;
552
+ /**
553
+ * AST validation preset to use for code validation
554
+ *
555
+ * Controls which validation rules are applied to code before execution.
556
+ * All presets support custom globals via the `globals` option.
557
+ *
558
+ * Presets:
559
+ * - agentscript: Specialized for AI agent tool orchestration (DEFAULT)
560
+ * - strict: Bank-grade security, blocks almost everything
561
+ * - secure: High security with reasonable flexibility
562
+ * - standard: Balanced security for most use cases
563
+ * - permissive: Minimal restrictions for trusted code
564
+ *
565
+ * @default 'agentscript'
566
+ *
567
+ * @example
568
+ * ```typescript
569
+ * // Use agentscript preset (default)
570
+ * const enclave = new Enclave({ preset: 'agentscript' });
571
+ *
572
+ * // Use strict preset for maximum security
573
+ * const enclave = new Enclave({ preset: 'strict' });
574
+ * ```
575
+ */
576
+ preset?: AstPreset;
577
+ /**
578
+ * Whether to validate AgentScript code before execution
579
+ * Default: true
580
+ */
581
+ validate?: boolean;
582
+ /**
583
+ * Whether to transform AgentScript code before execution
584
+ * Default: true
585
+ */
586
+ transform?: boolean;
587
+ /**
588
+ * Whether to allow functions in custom globals
589
+ * Default: Determined by securityLevel (false for STRICT/SECURE/STANDARD)
590
+ *
591
+ * Security Warning: Functions can leak host scope via closures.
592
+ * Only enable if you understand the security implications.
593
+ */
594
+ allowFunctionsInGlobals?: boolean;
595
+ /**
596
+ * Whether to sanitize stack traces in error messages
597
+ * Default: Determined by securityLevel (true for STRICT/SECURE)
598
+ *
599
+ * When enabled, file paths and line numbers are removed from stack traces
600
+ * to prevent information leakage about the host system.
601
+ */
602
+ sanitizeStackTraces?: boolean;
603
+ /**
604
+ * Maximum depth for value sanitization in tool responses
605
+ * Default: Determined by securityLevel
606
+ */
607
+ maxSanitizeDepth?: number;
608
+ /**
609
+ * Maximum properties per object in sanitized values
610
+ * Default: Determined by securityLevel
611
+ */
612
+ maxSanitizeProperties?: number;
613
+ /**
614
+ * Reference sidecar (pass-by-reference) configuration
615
+ *
616
+ * When enabled, the enclave:
617
+ * - Extracts large strings from code and stores them in a sidecar
618
+ * - Transforms concatenation to detect reference IDs
619
+ * - Resolves references at the callTool boundary
620
+ * - Lifts large tool results back to the sidecar
621
+ *
622
+ * This enables scripts to manipulate large data (videos, PDFs, images)
623
+ * without loading them into the JavaScript sandbox.
624
+ *
625
+ * @example
626
+ * ```typescript
627
+ * const enclave = new Enclave({
628
+ * securityLevel: 'STRICT',
629
+ * sidecar: {
630
+ * enabled: true,
631
+ * extractionThreshold: 64 * 1024, // 64KB
632
+ * },
633
+ * });
634
+ * ```
635
+ */
636
+ sidecar?: ReferenceSidecarOptions;
637
+ /**
638
+ * AI Scoring Gate configuration
639
+ *
640
+ * Adds semantic security analysis that detects attack patterns
641
+ * beyond what static AST validation can catch:
642
+ * - Data exfiltration patterns (list→send)
643
+ * - Excessive access (high limits, wildcards)
644
+ * - Fan-out attacks (tool calls in loops)
645
+ * - Sensitive data access (passwords, tokens)
646
+ *
647
+ * Runs AFTER AST validation but BEFORE code execution.
648
+ *
649
+ * @example
650
+ * ```typescript
651
+ * // Rule-based scorer (~1ms, zero dependencies)
652
+ * const enclave = new Enclave({
653
+ * scoringGate: {
654
+ * scorer: 'rule-based',
655
+ * blockThreshold: 70,
656
+ * },
657
+ * });
658
+ *
659
+ * // External API scorer (best detection)
660
+ * const enclave = new Enclave({
661
+ * scoringGate: {
662
+ * scorer: 'external-api',
663
+ * externalApi: {
664
+ * endpoint: 'https://api.example.com/score',
665
+ * apiKey: process.env.SCORING_API_KEY,
666
+ * },
667
+ * },
668
+ * });
669
+ * ```
670
+ */
671
+ scoringGate?: ScoringGateConfig;
672
+ /**
673
+ * Worker Pool Adapter configuration
674
+ *
675
+ * Only used when adapter is set to 'worker_threads'.
676
+ * Provides OS-level memory isolation via worker threads with:
677
+ * - Pool management (min/max workers, scaling)
678
+ * - Memory monitoring and enforcement
679
+ * - Hard halt capability via worker.terminate()
680
+ * - Rate limiting for message flood protection
681
+ * - Dual-layer sandbox (worker thread + VM context)
682
+ *
683
+ * @example
684
+ * ```typescript
685
+ * const enclave = new Enclave({
686
+ * adapter: 'worker_threads',
687
+ * workerPoolConfig: {
688
+ * minWorkers: 2,
689
+ * maxWorkers: 8,
690
+ * memoryLimitPerWorker: 256 * 1024 * 1024, // 256MB
691
+ * },
692
+ * });
693
+ * ```
694
+ */
695
+ workerPoolConfig?: Partial<WorkerPoolConfig>;
696
+ /**
697
+ * Secure proxy configuration override
698
+ *
699
+ * Override individual secure proxy settings from the security level preset.
700
+ * If not provided, uses the security level defaults.
701
+ *
702
+ * @example
703
+ * ```typescript
704
+ * // Use STRICT but allow constructor access for debugging
705
+ * const enclave = new Enclave({
706
+ * securityLevel: 'STRICT',
707
+ * secureProxyConfig: { blockConstructor: false },
708
+ * });
709
+ * ```
710
+ */
711
+ secureProxyConfig?: Partial<SecureProxyLevelConfig>;
712
+ /**
713
+ * Double VM configuration for enhanced security isolation
714
+ *
715
+ * When enabled (default), user code runs inside a nested VM structure:
716
+ * - Parent VM: Security barrier with enhanced validation
717
+ * - Inner VM: Where user code actually executes
718
+ *
719
+ * This provides defense-in-depth: even if malicious code exploits a VM
720
+ * vulnerability, it only escapes to another sandboxed VM rather than
721
+ * the host process.
722
+ *
723
+ * The parent VM provides additional security:
724
+ * - Operation name validation (whitelist/blacklist patterns)
725
+ * - Rate limiting (max operations per second)
726
+ * - Suspicious pattern detection (exfiltration, enumeration)
727
+ * - Double sanitization of operation arguments
728
+ *
729
+ * @default { enabled: true }
730
+ *
731
+ * @example
732
+ * ```typescript
733
+ * // Use with custom validation (default is enabled)
734
+ * const enclave = new Enclave({
735
+ * doubleVm: {
736
+ * parentValidation: {
737
+ * allowedOperationPattern: /^[a-z]+:[a-z]+$/i,
738
+ * maxOperationsPerSecond: 50,
739
+ * },
740
+ * },
741
+ * });
742
+ *
743
+ * // SECURITY WARNING: Disable (not recommended for production)
744
+ * const enclave = new Enclave({
745
+ * doubleVm: { enabled: false },
746
+ * });
747
+ * ```
748
+ */
749
+ doubleVm?: PartialDoubleVmConfig;
750
+ }
751
+ /**
752
+ * Re-exported scoring types for convenience
753
+ * @see {@link ScoringGateConfig} Configuration for the AI scoring gate
754
+ * @see {@link ScoringGateResult} Result from scoring gate evaluation
755
+ */
756
+ export type { ScoringGateConfig, ScoringGateResult };
757
+ /**
758
+ * Re-exported worker pool configuration type
759
+ * @see {@link WorkerPoolConfig} Configuration for worker pool adapter
760
+ */
761
+ export type { WorkerPoolConfig };
762
+ /**
763
+ * Re-exported double VM types for convenience
764
+ * @see {@link DoubleVmConfig} Full configuration for double VM layer
765
+ * @see {@link PartialDoubleVmConfig} Partial configuration with defaults
766
+ * @see {@link ParentValidationConfig} Parent VM validation settings
767
+ */
768
+ export type { DoubleVmConfig, PartialDoubleVmConfig, ParentValidationConfig };
769
+ /**
770
+ * Default double VM configuration
771
+ *
772
+ * Double VM is enabled by default for all adapters.
773
+ * This provides defense-in-depth security through nested VM isolation.
774
+ */
775
+ export declare const DEFAULT_DOUBLE_VM_CONFIG: DoubleVmConfig;