@enclave-vm/core 2.10.0 → 2.11.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.
@@ -27,6 +27,7 @@ export declare class WorkerPoolAdapter implements SandboxAdapter {
27
27
  private readonly rateLimiter;
28
28
  private disposed;
29
29
  private initialized;
30
+ private readonly boundMemoryExceededHandler;
30
31
  private _totalExecutions;
31
32
  private _successfulExecutions;
32
33
  private _failedExecutions;
package/enclave.d.ts CHANGED
@@ -48,6 +48,7 @@ export declare class Enclave {
48
48
  private readonly referenceConfig?;
49
49
  private readonly scoringGate?;
50
50
  private readonly doubleVmConfig;
51
+ private readonly customGlobalNames;
51
52
  private adapter?;
52
53
  constructor(options?: CreateEnclaveOptions);
53
54
  /**
package/esm/index.mjs CHANGED
@@ -2037,6 +2037,7 @@ ${stackTraceHardeningCode}
2037
2037
  const hostAbortCheck = __host_abort_check__;
2038
2038
  const hostReportViolation = __host_reportViolation__;
2039
2039
  const hostConfig = __host_config__;
2040
+ const hostMemoryTrack = typeof __host_memory_track__ === 'function' ? __host_memory_track__ : function(){};
2040
2041
  const toolBridgeMode = ${JSON.stringify(toolBridgeMode)};
2041
2042
  const toolBridgeMaxPayloadBytes = ${toolBridgeMaxPayloadBytes};
2042
2043
 
@@ -2048,6 +2049,7 @@ ${stackTraceHardeningCode}
2048
2049
  try { delete globalThis.__host_abort_check__; } catch (e) { /* ignore */ }
2049
2050
  try { delete globalThis.__host_reportViolation__; } catch (e) { /* ignore */ }
2050
2051
  try { delete globalThis.__host_config__; } catch (e) { /* ignore */ }
2052
+ try { delete globalThis.__host_memory_track__; } catch (e) { /* ignore */ }
2051
2053
 
2052
2054
  // Policy violation reporter (best-effort; host decides how to handle based on security level)
2053
2055
  function __ag_reportViolation(kind) {
@@ -2617,7 +2619,7 @@ ${stackTraceHardeningCode}
2617
2619
  if (!leftIsRef && !rightIsRef) {
2618
2620
  // Track memory if enabled
2619
2621
  if (memoryLimit > 0) {
2620
- __host_memory_track__(rightLen * 2); // UTF-16 encoding
2622
+ hostMemoryTrack(rightLen * 2); // UTF-16 encoding
2621
2623
  }
2622
2624
  return left + right;
2623
2625
  }
@@ -2672,7 +2674,7 @@ ${stackTraceHardeningCode}
2672
2674
 
2673
2675
  // Track if result is a string
2674
2676
  if (typeof result === 'string' && memoryLimit > 0) {
2675
- __host_memory_track__(result.length * 2);
2677
+ hostMemoryTrack(result.length * 2);
2676
2678
  }
2677
2679
 
2678
2680
  return result;
@@ -2761,7 +2763,7 @@ ${stackTraceHardeningCode}
2761
2763
  if (consoleStats.totalBytes > maxConsoleBytes) {
2762
2764
  throw createSafeError('Console output size limit exceeded (max: ' + maxConsoleBytes + ' bytes). This limit prevents I/O flood attacks.');
2763
2765
  }
2764
- method.apply(console, arguments);
2766
+ method.call(console, output);
2765
2767
  };
2766
2768
  }
2767
2769
 
@@ -2822,9 +2824,9 @@ ${stackTraceHardeningCode}
2822
2824
  // First, inject the host memory tracking callback into innerContext
2823
2825
  // This allows the patched methods to track cumulative memory
