@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/enclave.js ADDED
@@ -0,0 +1,671 @@
1
+ "use strict";
2
+ /**
3
+ * Enclave - Safe AgentScript Execution Environment
4
+ *
5
+ * Provides a sandboxed environment for executing AgentScript code with:
6
+ * - AST validation
7
+ * - Code transformation
8
+ * - Runtime safety wrappers
9
+ * - Resource limits (timeout, memory, iterations)
10
+ * - Pass-by-reference support for large data
11
+ *
12
+ * @packageDocumentation
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.Enclave = void 0;
16
+ exports.runAgentScript = runAgentScript;
17
+ const tslib_1 = require("tslib");
18
+ const ast_1 = require("@enclave-vm/ast");
19
+ const babel_1 = require("./babel");
20
+ const ast_2 = require("@enclave-vm/ast");
21
+ const ast_3 = require("@enclave-vm/ast");
22
+ const acorn = tslib_1.__importStar(require("acorn"));
23
+ const astring_1 = require("astring");
24
+ const types_1 = require("./types");
25
+ const globals_validator_1 = require("./globals-validator");
26
+ const sidecar_1 = require("./sidecar");
27
+ const sidecar_2 = require("./sidecar");
28
+ const scoring_1 = require("./scoring");
29
+ /**
30
+ * Default security level
31
+ */
32
+ const DEFAULT_SECURITY_LEVEL = 'STANDARD';
33
+ /**
34
+ * Default maximum tool bridge payload size.
35
+ */
36
+ const DEFAULT_TOOL_BRIDGE_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024; // 5MB
37
+ /**
38
+ * Get merged configuration from security level and explicit options
39
+ * Explicit options override security level defaults
40
+ */
41
+ function getConfigFromSecurityLevel(securityLevel, options) {
42
+ const levelConfig = types_1.SECURITY_LEVEL_CONFIGS[securityLevel];
43
+ // Merge secure proxy config: explicit options override level defaults
44
+ const secureProxyConfig = {
45
+ ...levelConfig.secureProxy,
46
+ ...(options.secureProxyConfig ?? {}),
47
+ };
48
+ return {
49
+ timeout: options.timeout ?? levelConfig.timeout,
50
+ maxIterations: options.maxIterations ?? levelConfig.maxIterations,
51
+ maxToolCalls: options.maxToolCalls ?? levelConfig.maxToolCalls,
52
+ sanitizeStackTraces: options.sanitizeStackTraces ?? levelConfig.sanitizeStackTraces,
53
+ maxSanitizeDepth: options.maxSanitizeDepth ?? levelConfig.maxSanitizeDepth,
54
+ maxSanitizeProperties: options.maxSanitizeProperties ?? levelConfig.maxSanitizeProperties,
55
+ allowFunctionsInGlobals: options.allowFunctionsInGlobals ?? levelConfig.allowFunctionsInGlobals,
56
+ maxConsoleOutputBytes: options.maxConsoleOutputBytes ?? levelConfig.maxConsoleOutputBytes,
57
+ maxConsoleCalls: options.maxConsoleCalls ?? levelConfig.maxConsoleCalls,
58
+ secureProxyConfig,
59
+ };
60
+ }
61
+ /**
62
+ * Base configuration values (non-security-level dependent)
63
+ */
64
+ const BASE_CONFIG = {
65
+ memoryLimit: 1 * 1024 * 1024, // 1 MB - default memory limit for AgentScript execution
66
+ adapter: 'vm',
67
+ allowBuiltins: false,
68
+ globals: {},
69
+ toolHandler: undefined,
70
+ };
71
+ /**
72
+ * Build reference config from security level and sidecar options
73
+ */
74
+ function buildReferenceConfig(securityLevel, sidecarOptions) {
75
+ if (!sidecarOptions?.enabled) {
76
+ return undefined;
77
+ }
78
+ const baseConfig = sidecar_2.REFERENCE_CONFIGS[securityLevel];
79
+ return {
80
+ maxTotalSize: sidecarOptions.maxTotalSize ?? baseConfig.maxTotalSize,
81
+ maxReferenceSize: sidecarOptions.maxReferenceSize ?? baseConfig.maxReferenceSize,
82
+ extractionThreshold: sidecarOptions.extractionThreshold ?? baseConfig.extractionThreshold,
83
+ maxResolvedSize: sidecarOptions.maxResolvedSize ?? baseConfig.maxResolvedSize,
84
+ allowComposites: sidecarOptions.allowComposites ?? baseConfig.allowComposites,
85
+ maxReferenceCount: sidecarOptions.maxReferenceCount ?? baseConfig.maxReferenceCount,
86
+ maxResolutionDepth: baseConfig.maxResolutionDepth,
87
+ };
88
+ }
89
+ /**
90
+ * Enclave - Safe AgentScript Execution Environment
91
+ *
92
+ * @example
93
+ * ```typescript
94
+ * import { Enclave } from '@enclave-vm/core';
95
+ *
96
+ * // Create enclave with tool handler
97
+ * const enclave = new Enclave({
98
+ * timeout: 5000,
99
+ * maxToolCalls: 50,
100
+ * toolHandler: async (toolName, args) => {
101
+ * // Handle tool calls
102
+ * return { result: 'data' };
103
+ * },
104
+ * });
105
+ *
106
+ * // Execute AgentScript code
107
+ * const code = `
108
+ * const users = await callTool('users:list', {});
109
+ * return users.items.length;
110
+ * `;
111
+ *
112
+ * const result = await enclave.run(code);
113
+ * console.log(result.value); // Number of users
114
+ * ```
115
+ */
116
+ class Enclave {
117
+ config;
118
+ securityLevel;
119
+ validator;
120
+ validateCode;
121
+ transformCode;
122
+ referenceConfig;
123
+ scoringGate;
124
+ doubleVmConfig;
125
+ adapter;
126
+ constructor(options = {}) {
127
+ // Determine security level (default: STANDARD)
128
+ this.securityLevel = options.securityLevel ?? DEFAULT_SECURITY_LEVEL;
129
+ // Get configuration from security level, with explicit options overriding
130
+ const securityConfig = getConfigFromSecurityLevel(this.securityLevel, options);
131
+ // Validate custom globals before use
132
+ // Security: Prevents function injection, getters/setters, and dangerous patterns
133
+ if (options.globals) {
134
+ (0, globals_validator_1.validateGlobals)(options.globals, {
135
+ maxDepth: 10,
136
+ allowFunctions: securityConfig.allowFunctionsInGlobals,
137
+ allowGettersSetters: false,
138
+ });
139
+ }
140
+ // Normalize tool bridge configuration (defaults + validation)
141
+ const normalizedToolBridge = {
142
+ mode: options.toolBridge?.mode ?? 'string',
143
+ maxPayloadBytes: options.toolBridge?.maxPayloadBytes ?? DEFAULT_TOOL_BRIDGE_MAX_PAYLOAD_BYTES,
144
+ acknowledgeInsecureDirect: options.toolBridge?.acknowledgeInsecureDirect ?? false,
145
+ };
146
+ if (normalizedToolBridge.mode !== 'string' && normalizedToolBridge.mode !== 'direct') {
147
+ throw new TypeError(`Invalid toolBridge.mode: ${String(normalizedToolBridge.mode)}`);
148
+ }
149
+ if (!Number.isFinite(normalizedToolBridge.maxPayloadBytes) || normalizedToolBridge.maxPayloadBytes <= 0) {
150
+ throw new TypeError('toolBridge.maxPayloadBytes must be a positive, finite number');
151
+ }
152
+ if (normalizedToolBridge.mode === 'direct' && normalizedToolBridge.acknowledgeInsecureDirect !== true) {
153
+ throw new Error(`toolBridge.mode='direct' is insecure; set toolBridge.acknowledgeInsecureDirect=true to enable it explicitly.`);
154
+ }
155
+ // Build initial globals from base config and user options
156
+ const initialGlobals = {
157
+ ...BASE_CONFIG.globals,
158
+ ...options.globals,
159
+ };
160
+ // Add Babel global when preset is 'babel'
161
+ // Creates a restricted Babel.transform() and Babel.transformMultiple() API
162
+ // with security-level-aware limits
163
+ const presetName = options.preset ?? 'agentscript';
164
+ if (presetName === 'babel') {
165
+ const babelConfig = (0, ast_1.getBabelConfig)(this.securityLevel);
166
+ const restrictedBabel = (0, babel_1.createRestrictedBabel)({
167
+ maxInputSize: babelConfig.maxInputSize,
168
+ maxOutputSize: babelConfig.maxOutputSize,
169
+ allowedPresets: babelConfig.allowedPresets,
170
+ transformTimeout: babelConfig.transformTimeout,
171
+ });
172
+ // Multi-file limits from security level
173
+ const multiFileLimits = {
174
+ maxFiles: babelConfig.maxFiles,
175
+ maxTotalInputSize: babelConfig.maxTotalInputSize,
176
+ maxTotalOutputSize: babelConfig.maxTotalOutputSize,
177
+ transformTimeout: babelConfig.transformTimeout,
178
+ };
179
+ // Create combined Babel global with both transform and transformMultiple
180
+ initialGlobals['Babel'] = {
181
+ // Single file transform
182
+ transform: restrictedBabel.transform,
183
+ // Multi-file transform
184
+ transformMultiple: (files, transformOptions) => {
185
+ return (0, babel_1.transformMultiple)(files, transformOptions ?? {}, multiFileLimits, restrictedBabel.transform);
186
+ },
187
+ };
188
+ }
189
+ // Merge with defaults, applying security level configuration
190
+ // Note: We explicitly set secureProxyConfig AFTER spreading options to ensure
191
+ // the merged config from securityConfig takes precedence over partial options
192
+ this.config = {
193
+ ...BASE_CONFIG,
194
+ timeout: securityConfig.timeout,
195
+ maxIterations: securityConfig.maxIterations,
196
+ maxToolCalls: securityConfig.maxToolCalls,
197
+ sanitizeStackTraces: securityConfig.sanitizeStackTraces,
198
+ maxSanitizeDepth: securityConfig.maxSanitizeDepth,
199
+ maxSanitizeProperties: securityConfig.maxSanitizeProperties,
200
+ maxConsoleOutputBytes: securityConfig.maxConsoleOutputBytes,
201
+ maxConsoleCalls: securityConfig.maxConsoleCalls,
202
+ ...options,
203
+ toolBridge: normalizedToolBridge,
204
+ // secureProxyConfig must come AFTER options spread to use the merged config
205
+ secureProxyConfig: securityConfig.secureProxyConfig,
206
+ globals: initialGlobals,
207
+ };
208
+ // Create validator with custom globals
209
+ // Extract custom global names from the final globals (includes Babel if preset='babel')
210
+ const customGlobalNames = Object.keys(initialGlobals);
211
+ // For each custom global, we need to whitelist both:
212
+ // 1. The original name (customValue)
213
+ // 2. The transformed name (__safe_customValue)
214
+ const customAllowedGlobals = customGlobalNames.flatMap((name) => [name, `__safe_${name}`]);
215
+ // Create validator based on selected preset
216
+ // Note: presetName is defined earlier (before config) for Babel global injection
217
+ this.validator = this.createValidator(presetName, customAllowedGlobals);
218
+ // Configuration flags
219
+ this.validateCode = options.validate !== false; // Default: true
220
+ this.transformCode = options.transform !== false; // Default: true
221
+ // Build reference config if sidecar is enabled
222
+ this.referenceConfig = buildReferenceConfig(this.securityLevel, options.sidecar);
223
+ // Initialize scoring gate if configured
224
+ if (options.scoringGate && options.scoringGate.scorer !== 'disabled') {
225
+ this.scoringGate = new scoring_1.ScoringGate(options.scoringGate);
226
+ }
227
+ // Build double VM config (default enabled for all adapters)
228
+ this.doubleVmConfig = this.buildDoubleVmConfig(options.doubleVm);
229
+ // Adapter will be lazy-loaded based on config.adapter
230
+ }
231
+ /**
232
+ * Build double VM configuration from user options
233
+ *
234
+ * Merges user options with defaults, handling nested validation config.
235
+ */
236
+ buildDoubleVmConfig(options) {
237
+ if (!options) {
238
+ return { ...types_1.DEFAULT_DOUBLE_VM_CONFIG };
239
+ }
240
+ return {
241
+ enabled: options.enabled ?? types_1.DEFAULT_DOUBLE_VM_CONFIG.enabled,
242
+ parentTimeoutBuffer: options.parentTimeoutBuffer ?? types_1.DEFAULT_DOUBLE_VM_CONFIG.parentTimeoutBuffer,
243
+ parentValidation: {
244
+ ...types_1.DEFAULT_DOUBLE_VM_CONFIG.parentValidation,
245
+ ...options.parentValidation,
246
+ // User-provided custom patterns (default patterns from DEFAULT_SUSPICIOUS_PATTERNS
247
+ // are automatically added by DoubleVmWrapper during bootstrap)
248
+ suspiciousPatterns: [...(options.parentValidation?.suspiciousPatterns ?? [])],
249
+ },
250
+ };
251
+ }
252
+ /**
253
+ * Initialize async components (scoring gate, etc.)
254
+ *
255
+ * Call this before run() if using scorers that require initialization
256
+ * (e.g., local-llm needs to download the model)
257
+ */
258
+ async initialize() {
259
+ await this.scoringGate?.initialize();
260
+ }
261
+ /**
262
+ * Execute AgentScript code
263
+ *
264
+ * @param code AgentScript code to execute
265
+ * @param toolHandler Optional tool handler (overrides constructor config)
266
+ * @returns Execution result
267
+ */
268
+ async run(code, toolHandler) {
269
+ const startTime = Date.now();
270
+ // Initialize stats
271
+ const stats = {
272
+ duration: 0,
273
+ toolCallCount: 0,
274
+ iterationCount: 0,
275
+ startTime,
276
+ endTime: 0,
277
+ };
278
+ // Create sidecar for this execution if enabled
279
+ const sidecar = this.referenceConfig ? new sidecar_1.ReferenceSidecar(this.referenceConfig) : undefined;
280
+ try {
281
+ // Step 1: Transform (if enabled) - MUST happen before validation
282
+ // because AgentScript allows top-level return, await, etc. which are only
283
+ // valid after wrapping in async function __ag_main()
284
+ let transformedCode = code;
285
+ if (this.transformCode) {
286
+ // Check if already wrapped
287
+ const needsWrapping = !(0, ast_2.isWrappedInMain)(code);
288
+ transformedCode = (0, ast_2.transformAgentScript)(code, {
289
+ wrapInMain: needsWrapping,
290
+ transformCallTool: true,
291
+ transformLoops: true,
292
+ });
293
+ }
294
+ // Step 1.5: Validate (if enabled) - validate BEFORE memory transforms
295
+ // This catches malicious patterns like constructor obfuscation BEFORE
296
+ // they get transformed to __safe_concat calls (which would bypass detection)
297
+ if (this.validateCode) {
298
+ const validationResult = await this.validator.validate(transformedCode);
299
+ if (!validationResult.valid) {
300
+ // Format errors with location info and deduplicate
301
+ const errorMessages = this.formatValidationErrors(validationResult.issues);
302
+ return {
303
+ success: false,
304
+ error: {
305
+ name: 'ValidationError',
306
+ message: `AgentScript validation failed:\n${errorMessages}`,
307
+ code: 'VALIDATION_ERROR',
308
+ data: { issues: validationResult.issues },
309
+ },
310
+ stats: {
311
+ ...stats,
312
+ duration: Date.now() - startTime,
313
+ endTime: Date.now(),
314
+ },
315
+ };
316
+ }
317
+ }
318
+ // Step 2: Apply sidecar transforms if enabled
319
+ // These transforms extract large strings and convert concatenation to safe calls
320
+ if (sidecar && this.referenceConfig) {
321
+ transformedCode = this.applySidecarTransforms(transformedCode, sidecar);
322
+ }
323
+ else if (this.config.memoryLimit && this.config.memoryLimit > 0) {
324
+ // Step 2.1: Apply memory tracking transforms when memoryLimit is set
325
+ // This transforms concatenation to use __safe_concat for memory tracking
326
+ transformedCode = this.applyMemoryTrackingTransforms(transformedCode);
327
+ }
328
+ // Step 2.5: AI Scoring Gate (if configured)
329
+ // This runs AFTER AST validation but BEFORE code execution
330
+ let scoringResult;
331
+ if (this.scoringGate) {
332
+ scoringResult = await this.scoringGate.evaluate(transformedCode);
333
+ if (!scoringResult.allowed) {
334
+ const signalSummary = scoringResult.signals?.map((s) => `${s.id}: ${s.description}`).join('; ') ?? 'Unknown risk';
335
+ return {
336
+ success: false,
337
+ error: {
338
+ name: 'ScoringGateError',
339
+ message: `Script blocked by AI scoring (score: ${scoringResult.totalScore}): ${signalSummary}`,
340
+ code: 'SCORING_BLOCKED',
341
+ data: {
342
+ totalScore: scoringResult.totalScore,
343
+ riskLevel: scoringResult.riskLevel,
344
+ signals: scoringResult.signals,
345
+ },
346
+ },
347
+ stats: {
348
+ ...stats,
349
+ duration: Date.now() - startTime,
350
+ endTime: Date.now(),
351
+ },
352
+ scoringResult,
353
+ };
354
+ }
355
+ }
356
+ // Step 3: Create execution context
357
+ const context = {
358
+ config: this.config,
359
+ stats,
360
+ abortController: new AbortController(),
361
+ aborted: false,
362
+ toolHandler: toolHandler || this.config.toolHandler,
363
+ sidecar,
364
+ referenceConfig: this.referenceConfig,
365
+ secureProxyConfig: this.config.secureProxyConfig,
366
+ };
367
+ // Set up timeout
368
+ const timeoutId = setTimeout(() => {
369
+ context.aborted = true;
370
+ context.abortController.abort();
371
+ }, this.config.timeout);
372
+ try {
373
+ // Step 4: Execute in sandbox
374
+ const adapter = await this.getAdapter();
375
+ const result = await adapter.execute(transformedCode, context);
376
+ // Clear timeout
377
+ clearTimeout(timeoutId);
378
+ // Include scoring result in successful execution
379
+ if (scoringResult) {
380
+ return { ...result, scoringResult };
381
+ }
382
+ return result;
383
+ }
384
+ catch (error) {
385
+ // Clear timeout
386
+ clearTimeout(timeoutId);
387
+ const err = error;
388
+ return {
389
+ success: false,
390
+ error: {
391
+ name: err.name || 'ExecutionError',
392
+ message: err.message || 'Unknown execution error',
393
+ stack: err.stack,
394
+ code: 'EXECUTION_ERROR',
395
+ },
396
+ stats: {
397
+ ...stats,
398
+ duration: Date.now() - startTime,
399
+ endTime: Date.now(),
400
+ },
401
+ };
402
+ }
403
+ }
404
+ catch (error) {
405
+ const err = error;
406
+ return {
407
+ success: false,
408
+ error: {
409
+ name: err.name || 'EnclaveError',
410
+ message: err.message || 'Unknown enclave error',
411
+ stack: err.stack,
412
+ code: 'ENCLAVE_ERROR',
413
+ },
414
+ stats: {
415
+ ...stats,
416
+ duration: Date.now() - startTime,
417
+ endTime: Date.now(),
418
+ },
419
+ };
420
+ }
421
+ finally {
422
+ // Always dispose the sidecar to prevent memory leaks
423
+ if (sidecar) {
424
+ sidecar.dispose();
425
+ }
426
+ }
427
+ }
428
+ /**
429
+ * Apply memory tracking transforms to code
430
+ *
431
+ * Transforms concatenation operations to use __safe_concat for memory tracking.
432
+ * This is used when memoryLimit is set but no sidecar is configured.
433
+ *
434
+ * @param code The code to transform
435
+ * @returns The transformed code
436
+ */
437
+ applyMemoryTrackingTransforms(code) {
438
+ // Parse the code into an AST
439
+ const ast = acorn.parse(code, {
440
+ ecmaVersion: 'latest',
441
+ sourceType: 'module',
442
+ });
443
+ // Transform concatenation operations (a + b -> __safe_concat(a, b))
444
+ // This allows the runtime to track memory allocations for string concatenation
445
+ (0, ast_3.transformConcatenation)(ast);
446
+ // Transform template literals (`Hello ${name}` -> __safe_template(['Hello ', ''], name))
447
+ // This also enables memory tracking for template string creation
448
+ (0, ast_3.transformTemplateLiterals)(ast);
449
+ // Generate code from the transformed AST
450
+ return (0, astring_1.generate)(ast);
451
+ }
452
+ /**
453
+ * Apply sidecar transforms to code
454
+ *
455
+ * Extracts large strings and transforms concatenation to use safe functions.
456
+ *
457
+ * @param code The code to transform
458
+ * @param sidecar The sidecar to store extracted strings
459
+ * @returns The transformed code
460
+ */
461
+ applySidecarTransforms(code, sidecar) {
462
+ // Parse the code into an AST
463
+ const ast = acorn.parse(code, {
464
+ ecmaVersion: 'latest',
465
+ sourceType: 'module',
466
+ });
467
+ // Extract large strings (if extraction threshold is set)
468
+ if (this.referenceConfig?.extractionThreshold) {
469
+ (0, ast_3.extractLargeStrings)(ast, {
470
+ threshold: this.referenceConfig.extractionThreshold,
471
+ onExtract: (value) => {
472
+ return sidecar.store(value, 'extraction');
473
+ },
474
+ });
475
+ }
476
+ // Transform concatenation operations (a + b -> __safe_concat(a, b))
477
+ (0, ast_3.transformConcatenation)(ast);
478
+ // Transform template literals (`Hello ${name}` -> __safe_template(['Hello ', ''], name))
479
+ (0, ast_3.transformTemplateLiterals)(ast);
480
+ // Generate code from the transformed AST
481
+ return (0, astring_1.generate)(ast);
482
+ }
483
+ /**
484
+ * Get or create the sandbox adapter
485
+ *
486
+ * When double VM is enabled (default), the base adapter is wrapped
487
+ * with a double VM layer that provides:
488
+ * - Nested VM isolation (Parent VM + Inner VM)
489
+ * - Enhanced tool call validation
490
+ * - Suspicious pattern detection
491
+ * - Defense-in-depth against VM escape attacks
492
+ */
493
+ async getAdapter() {
494
+ if (this.adapter) {
495
+ return this.adapter;
496
+ }
497
+ // If double VM is enabled, use the double VM wrapper directly
498
+ // The double VM wrapper creates its own VM structure
499
+ if (this.doubleVmConfig.enabled) {
500
+ const { wrapWithDoubleVm } = await import('./double-vm/index.js');
501
+ // Pass undefined as base adapter since DoubleVmWrapper creates its own VMs
502
+ this.adapter = wrapWithDoubleVm(undefined, this.doubleVmConfig, this.securityLevel);
503
+ return this.adapter;
504
+ }
505
+ // Double VM disabled - use base adapter with security warning
506
+ // (warning is logged by wrapWithDoubleVm when enabled=false)
507
+ const { wrapWithDoubleVm } = await import('./double-vm/index.js');
508
+ let baseAdapter;
509
+ // Lazy-load adapter based on configuration
510
+ switch (this.config.adapter) {
511
+ case 'vm': {
512
+ const { VmAdapter } = await import('./adapters/vm-adapter.js');
513
+ baseAdapter = new VmAdapter(this.securityLevel);
514
+ break;
515
+ }
516
+ case 'isolated-vm':
517
+ throw new Error('isolated-vm adapter not yet implemented');
518
+ case 'worker_threads': {
519
+ const { WorkerPoolAdapter } = await import('./adapters/worker-pool/index.js');
520
+ baseAdapter = new WorkerPoolAdapter(this.config.workerPoolConfig, this.securityLevel);
521
+ await baseAdapter.initialize?.();
522
+ break;
523
+ }
524
+ default:
525
+ throw new Error(`Unknown adapter: ${this.config.adapter}`);
526
+ }
527
+ // This will log a security warning and return the base adapter unchanged
528
+ this.adapter = wrapWithDoubleVm(baseAdapter, this.doubleVmConfig, this.securityLevel);
529
+ return this.adapter;
530
+ }
531
+ /**
532
+ * Get the current security level
533
+ *
534
+ * @returns The security level this enclave was configured with
535
+ */
536
+ getSecurityLevel() {
537
+ return this.securityLevel;
538
+ }
539
+ /**
540
+ * Get the effective configuration
541
+ *
542
+ * Useful for debugging and understanding what settings are active
543
+ *
544
+ * @returns A copy of the current configuration
545
+ */
546
+ getEffectiveConfig() {
547
+ return {
548
+ securityLevel: this.securityLevel,
549
+ timeout: this.config.timeout,
550
+ maxIterations: this.config.maxIterations,
551
+ maxToolCalls: this.config.maxToolCalls,
552
+ sanitizeStackTraces: this.config.sanitizeStackTraces,
553
+ maxSanitizeDepth: this.config.maxSanitizeDepth,
554
+ maxSanitizeProperties: this.config.maxSanitizeProperties,
555
+ memoryLimit: this.config.memoryLimit,
556
+ };
557
+ }
558
+ /**
559
+ * Create a validator based on the selected preset
560
+ *
561
+ * @param presetName The preset to use
562
+ * @param customAllowedGlobals Custom globals to whitelist
563
+ * @returns A configured JSAstValidator
564
+ */
565
+ createValidator(presetName, customAllowedGlobals) {
566
+ // Get base globals from ast-guard based on security level
567
+ // This ensures AST validation matches worker sandbox restrictions
568
+ const securityLevelGlobals = (0, ast_1.getAgentScriptGlobals)(this.securityLevel);
569
+ // Additional enclave-specific globals (for memory transforms and parallel execution)
570
+ const enclaveSpecificGlobals = [
571
+ 'parallel', // Parallel execution API
572
+ '__safe_parallel', // Transformed parallel
573
+ '__safe_concat', // Memory-safe string concatenation
574
+ '__safe_template', // Memory-safe template literals
575
+ ];
576
+ // Combine: security-level globals + enclave-specific + custom
577
+ const allAllowedGlobals = [...securityLevelGlobals, ...enclaveSpecificGlobals, ...customAllowedGlobals];
578
+ switch (presetName) {
579
+ case 'agentscript':
580
+ // AgentScript preset with security-level-aware globals
581
+ // Enable allowDynamicArrayFill when memoryLimit is configured
582
+ // because runtime Array.prototype.fill patching provides protection
583
+ return new ast_1.JSAstValidator((0, ast_1.createAgentScriptPreset)({
584
+ securityLevel: this.securityLevel,
585
+ allowedGlobals: allAllowedGlobals,
586
+ allowDynamicArrayFill: this.config.memoryLimit > 0,
587
+ }));
588
+ case 'strict':
589
+ // Other presets don't have allowedGlobals option - they use their own rules
590
+ // Note: custom globals are still available at runtime, just not validated at AST level
591
+ return new ast_1.JSAstValidator((0, ast_1.createStrictPreset)());
592
+ case 'secure':
593
+ return new ast_1.JSAstValidator((0, ast_1.createSecurePreset)());
594
+ case 'standard':
595
+ return new ast_1.JSAstValidator((0, ast_1.createStandardPreset)());
596
+ case 'permissive':
597
+ return new ast_1.JSAstValidator((0, ast_1.createPermissivePreset)());
598
+ case 'babel':
599
+ // Babel preset uses security level for all limits
600
+ // Extends AgentScript preset with Babel.transform() support
601
+ return new ast_1.JSAstValidator((0, ast_1.createBabelPreset)({
602
+ securityLevel: this.securityLevel,
603
+ allowedGlobals: allAllowedGlobals,
604
+ allowDynamicArrayFill: this.config.memoryLimit > 0,
605
+ }));
606
+ default: {
607
+ // TypeScript exhaustiveness check
608
+ const _exhaustiveCheck = presetName;
609
+ throw new Error(`Unknown preset: ${_exhaustiveCheck}`);
610
+ }
611
+ }
612
+ }
613
+ /**
614
+ * Dispose the enclave and cleanup resources
615
+ */
616
+ dispose() {
617
+ if (this.adapter) {
618
+ this.adapter.dispose();
619
+ this.adapter = undefined;
620
+ }
621
+ this.scoringGate?.dispose();
622
+ }
623
+ /**
624
+ * Get scoring gate statistics (if configured)
625
+ */
626
+ getScoringStats() {
627
+ return this.scoringGate?.getCacheStats() ?? null;
628
+ }
629
+ /**
630
+ * Format validation errors with line numbers and deduplication
631
+ *
632
+ * @param issues Array of validation issues
633
+ * @returns Formatted error message string
634
+ */
635
+ formatValidationErrors(issues) {
636
+ // Create unique key for each error to deduplicate
637
+ const seen = new Set();
638
+ const uniqueErrors = [];
639
+ for (const issue of issues) {
640
+ // Build location string if available
641
+ const locationStr = issue.location ? `:${issue.location.line}:${issue.location.column}` : '';
642
+ // Create unique key for deduplication (code + message + location)
643
+ const key = `${issue.code}|${issue.message}|${locationStr}`;
644
+ if (!seen.has(key)) {
645
+ seen.add(key);
646
+ // Format: "CODE (line:col): message" or "CODE: message" if no location
647
+ const formattedLocation = issue.location ? ` (line ${issue.location.line})` : '';
648
+ uniqueErrors.push(`${issue.code}${formattedLocation}: ${issue.message}`);
649
+ }
650
+ }
651
+ return uniqueErrors.join('\n');
652
+ }
653
+ }
654
+ exports.Enclave = Enclave;
655
+ /**
656
+ * Convenience function to create an enclave and run code in one step
657
+ *
658
+ * @param code AgentScript code to execute
659
+ * @param options Enclave configuration options
660
+ * @returns Execution result
661
+ */
662
+ async function runAgentScript(code, options = {}) {
663
+ const enclave = new Enclave(options);
664
+ try {
665
+ return await enclave.run(code);
666
+ }
667
+ finally {
668
+ enclave.dispose();
669
+ }
670
+ }
671
+ //# sourceMappingURL=enclave.js.map