2824
2826
  Object.defineProperty(innerContext, '__host_memory_track__', {
2825
- value: __host_memory_track__,
2827
+ value: hostMemoryTrack,
2826
2828
  writable: false,
2827
- configurable: false,
2829
+ configurable: true,
2828
2830
  enumerable: false
2829
2831
  });
2830
2832
 
@@ -2913,8 +2915,110 @@ ${stackTraceHardeningCode}
2913
2915
  // Remove dangerous globals from inner VM (AFTER memory patching)
2914
2916
  ${sanitizeContextCode}
2915
2917
 
2916
- // Freeze built-in prototypes to prevent prototype pollution
2917
- // and cut off constructor chain access for sandbox escape prevention
2918
+ // ============================================================
2919
+ // PHASE 2 HARDENING: CVE-2023-29017 Stack Overflow Escape Defense
2920
+ // ============================================================
2921
+ //
2922
+ // CRITICAL: Hardening MUST run BEFORE prototypes are frozen!
2923
+ // Otherwise Object.defineProperty calls will silently fail on frozen prototypes.
2924
+ //
2925
+ // Defense-in-depth against prototype chain escape via stack overflow errors:
2926
+ // 1. __proto__ shadowing to block prototype chain traversal
2927
+ // 2. Legacy method blocking (__lookupGetter__, etc.)
2928
+ // 3. Error constructor wrapping to secure V8-generated errors
2929
+ // 4. Then freeze all prototypes to lock in hardening
2930
+
2931
+ // HARDENING 1: Shadow __proto__ on PARENT VM error prototypes with null
2932
+ // This prevents e["__proto__"]["__proto__"] traversal attacks by making
2933
+ // __proto__ return null instead of the actual prototype chain.
2934
+ // MUST run before freeze!
2935
+ (function() {
2936
+ var errorProtos = [
2937
+ Error.prototype,
2938
+ TypeError.prototype,
2939
+ RangeError.prototype,
2940
+ SyntaxError.prototype,
2941
+ ReferenceError.prototype,
2942
+ URIError.prototype,
2943
+ EvalError.prototype
2944
+ ];
2945
+ for (var i = 0; i < errorProtos.length; i++) {
2946
+ // Shadow __proto__ with a null-returning getter
2947
+ // This blocks: error["__proto__"]["__proto__"]["__proto__"] attacks
2948
+ Object.defineProperty(errorProtos[i], '__proto__', {
2949
+ get: function() { return null; },
2950
+ set: function() { /* silently ignore */ },
2951
+ configurable: false,
2952
+ enumerable: false
2953
+ });
2954
+ }
2955
+ })();
2956
+
2957
+ // HARDENING 2: Shadow __proto__ in INNER VM error prototypes
2958
+ // MUST run before freeze!
2959
+ (function() {
2960
+ var shadowProtoCode =
2961
+ '(function() {' +
2962
+ ' var errorProtos = [' +
2963
+ ' Error.prototype,' +
2964
+ ' TypeError.prototype,' +
2965
+ ' RangeError.prototype,' +
2966
+ ' SyntaxError.prototype,' +
2967
+ ' ReferenceError.prototype,' +
2968
+ ' URIError.prototype,' +
2969
+ ' EvalError.prototype' +
2970
+ ' ];' +
2971
+ ' for (var i = 0; i < errorProtos.length; i++) {' +
2972
+ ' Object.defineProperty(errorProtos[i], "__proto__", {' +
2973
+ ' get: function() { return null; },' +
2974
+ ' set: function() {},' +
2975
+ ' configurable: false,' +
2976
+ ' enumerable: false' +
2977
+ ' });' +
2978
+ ' }' +
2979
+ '})();';
2980
+ var shadowScript = new vm.Script(shadowProtoCode);
2981
+ shadowScript.runInContext(innerContext);
2982
+ })();
2983
+
2984
+ // HARDENING 3: Block legacy prototype manipulation methods in PARENT VM
2985
+ // These deprecated methods (__lookupGetter__, __lookupSetter__, __defineGetter__, __defineSetter__)
2986
+ // can be used to bypass frozen prototype protections.
2987
+ // MUST run before freeze!
2988
+ (function() {
2989
+ var legacyMethods = ['__lookupGetter__', '__lookupSetter__', '__defineGetter__', '__defineSetter__'];
2990
+ for (var i = 0; i < legacyMethods.length; i++) {
2991
+ Object.defineProperty(Object.prototype, legacyMethods[i], {
2992
+ value: function() { return undefined; },
2993
+ writable: false,
2994
+ configurable: false,
2995
+ enumerable: false
2996
+ });
2997
+ }
2998
+ })();
2999
+
3000
+ // HARDENING 4: Block legacy prototype methods in INNER VM
3001
+ // MUST run before freeze!
3002
+ (function() {
3003
+ var blockLegacyCode =
3004
+ '(function() {' +
3005
+ ' var methods = ["__lookupGetter__", "__lookupSetter__", "__defineGetter__", "__defineSetter__"];' +
3006
+ ' for (var i = 0; i < methods.length; i++) {' +
3007
+ ' Object.defineProperty(Object.prototype, methods[i], {' +
3008
+ ' value: function() { return undefined; },' +
3009
+ ' writable: false,' +
3010
+ ' configurable: false,' +
3011
+ ' enumerable: false' +
3012
+ ' });' +
3013
+ ' }' +
3014
+ '})();';
3015
+ var blockScript = new vm.Script(blockLegacyCode);
3016
+ blockScript.runInContext(innerContext);
3017
+ })();
3018
+
3019
+ // ============================================================
3020
+ // PROTOTYPE FREEZING: Lock in hardening by freezing all prototypes
3021
+ // ============================================================
2918
3022
  //
2919
3023
  // We freeze prototypes in TWO places:
2920
3024
  // 1. PARENT VM prototypes - because SafeObject.prototype = Object.prototype uses parent's prototype
@@ -2936,6 +3040,8 @@ ${stackTraceHardeningCode}
2936
3040
  Object.freeze(RangeError.prototype);
2937
3041
  Object.freeze(SyntaxError.prototype);
2938
3042
  Object.freeze(ReferenceError.prototype);
3043
+ Object.freeze(URIError.prototype);
3044
+ Object.freeze(EvalError.prototype);
2939
3045
  Object.freeze(Promise.prototype);
2940
3046
 
2941
3047
  // Freeze INNER VM prototypes (used by literals like '', [], etc.)
@@ -2953,11 +3059,64 @@ ${stackTraceHardeningCode}
2953
3059
  'Object.freeze(RangeError.prototype);' +
2954
3060
  'Object.freeze(SyntaxError.prototype);' +
2955
3061
  'Object.freeze(ReferenceError.prototype);' +
3062
+ 'Object.freeze(URIError.prototype);' +
3063
+ 'Object.freeze(EvalError.prototype);' +
2956
3064
  'Object.freeze(Promise.prototype);';
2957
3065
  var freezeScript = new vm.Script(freezeCode);
2958
3066
  freezeScript.runInContext(innerContext);
2959
3067
  })();
2960
3068
 
3069
+ // HARDENING 5: Wrap error constructors to freeze instances
3070
+ // V8-generated errors (like stack overflow RangeError) are created internally,
3071
+ // not via the constructor. But wrapping provides defense-in-depth for any
3072
+ // errors that ARE created via constructors.
3073
+ // NOTE: This can run after freeze because it replaces global constructors, not prototype properties
3074
+ (function() {
3075
+ var wrapErrorCode =
3076
+ '(function() {' +
3077
+ ' var origError = Error;' +
3078
+ ' var origTypeError = TypeError;' +
3079
+ ' var origRangeError = RangeError;' +
3080
+ ' var origSyntaxError = SyntaxError;' +
3081
+ ' var origReferenceError = ReferenceError;' +
3082
+ ' var origEvalError = EvalError;' +
3083
+ ' var origURIError = URIError;' +
3084
+ ' function wrapErrorCtor(OrigCtor, name) {' +
3085
+ ' var WrappedCtor = function(msg) {' +
3086
+ ' var err;' +
3087
+ ' if (new.target) {' +
3088
+ ' err = new OrigCtor(msg);' +
3089
+ ' } else {' +
3090
+ ' err = OrigCtor(msg);' +
3091
+ ' }' +
3092
+ ' try { Object.freeze(err); } catch (e) {}' +
3093
+ ' return err;' +
3094
+ ' };' +
3095
+ ' WrappedCtor.prototype = OrigCtor.prototype;' +
3096
+ ' try { Object.setPrototypeOf(WrappedCtor, OrigCtor); } catch (e) {}' +
3097
+ ' try { Object.freeze(WrappedCtor); } catch (e) {}' +
3098
+ ' return WrappedCtor;' +
3099
+ ' }' +
3100
+ ' try { Error = wrapErrorCtor(origError, "Error"); } catch (e) {}' +
3101
+ ' try { TypeError = wrapErrorCtor(origTypeError, "TypeError"); } catch (e) {}' +
3102
+ ' try { RangeError = wrapErrorCtor(origRangeError, "RangeError"); } catch (e) {}' +
3103
+ ' try { SyntaxError = wrapErrorCtor(origSyntaxError, "SyntaxError"); } catch (e) {}' +
3104
+ ' try { ReferenceError = wrapErrorCtor(origReferenceError, "ReferenceError"); } catch (e) {}' +
3105
+ ' try { EvalError = wrapErrorCtor(origEvalError, "EvalError"); } catch (e) {}' +
3106
+ ' try { URIError = wrapErrorCtor(origURIError, "URIError"); } catch (e) {}' +
3107
+ '})();';
3108
+ try {
3109
+ var wrapScript = new vm.Script(wrapErrorCode);
3110
+ wrapScript.runInContext(innerContext);
3111
+ } catch (e) { /* ignore */ }
3112
+ })();
3113
+
3114
+ // NOTE: HARDENING 6 and 7 (Object.getPrototypeOf / Reflect.getPrototypeOf wrappers)
3115
+ // were removed as they break legitimate internal functionality like __safe_template.
3116
+ // The existing defenses (prototype freezing, __proto__ shadowing, error constructor
3117
+ // wrapping, codeGeneration.strings=false) provide sufficient protection against
3118
+ // the CVE-2023-29017 attack pattern.
3119
+
2961
3120
  // Inject safe runtime functions (non-writable, non-configurable)
2962
3121
  // Wrap with secure proxy to block dangerous property access
2963
3122
  var safeRuntime = {
@@ -2996,6 +3155,9 @@ ${stackTraceHardeningCode}
2996
3155
  innerRuntimeScript.runInContext(innerContext);
2997
3156
  } catch (e) { /* ignore */ }
2998
3157
 
3158
+ // Defense-in-depth: Remove host callback from inner sandbox after all scripts have captured it
3159
+ try { delete innerContext['__host_memory_track__']; } catch (e) { /* ignore */ }
3160
+
2999
3161
  // Create a safe Object that blocks dangerous STATIC methods
3000
3162
  // Prevents ATK-DATA-02 (Serialization Hijack via defineProperty)
3001
3163
  // Note: __defineGetter__ etc. are on Object.prototype (instance methods), not static
@@ -3142,6 +3304,61 @@ ${stackTraceHardeningCode}
3142
3304
  // Execute User Code
3143
3305
  // ============================================================
3144
3306
 
3307
+ // HARDENING 4: Runtime prototype verification before user code execution
3308
+ // Verifies that critical prototypes are still frozen. If any have been
3309
+ // unfrozen (which shouldn't be possible but defense-in-depth), abort.
3310
+ (function() {
3311
+ var criticalPrototypes = [
3312
+ { name: 'Object.prototype', proto: Object.prototype },
3313
+ { name: 'Array.prototype', proto: Array.prototype },
3314
+ { name: 'Function.prototype', proto: Function.prototype },
3315
+ { name: 'Error.prototype', proto: Error.prototype },
3316
+ { name: 'RangeError.prototype', proto: RangeError.prototype }
3317
+ ];
3318
+ for (var i = 0; i < criticalPrototypes.length; i++) {
3319
+ var item = criticalPrototypes[i];
3320
+ if (!Object.isFrozen(item.proto)) {
3321
+ throw new Error('SECURITY VIOLATION: ' + item.name + ' is not frozen. Aborting execution.');
3322
+ }
3323
+ }
3324
+ })();
3325
+
3326
+ // HARDENING 5: Runtime verification in INNER VM
3327
+ (function() {
3328
+ var verifyCode =
3329
+ '(function() {' +
3330
+ ' var protos = [Object.prototype, Array.prototype, Error.prototype, RangeError.prototype];' +
3331
+ ' for (var i = 0; i < protos.length; i++) {' +
3332
+ ' if (!Object.isFrozen(protos[i])) {' +
3333
+ ' throw new Error("SECURITY VIOLATION: Inner VM prototype not frozen");' +
3334
+ ' }' +
3335
+ ' }' +
3336
+ '})();';
3337
+ try {
3338
+ var verifyScript = new vm.Script(verifyCode);
3339
+ verifyScript.runInContext(innerContext);
3340
+ } catch (e) {
3341
+ if (e.message && e.message.indexOf('SECURITY VIOLATION') >= 0) {
3342
+ throw e;
3343
+ }
3344
+ /* ignore other errors */
3345
+ }
3346
+ })();
3347
+
3348
+ // Defense-in-depth: Neutralize dangerous static methods on the intrinsic Object constructor
3349
+ // in the inner VM. SafeObject only replaces the global Object variable; the REAL intrinsic
3350
+ // Object is still reachable via {}.constructor and retains getOwnPropertyDescriptors etc.
3351
+ // NOTE: Only applied to inner VM - parent VM needs these for createSecureProxy/createSafeError.
3352
+ (function() {
3353
+ var neutralizeCode =
3354
+ '(function() {' +
3355
+ ' var RealObject = Object.getPrototypeOf({}).constructor;' +
3356
+ ' var dangerous = ["getOwnPropertyDescriptors","getOwnPropertyDescriptor","defineProperty","defineProperties","setPrototypeOf"];' +
3357
+ ' for (var i = 0; i < dangerous.length; i++) { try { delete RealObject[dangerous[i]]; } catch(e) {} }' +
3358
+ '})();';
3359
+ try { var s = new vm.Script(neutralizeCode); s.runInContext(innerContext); } catch(e) { /* defense-in-depth */ }
3360
+ })();
3361
+
3145
3362
  var userCode = ${JSON.stringify(userCode)};
3146
3363
  // IMPORTANT: For stack overflow errors (RangeError: Maximum call stack size exceeded),
3147
3364
  // Node/V8 may ignore Error.prepareStackTrace when it was installed by a different Script
@@ -3659,7 +3876,7 @@ var init_double_vm_wrapper = __esm({
3659
3876
  }
3660
3877
  },
3661
3878
  writable: false,
3662
- configurable: false
3879
+ configurable: true
3663
3880
  });
3664
3881
  } else {
3665
3882
  Object.defineProperty(parentContext, "__host_memory_track__", {
@@ -3667,7 +3884,7 @@ var init_double_vm_wrapper = __esm({
3667
3884
  value: () => {
3668
3885
  },
3669
3886
  writable: false,
3670
- configurable: false
3887
+ configurable: true
3671
3888
  });
3672
3889
  }
3673
3890
  Object.defineProperty(parentContext, "console", {
@@ -4517,7 +4734,7 @@ function createSafeConsole(config, stats) {
4517
4734
  "SecurityError"
4518
4735
  );
4519
4736
  }
4520
- method(...args);
4737
+ method(output);
4521
4738
  };
4522
4739
  return {
4523
4740
  log: wrap(console.log.bind(console)),
@@ -4652,7 +4869,7 @@ function sanitizeVmContext(context, securityLevel) {
4652
4869
  enumerable: true
4653
4870
  });
4654
4871
  }
4655
- var SENSITIVE_STACK_PATTERNS2, STACK_TRACE_HARDENING_CODE, STACK_TRACE_HARDENING_SCRIPT, CODE_GENERATION_VIOLATION_DETECTOR_CODE, CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT, PROTECTED_PREFIXES, DANGEROUS_OBJECT_STATIC_METHODS, NODEJS_24_DANGEROUS_GLOBALS2, VmAdapter;
4872
+ var SENSITIVE_STACK_PATTERNS2, STACK_TRACE_HARDENING_CODE, STACK_TRACE_HARDENING_SCRIPT, CODE_GENERATION_VIOLATION_DETECTOR_CODE, CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT, INTRINSIC_OBJECT_NEUTRALIZATION_CODE, INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT, PROTECTED_PREFIXES, DANGEROUS_OBJECT_STATIC_METHODS, NODEJS_24_DANGEROUS_GLOBALS2, VmAdapter;
4656
4873
  var init_vm_adapter = __esm({
4657
4874
  "libs/core/src/adapters/vm-adapter.ts"() {
4658
4875
  "use strict";
@@ -4935,6 +5152,22 @@ var init_vm_adapter = __esm({
4935
5152
  })();
4936
5153
  `.trim();
4937
5154
  CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT = new vm3.Script(CODE_GENERATION_VIOLATION_DETECTOR_CODE);
5155
+ INTRINSIC_OBJECT_NEUTRALIZATION_CODE = `
5156
+ (function() {
5157
+ var RealObject = Object.getPrototypeOf({}).constructor;
5158
+ var dangerous = [
5159
+ 'getOwnPropertyDescriptors',
5160
+ 'getOwnPropertyDescriptor',
5161
+ 'defineProperty',
5162
+ 'defineProperties',
5163
+ 'setPrototypeOf'
5164
+ ];
5165
+ for (var i = 0; i < dangerous.length; i++) {
5166
+ try { delete RealObject[dangerous[i]]; } catch (e) {}
5167
+ }
5168
+ })();
5169
+ `;
5170
+ INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new vm3.Script(INTRINSIC_OBJECT_NEUTRALIZATION_CODE);
4938
5171
  PROTECTED_PREFIXES = ["__safe_", "__ag_"];
4939
5172
  DANGEROUS_OBJECT_STATIC_METHODS = [
4940
5173
  "defineProperty",
@@ -5069,7 +5302,7 @@ var init_vm_adapter = __esm({
5069
5302
  memoryTracker.track(bytes);
5070
5303
  },
5071
5304
  writable: false,
5072
- configurable: false,
5305
+ configurable: true,
5073
5306
  enumerable: false
5074
5307
  });
5075
5308
  const patchScript = new vm3.Script(`
@@ -5176,6 +5409,10 @@ var init_vm_adapter = __esm({
5176
5409
  })();
5177
5410
  `);
5178
5411
  patchScript.runInContext(baseSandbox);
5412
+ try {
5413
+ delete baseSandbox["__host_memory_track__"];
5414
+ } catch {
5415
+ }
5179
5416
  }
5180
5417
  const shouldHardenStacks = config.sanitizeStackTraces ?? true;
5181
5418
  if (shouldHardenStacks) {
@@ -5346,17 +5583,16 @@ var init_vm_adapter = __esm({
5346
5583
  ),
5347
5584
  writable: false,
5348
5585
  configurable: false,
5349
- enumerable: true
5586
+ enumerable: false
5350
5587
  });
5351
5588
  }
5589
+ try {
5590
+ INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT.runInContext(baseSandbox);
5591
+ } catch {
5592
+ }
5352
5593
  const _protectedSandbox = createProtectedSandbox(baseSandbox);
5353
5594
  this.context = baseSandbox;
5354
- const wrappedCode = `
5355
- (async () => {
5356
- ${code}
5357
- return typeof __ag_main === 'function' ? await __ag_main() : undefined;
5358
- })();
5359
- `;
5595
+ const wrappedCode = "(async () => {\n" + code + '\nreturn typeof __ag_main === "function" ? await __ag_main() : undefined;\n})();';
5360
5596
  const script = new vm3.Script(wrappedCode, {
5361
5597
  filename: "agentscript.js"
5362
5598
  });
@@ -6576,6 +6812,8 @@ var init_worker_pool_adapter = __esm({
6576
6812
  rateLimiter;
6577
6813
  disposed = false;
6578
6814
  initialized = false;
6815
+ // Bound event handler for proper cleanup
6816
+ boundMemoryExceededHandler = this.handleMemoryExceeded.bind(this);
6579
6817
  // Metrics
6580
6818
  _totalExecutions = 0;
6581
6819
  _successfulExecutions = 0;
@@ -6598,7 +6836,7 @@ var init_worker_pool_adapter = __esm({
6598
6836
  this.slots
6599
6837
  );
6600
6838
  this.rateLimiter = createRateLimiter(this.config.maxMessagesPerSecond);
6601
- this.memoryMonitor.on("memoryExceeded", this.handleMemoryExceeded.bind(this));
6839
+ this.memoryMonitor.on("memoryExceeded", this.boundMemoryExceededHandler);
6602
6840
  }
6603
6841
  /**
6604
6842
  * Initialize the worker pool
@@ -6663,6 +6901,7 @@ var init_worker_pool_adapter = __esm({
6663
6901
  return;
6664
6902
  }
6665
6903
  this.disposed = true;
6904
+ this.memoryMonitor.off("memoryExceeded", this.boundMemoryExceededHandler);
6666
6905
  this.memoryMonitor.stop();
6667
6906
  this.executionQueue.clear();
6668
6907
  const terminatePromises = [];
@@ -9778,6 +10017,7 @@ var Enclave = class {
9778
10017
  referenceConfig;
9779
10018
  scoringGate;
9780
10019
  doubleVmConfig;
10020
+ customGlobalNames;
9781
10021
  adapter;
9782
10022
  constructor(options = {}) {
9783
10023
  this.securityLevel = options.securityLevel ?? DEFAULT_SECURITY_LEVEL;
@@ -9849,8 +10089,8 @@ var Enclave = class {
9849
10089
  secureProxyConfig: securityConfig.secureProxyConfig,
9850
10090
  globals: initialGlobals
9851
10091
  };
9852
- const customGlobalNames = Object.keys(initialGlobals);
9853
- const customAllowedGlobals = customGlobalNames.flatMap((name) => [name, `__safe_${name}`]);
10092
+ this.customGlobalNames = Object.keys(initialGlobals);
10093
+ const customAllowedGlobals = this.customGlobalNames.flatMap((name) => [name, `__safe_${name}`]);
9854
10094
  this.validator = this.createValidator(presetName, customAllowedGlobals);
9855
10095
  this.validateCode = options.validate !== false;
9856
10096
  this.transformCode = options.transform !== false;
@@ -9914,7 +10154,9 @@ var Enclave = class {
9914
10154
  transformedCode = transformAgentScript(code, {
9915
10155
  wrapInMain: needsWrapping,
9916
10156
  transformCallTool: true,
9917
- transformLoops: true
10157
+ transformLoops: true,
10158
+ // Pass custom global names so they aren't transformed to __safe_ prefix
10159
+ additionalIdentifiers: this.customGlobalNames
9918
10160
  });
9919
10161
  }
9920
10162
  if (this.validateCode) {