@enclave-vm/core 2.15.1 → 2.15.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -31,9 +31,17 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
33
  // libs/core/src/safe-error.ts
34
- function createSafeError(message, name = "Error") {
34
+ function createSafeError(message, name = "Error", code) {
35
35
  const error = new Error(message);
36
36
  error.name = name;
37
+ if (typeof code === "string") {
38
+ Object.defineProperty(error, "code", {
39
+ value: code,
40
+ writable: false,
41
+ enumerable: false,
42
+ configurable: false
43
+ });
44
+ }
37
45
  const SafeConstructor = /* @__PURE__ */ Object.create(null);
38
46
  Object.defineProperties(SafeConstructor, {
39
47
  constructor: {
@@ -92,6 +100,7 @@ function getBlockedPropertiesForLevel(level) {
92
100
  const blocked = /* @__PURE__ */ new Set();
93
101
  if (level !== "PERMISSIVE") {
94
102
  BLOCKED_PROPERTY_CATEGORIES.PROTOTYPE.forEach((p) => blocked.add(p));
103
+ BLOCKED_PROPERTY_CATEGORIES.DESCRIPTOR_MUTATION.forEach((p) => blocked.add(p));
95
104
  }
96
105
  switch (level) {
97
106
  case "STRICT":
@@ -112,6 +121,7 @@ function buildBlockedPropertiesFromConfig(config) {
112
121
  const blocked = /* @__PURE__ */ new Set();
113
122
  if (config.blockConstructor) {
114
123
  blocked.add("constructor");
124
+ BLOCKED_PROPERTY_CATEGORIES.DESCRIPTOR_MUTATION.forEach((p) => blocked.add(p));
115
125
  }
116
126
  if (config.blockPrototype) {
117
127
  blocked.add("__proto__");
@@ -134,27 +144,35 @@ function createSafeReflect(securityLevel) {
134
144
  dangerousMethods.add("apply");
135
145
  dangerousMethods.add("defineProperty");
136
146
  }
137
- return new Proxy(Reflect, {
138
- get(target, prop) {
147
+ const refuseMutation = () => {
148
+ throw createSafeError("Reflect is read-only in the sandbox", "SecurityError");
149
+ };
150
+ return new Proxy(ReflectObject, {
151
+ set: refuseMutation,
152
+ defineProperty: refuseMutation,
153
+ deleteProperty: refuseMutation,
154
+ setPrototypeOf: refuseMutation,
155
+ preventExtensions: refuseMutation,
156
+ get(_target, prop) {
139
157
  if (typeof prop === "string" && dangerousMethods.has(prop)) {
140
158
  return void 0;
141
159
  }
142
- const value = Reflect.get(target, prop);
160
+ if (!PINNED_REFLECT_VALUES.has(prop)) {
161
+ return void 0;
162
+ }
163
+ const value = PINNED_REFLECT_VALUES.get(prop);
143
164
  if (typeof value === "function" && prop === "construct") {
144
- const safeConstruct = function(ctorTarget, args, newTarget) {
145
- const AsyncFunction = async function() {
146
- }.constructor;
147
- const GeneratorFunction = function* () {
148
- }.constructor;
149
- const AsyncGeneratorFunction = async function* () {
150
- }.constructor;
151
- if (ctorTarget === Function || ctorTarget === AsyncFunction || ctorTarget === GeneratorFunction || ctorTarget === AsyncGeneratorFunction) {
165
+ const safeConstruct = function(ctorTarget, args, ...newTarget) {
166
+ if (ctorTarget === FunctionCtor || ctorTarget === AsyncFunctionCtor || ctorTarget === GeneratorFunctionCtor || ctorTarget === AsyncGeneratorFunctionCtor) {
152
167
  throw createSafeError("Reflect.construct with function constructors is blocked", "SecurityError");
153
168
  }
154
- return Reflect.construct(
169
+ if (newTarget.length === 0) {
170
+ return ReflectConstruct(ctorTarget, args);
171
+ }
172
+ return ReflectConstruct(
155
173
  ctorTarget,
156
174
  args,
157
- newTarget
175
+ newTarget[0]
158
176
  );
159
177
  };
160
178
  return createSecureProxy(safeConstruct);
@@ -166,6 +184,14 @@ function createSafeReflect(securityLevel) {
166
184
  }
167
185
  });
168
186
  }
187
+ function gatedProxyCache(gate) {
188
+ let cache = gatedProxyCaches.get(gate);
189
+ if (!cache) {
190
+ cache = /* @__PURE__ */ new WeakMap();
191
+ gatedProxyCaches.set(gate, cache);
192
+ }
193
+ return cache;
194
+ }
169
195
  function getFullCacheKey(options) {
170
196
  const parts = [];
171
197
  if (options.levelConfig) {
@@ -191,7 +217,7 @@ function getFullCacheKey(options) {
191
217
  function isProxyable(value) {
192
218
  if (value === null) return false;
193
219
  if (typeof value !== "object" && typeof value !== "function") return false;
194
- const tag = Object.prototype.toString.call(value);
220
+ const tag = ReflectApply2(ObjectToString, value, []);
195
221
  if (NON_PROXYABLE_TYPES.has(tag)) {
196
222
  return false;
197
223
  }
@@ -202,12 +228,11 @@ function createSecureProxy(target, options = {}) {
202
228
  return target;
203
229
  }
204
230
  const cacheKey = getFullCacheKey(options);
205
- const targetCache = proxyCache.get(target);
206
- if (targetCache) {
207
- const cached = targetCache.get(cacheKey);
208
- if (cached) {
209
- return cached;
210
- }
231
+ const gateCache = options.callGate ? gatedProxyCache(options.callGate) : void 0;
232
+ const lookupCached = (obj) => gateCache ? gateCache.get(obj) : proxyCache.get(obj)?.get(cacheKey);
233
+ const cached = lookupCached(target);
234
+ if (cached) {
235
+ return cached;
211
236
  }
212
237
  const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
213
238
  const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
@@ -218,12 +243,9 @@ function createSecureProxy(target, options = {}) {
218
243
  if (!isProxyable(obj)) {
219
244
  return obj;
220
245
  }
221
- const objCache = proxyCache.get(obj);
222
- if (objCache) {
223
- const cachedProxy = objCache.get(cacheKey);
224
- if (cachedProxy) {
225
- return cachedProxy;
226
- }
246
+ const cachedProxy = lookupCached(obj);
247
+ if (cachedProxy) {
248
+ return cachedProxy;
227
249
  }
228
250
  if (depth > maxDepth) {
229
251
  throw createSafeError(
@@ -234,7 +256,7 @@ function createSecureProxy(target, options = {}) {
234
256
  const proxy = new Proxy(obj, {
235
257
  get(target2, property, receiver) {
236
258
  const propName = typeof property === "symbol" ? property.toString() : property;
237
- const descriptor = Object.getOwnPropertyDescriptor(target2, property);
259
+ const descriptor = ObjectGetOwnPropertyDescriptor(target2, property);
238
260
  if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
239
261
  const exactValue = descriptor.value;
240
262
  if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
@@ -269,11 +291,11 @@ function createSecureProxy(target, options = {}) {
269
291
  }
270
292
  return void 0;
271
293
  }
272
- const value = Reflect.get(target2, property, receiver);
294
+ const value = ReflectGet(target2, property, receiver);
273
295
  if (typeof value === "function") {
274
- const tag = Object.prototype.toString.call(target2);
296
+ const tag = ReflectApply2(ObjectToString, target2, []);
275
297
  if (INTERNAL_SLOT_TYPES.has(tag)) {
276
- const boundMethod = value.bind(target2);
298
+ const boundMethod = ReflectApply2(FunctionBind, value, [target2]);
277
299
  return proxyWithDepth(boundMethod, depth + 1);
278
300
  }
279
301
  }
@@ -297,7 +319,7 @@ function createSecureProxy(target, options = {}) {
297
319
  }
298
320
  return false;
299
321
  }
300
- return Reflect.set(target2, property, value, receiver);
322
+ return ReflectSet(target2, property, value, receiver);
301
323
  },
302
324
  // Block defining dangerous properties
303
325
  defineProperty(target2, property, descriptor) {
@@ -314,18 +336,18 @@ function createSecureProxy(target, options = {}) {
314
336
  }
315
337
  return false;
316
338
  }
317
- return Reflect.defineProperty(target2, property, descriptor);
339
+ return ReflectDefineProperty(target2, property, descriptor);
318
340
  },
319
341
  // Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
320
342
  // Must respect proxy invariants: non-configurable own properties cannot be hidden
321
343
  ownKeys(target2) {
322
- const keys = Reflect.ownKeys(target2);
344
+ const keys = ReflectOwnKeys2(target2);
323
345
  return keys.filter((key) => {
324
346
  const keyStr = typeof key === "symbol" ? key.toString() : key;
325
347
  if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
326
348
  return true;
327
349
  }
328
- const descriptor = Object.getOwnPropertyDescriptor(target2, key);
350
+ const descriptor = ObjectGetOwnPropertyDescriptor(target2, key);
329
351
  if (descriptor && !descriptor.configurable) {
330
352
  return true;
331
353
  }
@@ -336,7 +358,7 @@ function createSecureProxy(target, options = {}) {
336
358
  // Must respect proxy invariants: non-configurable properties must return actual descriptor
337
359
  getOwnPropertyDescriptor(target2, property) {
338
360
  const propName = typeof property === "symbol" ? property.toString() : property;
339
- const descriptor = Reflect.getOwnPropertyDescriptor(target2, property);
361
+ const descriptor = ReflectGetOwnPropertyDescriptor2(target2, property);
340
362
  if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
341
363
  const exactValue = descriptor.value;
342
364
  if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
@@ -395,7 +417,10 @@ function createSecureProxy(target, options = {}) {
395
417
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
396
418
  apply(target2, thisArg, argArray) {
397
419
  const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
398
- const result = Reflect.apply(target2, unwrappedThis, argArray);
420
+ if (options.callGate && options.callGate.gates(target2)) {
421
+ return options.callGate.call(target2, unwrappedThis, argArray);
422
+ }
423
+ const result = ReflectApply2(target2, unwrappedThis, argArray);
399
424
  if (isProxyable(result)) {
400
425
  return proxyWithDepth(result, depth + 1);
401
426
  }
@@ -406,19 +431,26 @@ function createSecureProxy(target, options = {}) {
406
431
  // host Function constructor — the same escape class the apply trap closes for calls.
407
432
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
408
433
  construct(target2, argArray, newTarget) {
409
- const instance = Reflect.construct(target2, argArray, newTarget === proxy ? target2 : newTarget);
434
+ if (options.callGate && options.callGate.gates(target2)) {
435
+ throw createSafeError("Host functions cannot be called with new", "TypeError");
436
+ }
437
+ const instance = ReflectConstruct(target2, argArray, newTarget === proxy ? target2 : newTarget);
410
438
  if (isProxyable(instance)) {
411
439
  return proxyWithDepth(instance, depth + 1);
412
440
  }
413
441
  return instance;
414
442
  }
415
443
  });
416
- let objCacheMap = proxyCache.get(obj);
417
- if (!objCacheMap) {
418
- objCacheMap = /* @__PURE__ */ new Map();
419
- proxyCache.set(obj, objCacheMap);
444
+ if (gateCache) {
445
+ gateCache.set(obj, proxy);
446
+ } else {
447
+ let objCacheMap = proxyCache.get(obj);
448
+ if (!objCacheMap) {
449
+ objCacheMap = /* @__PURE__ */ new Map();
450
+ proxyCache.set(obj, objCacheMap);
451
+ }
452
+ objCacheMap.set(cacheKey, proxy);
420
453
  }
421
- objCacheMap.set(cacheKey, proxy);
422
454
  proxySet.add(proxy);
423
455
  proxyToTarget.set(proxy, obj);
424
456
  return proxy;
@@ -460,11 +492,33 @@ function isSecureProxy(obj) {
460
492
  }
461
493
  return proxySet.has(obj);
462
494
  }
463
- var MIN_MEMBRANE_RECURSION_DEPTH, BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, proxyCache, proxySet, proxyToTarget, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
495
+ var ObjectGetOwnPropertyDescriptor, ObjectToString, FunctionBind, ReflectGet, ReflectSet, ReflectDefineProperty, ReflectGetOwnPropertyDescriptor2, ReflectOwnKeys2, ReflectApply2, ReflectConstruct, ReflectObject, PINNED_REFLECT_VALUES, FunctionCtor, AsyncFunctionCtor, GeneratorFunctionCtor, AsyncGeneratorFunctionCtor, MIN_MEMBRANE_RECURSION_DEPTH, BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, gatedProxyCaches, proxyCache, proxySet, proxyToTarget, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
464
496
  var init_secure_proxy = __esm({
465
497
  "libs/core/src/secure-proxy.ts"() {
466
498
  "use strict";
467
499
  init_safe_error();
500
+ ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
501
+ ObjectToString = Object.prototype.toString;
502
+ FunctionBind = Function.prototype.bind;
503
+ ReflectGet = Reflect.get;
504
+ ReflectSet = Reflect.set;
505
+ ReflectDefineProperty = Reflect.defineProperty;
506
+ ReflectGetOwnPropertyDescriptor2 = Reflect.getOwnPropertyDescriptor;
507
+ ReflectOwnKeys2 = Reflect.ownKeys;
508
+ ReflectApply2 = Reflect.apply;
509
+ ReflectConstruct = Reflect.construct;
510
+ ReflectObject = Reflect;
511
+ PINNED_REFLECT_VALUES = /* @__PURE__ */ new Map();
512
+ for (const key of ReflectOwnKeys2(ReflectObject)) {
513
+ PINNED_REFLECT_VALUES.set(key, ReflectGet(ReflectObject, key));
514
+ }
515
+ FunctionCtor = Function;
516
+ AsyncFunctionCtor = async function() {
517
+ }.constructor;
518
+ GeneratorFunctionCtor = function* () {
519
+ }.constructor;
520
+ AsyncGeneratorFunctionCtor = async function* () {
521
+ }.constructor;
468
522
  MIN_MEMBRANE_RECURSION_DEPTH = 256;
469
523
  BLOCKED_PROPERTY_CATEGORIES = {
470
524
  /**
@@ -479,6 +533,23 @@ var init_secure_proxy = __esm({
479
533
  "__lookupGetter__",
480
534
  "__lookupSetter__"
481
535
  ]),
536
+ /**
537
+ * Property-descriptor and prototype MUTATION gadgets. These are the primitives behind the
538
+ * GHSA-3279 membrane self-leak (`Object.defineProperty(Object, 'getOwnPropertyDescriptor', hook)`
539
+ * to intercept the trap's raw target) and classic prototype pollution (`setPrototypeOf`). They
540
+ * are never needed by AgentScript and are already refused by the single-VM SafeObject
541
+ * (`DANGEROUS_OBJECT_STATIC_METHODS`), so they are blocked at every level that blocks the
542
+ * constructor (all except PERMISSIVE). Read-only reflection (getPrototypeOf, keys, entries,
543
+ * getOwnPropertyNames) is intentionally NOT here: the membrane's own getPrototypeOf/ownKeys traps
544
+ * already neutralize it for proxied values, and it has legitimate uses.
545
+ */
546
+ DESCRIPTOR_MUTATION: /* @__PURE__ */ new Set([
547
+ "getOwnPropertyDescriptor",
548
+ "getOwnPropertyDescriptors",
549
+ "defineProperty",
550
+ "defineProperties",
551
+ "setPrototypeOf"
552
+ ]),
482
553
  /**
483
554
  * Node.js 24 Iterator helper method names
484
555
  * Blocked at STRICT/SECURE to prevent prototype chain access via iterators
@@ -520,7 +591,13 @@ var init_secure_proxy = __esm({
520
591
  "__defineGetter__",
521
592
  "__defineSetter__",
522
593
  "__lookupGetter__",
523
- "__lookupSetter__"
594
+ "__lookupSetter__",
595
+ // Descriptor / prototype mutation gadgets (GHSA-3279 self-leak + prototype pollution)
596
+ "getOwnPropertyDescriptor",
597
+ "getOwnPropertyDescriptors",
598
+ "defineProperty",
599
+ "defineProperties",
600
+ "setPrototypeOf"
524
601
  ]);
525
602
  DEFAULT_SECURE_PROXY_CONFIG = {
526
603
  blockConstructor: true,
@@ -541,6 +618,7 @@ var init_secure_proxy = __esm({
541
618
  // 'call',
542
619
  // 'apply',
543
620
  ]);
621
+ gatedProxyCaches = /* @__PURE__ */ new WeakMap();
544
622
  proxyCache = /* @__PURE__ */ new WeakMap();
545
623
  proxySet = /* @__PURE__ */ new WeakSet();
546
624
  proxyToTarget = /* @__PURE__ */ new WeakMap();
@@ -696,7 +774,7 @@ var init_reference_config = __esm({
696
774
 
697
775
  // libs/core/src/sidecar/reference-resolver.ts
698
776
  function untrustedLength(value) {
699
- const rawLen = ReflectGet(value, "length");
777
+ const rawLen = ReflectGet2(value, "length");
700
778
  if (typeof rawLen !== "number" || !NumberIsFinite(rawLen) || rawLen < 0) {
701
779
  return 0;
702
780
  }
@@ -713,7 +791,7 @@ function untrustedLength(value) {
713
791
  }
714
792
  function untrustedAt(value, index) {
715
793
  try {
716
- return ReflectGet(value, index);
794
+ return ReflectGet2(value, index);
717
795
  } catch {
718
796
  return void 0;
719
797
  }
@@ -722,12 +800,12 @@ function isCompositeHandle(value) {
722
800
  const obj = value;
723
801
  return typeof value === "object" && value !== null && obj["__type"] === "composite" && Array.isArray(obj["__parts"]);
724
802
  }
725
- var ReflectGet, NumberIsFinite, MathFloor, MAX_TRAVERSAL_LENGTH, ResolutionLimitError, ReferenceResolver;
803
+ var ReflectGet2, NumberIsFinite, MathFloor, MAX_TRAVERSAL_LENGTH, ResolutionLimitError, ReferenceResolver;
726
804
  var init_reference_resolver = __esm({
727
805
  "libs/core/src/sidecar/reference-resolver.ts"() {
728
806
  "use strict";
729
807
  init_reference_config();
730
- ReflectGet = Reflect.get;
808
+ ReflectGet2 = Reflect.get;
731
809
  NumberIsFinite = Number.isFinite;
732
810
  MathFloor = Math.floor;
733
811
  MAX_TRAVERSAL_LENGTH = 1e6;
@@ -999,7 +1077,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
999
1077
  context.visited.add(value);
1000
1078
  }
1001
1079
  if (ArrayIsArray(value)) {
1002
- const rawLen = ReflectGet2(value, "length");
1080
+ const rawLen = ReflectGet3(value, "length");
1003
1081
  const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
1004
1082
  context.propCount.count += len;
1005
1083
  if (context.propCount.count > maxProperties) {
@@ -1009,7 +1087,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1009
1087
  for (let i = 0; i < len; i++) {
1010
1088
  let item;
1011
1089
  try {
1012
- item = ReflectGet2(value, i);
1090
+ item = ReflectGet3(value, i);
1013
1091
  } catch {
1014
1092
  item = void 0;
1015
1093
  }
@@ -1018,15 +1096,15 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1018
1096
  return result;
1019
1097
  }
1020
1098
  if (value instanceof Date) {
1021
- const time = ReflectApply(DateProtoGetTime, value, []);
1099
+ const time = ReflectApply3(DateProtoGetTime, value, []);
1022
1100
  if (allowDates) {
1023
1101
  return new Date(time);
1024
1102
  }
1025
- return ReflectApply(DateProtoToISOString, value, []);
1103
+ return ReflectApply3(DateProtoToISOString, value, []);
1026
1104
  }
1027
1105
  if (value instanceof Error) {
1028
- const rawName = ReflectGet2(value, "name");
1029
- const rawMessage = ReflectGet2(value, "message");
1106
+ const rawName = ReflectGet3(value, "name");
1107
+ const rawMessage = ReflectGet3(value, "message");
1030
1108
  const name = typeof rawName === "string" ? rawName : "Error";
1031
1109
  const message = typeof rawMessage === "string" ? rawMessage : "";
1032
1110
  if (allowErrors) {
@@ -1039,11 +1117,11 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1039
1117
  return { error: message };
1040
1118
  }
1041
1119
  if (value instanceof RegExp) {
1042
- return ReflectApply(RegExpProtoToString, value, []);
1120
+ return ReflectApply3(RegExpProtoToString, value, []);
1043
1121
  }
1044
1122
  if (value instanceof Map) {
1045
1123
  const sanitizedMap = ObjectCreate(null);
1046
- const entries = ReflectApply(MapProtoEntries, value, []);
1124
+ const entries = ReflectApply3(MapProtoEntries, value, []);
1047
1125
  for (const [key, val] of entries) {
1048
1126
  if (typeof key !== "string") continue;
1049
1127
  if (DANGEROUS_KEYS.has(key)) continue;
@@ -1053,7 +1131,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1053
1131
  return sanitizedMap;
1054
1132
  }
1055
1133
  if (value instanceof Set) {
1056
- const iter = ReflectApply(SetProtoValues, value, []);
1134
+ const iter = ReflectApply3(SetProtoValues, value, []);
1057
1135
  const result = [];
1058
1136
  for (const item of iter) {
1059
1137
  context.propCount.count++;
@@ -1074,7 +1152,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1074
1152
  }
1075
1153
  let propValue;
1076
1154
  try {
1077
- propValue = ReflectGet2(value, key);
1155
+ propValue = ReflectGet3(value, key);
1078
1156
  } catch {
1079
1157
  continue;
1080
1158
  }
@@ -1212,13 +1290,13 @@ function checkSerializedSize(value, maxBytes) {
1212
1290
  return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
1213
1291
  }
1214
1292
  }
1215
- var DANGEROUS_KEYS, ReflectApply, ReflectGet2, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
1293
+ var DANGEROUS_KEYS, ReflectApply3, ReflectGet3, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
1216
1294
  var init_value_sanitizer = __esm({
1217
1295
  "libs/core/src/value-sanitizer.ts"() {
1218
1296
  "use strict";
1219
1297
  DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
1220
- ReflectApply = Reflect.apply;
1221
- ReflectGet2 = Reflect.get;
1298
+ ReflectApply3 = Reflect.apply;
1299
+ ReflectGet3 = Reflect.get;
1222
1300
  ArrayIsArray = Array.isArray;
1223
1301
  ObjectKeys = Object.keys;
1224
1302
  ObjectCreate = Object.create;
@@ -1232,6 +1310,390 @@ var init_value_sanitizer = __esm({
1232
1310
  }
1233
1311
  });
1234
1312
 
1313
+ // libs/core/src/global-function-gate.ts
1314
+ function isBuiltinMethod(fn) {
1315
+ return (typeof fn === "function" || typeof fn === "object" && fn !== null) && BUILTIN_METHODS.has(fn);
1316
+ }
1317
+ function resolveMaxGlobalFunctionCalls(config) {
1318
+ const explicit = config.maxGlobalFunctionCalls;
1319
+ if (typeof explicit === "number" && Number.isFinite(explicit) && explicit >= 0) {
1320
+ return Math.floor(explicit);
1321
+ }
1322
+ const maxToolCalls = typeof config.maxToolCalls === "number" && Number.isFinite(config.maxToolCalls) ? config.maxToolCalls : 100;
1323
+ return Math.max(0, Math.floor(maxToolCalls)) * DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL;
1324
+ }
1325
+ function globalFunctionLimitMessage(max) {
1326
+ return `Maximum global function call limit exceeded (${max}). This limit prevents runaway calls into host functions.`;
1327
+ }
1328
+ function resultLimits(context) {
1329
+ const { config } = context;
1330
+ return {
1331
+ maxDepth: config.maxSanitizeDepth,
1332
+ maxProperties: config.maxSanitizeProperties,
1333
+ maxPayloadBytes: config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES
1334
+ };
1335
+ }
1336
+ function truncate(value, max) {
1337
+ return value.length <= max ? value : `${value.slice(0, max)}\u2026`;
1338
+ }
1339
+ function failure(error) {
1340
+ let name = "Error";
1341
+ let message = "Global function call failed";
1342
+ try {
1343
+ if (error && typeof error === "object") {
1344
+ const rawName = error.name;
1345
+ const rawMessage = error.message;
1346
+ if (typeof rawName === "string" && rawName) name = rawName;
1347
+ if (typeof rawMessage === "string" && rawMessage) message = rawMessage;
1348
+ } else if (typeof error === "string" && error) {
1349
+ message = error;
1350
+ }
1351
+ } catch {
1352
+ }
1353
+ return {
1354
+ ok: false,
1355
+ name: truncate(name, MAX_ERROR_NAME_LENGTH),
1356
+ message: truncate(message, MAX_ERROR_MESSAGE_LENGTH)
1357
+ };
1358
+ }
1359
+ function jsonReplacer(_key, value) {
1360
+ if (typeof value === "bigint") return value.toString();
1361
+ if (typeof value === "number" && !Number.isFinite(value)) return null;
1362
+ return value;
1363
+ }
1364
+ function utf8ByteLength(value) {
1365
+ return Buffer.byteLength(value, "utf8");
1366
+ }
1367
+ function encodeResult(value, limits) {
1368
+ if (value === void 0) return { ok: true };
1369
+ let json;
1370
+ try {
1371
+ const sanitized = sanitizeValue(value, {
1372
+ maxDepth: limits.maxDepth,
1373
+ maxProperties: limits.maxProperties,
1374
+ allowDates: false,
1375
+ allowErrors: true
1376
+ });
1377
+ json = JsonStringify(sanitized, jsonReplacer);
1378
+ } catch {
1379
+ return { ok: false, name: "GlobalFunctionError", message: UNSAFE_RESULT_MESSAGE };
1380
+ }
1381
+ if (json === void 0) return { ok: true };
1382
+ if (utf8ByteLength(json) > limits.maxPayloadBytes) {
1383
+ return {
1384
+ ok: false,
1385
+ name: "GlobalFunctionError",
1386
+ message: `Global function result exceeds maximum size (${limits.maxPayloadBytes} bytes)`
1387
+ };
1388
+ }
1389
+ return { ok: true, json };
1390
+ }
1391
+ function isThenable(value) {
1392
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
1393
+ try {
1394
+ return typeof value.then === "function";
1395
+ } catch {
1396
+ return false;
1397
+ }
1398
+ }
1399
+ function invokeGlobalFunction(fn, thisArg, args, limits) {
1400
+ if (typeof fn !== "function") {
1401
+ return { ok: false, name: "TypeError", message: "Global is not a function" };
1402
+ }
1403
+ let result;
1404
+ try {
1405
+ result = ReflectApply4(fn, thisArg, ArrayIsArray2(args) ? args : []);
1406
+ } catch (error) {
1407
+ return failure(error);
1408
+ }
1409
+ if (isThenable(result)) {
1410
+ return Promise.resolve(result).then(
1411
+ (value) => encodeResult(value, limits),
1412
+ (error) => failure(error)
1413
+ );
1414
+ }
1415
+ return encodeResult(result, limits);
1416
+ }
1417
+ function toEnvelope(outcome) {
1418
+ if (outcome.ok) {
1419
+ return outcome.json === void 0 ? '{"v":1,"ok":true}' : `{"v":1,"ok":true,"value":${outcome.json}}`;
1420
+ }
1421
+ return JsonStringify({ v: 1, ok: false, error: { name: outcome.name, message: outcome.message } });
1422
+ }
1423
+ function createHostGlobalFunctionInvoker(context) {
1424
+ const limits = resultLimits(context);
1425
+ return (fn, thisArg, args) => {
1426
+ const outcome = invokeGlobalFunction(fn, thisArg, args, limits);
1427
+ return outcome instanceof Promise ? outcome.then(toEnvelope) : toEnvelope(outcome);
1428
+ };
1429
+ }
1430
+ function createGlobalFunctionGate(context, realm) {
1431
+ const limits = resultLimits(context);
1432
+ const max = resolveMaxGlobalFunctionCalls(context.config);
1433
+ let calls = 0;
1434
+ const settle = (outcome) => {
1435
+ if (!outcome.ok) {
1436
+ throw createSafeError(outcome.message, outcome.name);
1437
+ }
1438
+ return outcome.json === void 0 ? void 0 : realm.parseJson(outcome.json);
1439
+ };
1440
+ return {
1441
+ gates: (target) => !isBuiltinMethod(target),
1442
+ call: (target, thisArg, args) => {
1443
+ if (context.aborted) {
1444
+ throw createSafeError("Execution aborted");
1445
+ }
1446
+ calls++;
1447
+ if (calls > max) {
1448
+ throw createSafeError(globalFunctionLimitMessage(max));
1449
+ }
1450
+ const outcome = invokeGlobalFunction(target, thisArg, args, limits);
1451
+ if (outcome instanceof Promise) {
1452
+ return realm.adoptPromise(outcome.then(settle));
1453
+ }
1454
+ return settle(outcome);
1455
+ }
1456
+ };
1457
+ }
1458
+ var ReflectApply4, ReflectOwnKeys3, ObjectGetOwnPropertyDescriptor2, ObjectGetPrototypeOf2, ArrayIsArray2, JsonStringify, BUILTIN_METHODS, DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL, DEFAULT_MAX_PAYLOAD_BYTES, MAX_ERROR_MESSAGE_LENGTH, MAX_ERROR_NAME_LENGTH, UNSAFE_RESULT_MESSAGE;
1459
+ var init_global_function_gate = __esm({
1460
+ "libs/core/src/global-function-gate.ts"() {
1461
+ "use strict";
1462
+ init_value_sanitizer();
1463
+ init_safe_error();
1464
+ ReflectApply4 = Reflect.apply;
1465
+ ReflectOwnKeys3 = Reflect.ownKeys;
1466
+ ObjectGetOwnPropertyDescriptor2 = Object.getOwnPropertyDescriptor;
1467
+ ObjectGetPrototypeOf2 = Object.getPrototypeOf;
1468
+ ArrayIsArray2 = Array.isArray;
1469
+ JsonStringify = JSON.stringify;
1470
+ BUILTIN_METHODS = (() => {
1471
+ const methods = /* @__PURE__ */ new WeakSet();
1472
+ const typedArrays = [
1473
+ Int8Array,
1474
+ Uint8Array,
1475
+ Uint8ClampedArray,
1476
+ Int16Array,
1477
+ Uint16Array,
1478
+ Int32Array,
1479
+ Uint32Array,
1480
+ Float32Array,
1481
+ Float64Array,
1482
+ BigInt64Array,
1483
+ BigUint64Array
1484
+ ];
1485
+ const arrayIteratorPrototype = ObjectGetPrototypeOf2([][Symbol.iterator]());
1486
+ const prototypes = [
1487
+ Object.prototype,
1488
+ Array.prototype,
1489
+ String.prototype,
1490
+ Number.prototype,
1491
+ Boolean.prototype,
1492
+ Symbol.prototype,
1493
+ BigInt.prototype,
1494
+ Date.prototype,
1495
+ RegExp.prototype,
1496
+ Error.prototype,
1497
+ EvalError.prototype,
1498
+ RangeError.prototype,
1499
+ ReferenceError.prototype,
1500
+ SyntaxError.prototype,
1501
+ TypeError.prototype,
1502
+ URIError.prototype,
1503
+ Map.prototype,
1504
+ Set.prototype,
1505
+ WeakMap.prototype,
1506
+ WeakSet.prototype,
1507
+ Promise.prototype,
1508
+ ArrayBuffer.prototype,
1509
+ DataView.prototype,
1510
+ ObjectGetPrototypeOf2(Uint8Array.prototype),
1511
+ // %TypedArray%.prototype
1512
+ ...typedArrays.map((TypedArray) => TypedArray.prototype),
1513
+ arrayIteratorPrototype,
1514
+ ObjectGetPrototypeOf2(arrayIteratorPrototype),
1515
+ // %IteratorPrototype%
1516
+ ObjectGetPrototypeOf2((/* @__PURE__ */ new Map())[Symbol.iterator]()),
1517
+ ObjectGetPrototypeOf2((/* @__PURE__ */ new Set())[Symbol.iterator]()),
1518
+ ObjectGetPrototypeOf2(""[Symbol.iterator]())
1519
+ ];
1520
+ for (const prototype of prototypes) {
1521
+ if (prototype === null || typeof prototype !== "object") continue;
1522
+ for (const key of ReflectOwnKeys3(prototype)) {
1523
+ if (key === "constructor") continue;
1524
+ const descriptor = ObjectGetOwnPropertyDescriptor2(prototype, key);
1525
+ if (descriptor && typeof descriptor.value === "function") {
1526
+ methods.add(descriptor.value);
1527
+ }
1528
+ }
1529
+ }
1530
+ return methods;
1531
+ })();
1532
+ DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL = 10;
1533
+ DEFAULT_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
1534
+ MAX_ERROR_MESSAGE_LENGTH = 4096;
1535
+ MAX_ERROR_NAME_LENGTH = 128;
1536
+ UNSAFE_RESULT_MESSAGE = "Global function returned a value that cannot be passed into the sandbox (functions, symbols, and values beyond the sanitization depth or size limits are not allowed)";
1537
+ }
1538
+ });
1539
+
1540
+ // libs/core/src/stack-trace.ts
1541
+ function redactLine(line) {
1542
+ let out = line.length > MAX_LINE_LENGTH ? `${line.slice(0, MAX_LINE_LENGTH)}\u2026` : line;
1543
+ for (const pattern of SENSITIVE_STACK_PATTERNS) {
1544
+ pattern.lastIndex = 0;
1545
+ out = out.replace(pattern, "[REDACTED]");
1546
+ }
1547
+ return out;
1548
+ }
1549
+ function sanitizeStackTrace(stack, sanitize = true) {
1550
+ if (typeof stack !== "string" || !stack || !sanitize) return stack;
1551
+ const bounded = stack.length > MAX_STACK_LENGTH ? stack.slice(0, MAX_STACK_LENGTH) : stack;
1552
+ return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
1553
+ }
1554
+ var SENSITIVE_STACK_PATTERNS, FRAME_LINE, MAX_STACK_LENGTH, MAX_LINE_LENGTH, REDACTED_FRAME;
1555
+ var init_stack_trace = __esm({
1556
+ "libs/core/src/stack-trace.ts"() {
1557
+ "use strict";
1558
+ SENSITIVE_STACK_PATTERNS = [
1559
+ // Unix file system paths
1560
+ /\/Users\/[^/]+\/[^\s):]*/gi,
1561
+ // macOS home directories
1562
+ /\/home\/[^/]+\/[^\s):]*/gi,
1563
+ // Linux home directories
1564
+ /\/var\/[^\s):]*/gi,
1565
+ // System var directories
1566
+ /\/opt\/[^\s):]*/gi,
1567
+ // Optional software
1568
+ /\/tmp\/[^\s):]*/gi,
1569
+ // Temporary files
1570
+ /\/etc\/[^\s):]*/gi,
1571
+ // System configuration
1572
+ /\/root\/[^\s):]*/gi,
1573
+ // Root home directory
1574
+ /\/mnt\/[^\s):]*/gi,
1575
+ // Mount points
1576
+ /\/srv\/[^\s):]*/gi,
1577
+ // Service data
1578
+ /\/data\/[^\s):]*/gi,
1579
+ // Data directories
1580
+ /\/app\/[^\s):]*/gi,
1581
+ // Application directories
1582
+ /\/proc\/[^\s):]*/gi,
1583
+ // Process information
1584
+ /\/sys\/[^\s):]*/gi,
1585
+ // System files
1586
+ // Windows paths
1587
+ /\\\\[^\s):]*/g,
1588
+ // UNC paths
1589
+ /[A-Z]:\\[^\s):]+/gi,
1590
+ // Windows drive paths
1591
+ // URL-based paths
1592
+ /file:\/\/[^\s):]+/gi,
1593
+ // File URLs
1594
+ /webpack:\/\/[^\s):]+/gi,
1595
+ // Webpack paths
1596
+ /%2F[^\s):]+/gi,
1597
+ // URL-encoded paths
1598
+ // Package managers and node
1599
+ /node_modules\/[^\s):]+/gi,
1600
+ // Node modules paths
1601
+ /\/nix\/store\/[^\s):]*/gi,
1602
+ // Nix store paths
1603
+ /\.npm\/[^\s):]*/gi,
1604
+ // NPM cache
1605
+ /\.yarn\/[^\s):]*/gi,
1606
+ // Yarn cache
1607
+ /\.pnpm\/[^\s):]*/gi,
1608
+ // PNPM cache
1609
+ // Container and orchestration
1610
+ /\/run\/secrets\/[^\s):]*/gi,
1611
+ // Docker/K8s secrets
1612
+ /\/var\/run\/[^\s):]*/gi,
1613
+ // Runtime directories
1614
+ /\/docker\/[^\s):]*/gi,
1615
+ // Docker paths
1616
+ /\/containers\/[^\s):]*/gi,
1617
+ // Container paths
1618
+ /\/kubelet\/[^\s):]*/gi,
1619
+ // Kubernetes kubelet
1620
+ // CI/CD systems
1621
+ /\/github\/workspace\/[^\s):]*/gi,
1622
+ // GitHub Actions
1623
+ /\/runner\/[^\s):]*/gi,
1624
+ // GitHub/GitLab runner
1625
+ /\/builds\/[^\s):]*/gi,
1626
+ // CI builds
1627
+ /\/workspace\/[^\s):]*/gi,
1628
+ // Generic workspace
1629
+ /\/pipeline\/[^\s):]*/gi,
1630
+ // CI pipelines
1631
+ /\/jenkins\/[^\s):]*/gi,
1632
+ // Jenkins
1633
+ /\/bamboo\/[^\s):]*/gi,
1634
+ // Bamboo
1635
+ /\/teamcity\/[^\s):]*/gi,
1636
+ // TeamCity
1637
+ /\/circleci\/[^\s):]*/gi,
1638
+ // CircleCI
1639
+ // Cloud providers
1640
+ /\/aws\/[^\s):]*/gi,
1641
+ // AWS paths
1642
+ /\/gcloud\/[^\s):]*/gi,
1643
+ // Google Cloud
1644
+ /\/azure\/[^\s):]*/gi,
1645
+ // Azure paths
1646
+ /s3:\/\/[^\s):]+/gi,
1647
+ // S3 URIs
1648
+ /gs:\/\/[^\s):]+/gi,
1649
+ // GCS URIs
1650
+ // Secrets and credentials (patterns that might appear in paths or errors)
1651
+ /[A-Z0-9]{20,}/g,
1652
+ // AWS-style access keys (20+ uppercase chars)
1653
+ /sk-[a-zA-Z0-9]{32,}/g,
1654
+ // OpenAI/Stripe-style secret keys
1655
+ /ghp_[a-zA-Z0-9]{36,}/g,
1656
+ // GitHub personal access tokens
1657
+ /gho_[a-zA-Z0-9]{36,}/g,
1658
+ // GitHub OAuth tokens
1659
+ /github_pat_[a-zA-Z0-9_]{22,}/g,
1660
+ // GitHub fine-grained tokens
1661
+ /xox[baprs]-[a-zA-Z0-9-]+/g,
1662
+ // Slack tokens
1663
+ /Bearer\s+[a-zA-Z0-9._-]+/gi,
1664
+ // Bearer tokens
1665
+ /Basic\s+[a-zA-Z0-9+/=]+/gi,
1666
+ // Basic auth
1667
+ // Internal network info
1668
+ /(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
1669
+ // Private IPs
1670
+ /[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
1671
+ // Internal hostnames
1672
+ /localhost:\d+/gi,
1673
+ // Localhost with port
1674
+ /127\.0\.0\.1:\d+/gi,
1675
+ // Loopback with port
1676
+ // User information
1677
+ /\/u\/[^/]+\//gi,
1678
+ // User subdirectories
1679
+ /~[a-z_][a-z0-9_-]*/gi,
1680
+ // Unix user home shorthand
1681
+ // Anything else that is still shaped like a location: an absolute path of two or more
1682
+ // segments, a URL, or a script location such as `agentscript.js:3` / `index.mjs:10:5`.
1683
+ /[a-z][a-z0-9+.-]*:\/\/[^\s)]+/gi,
1684
+ // Other URLs (http://host/bundle.js:1:2)
1685
+ /(?:\/[\w.@%+-]+){2,}\/?/g,
1686
+ // Remaining absolute paths
1687
+ /[\w.@-]+\.(?:[cm]?[jt]sx?|json|node|wasm)(?::\d+){1,2}/gi
1688
+ // file.ext:line[:column]
1689
+ ];
1690
+ FRAME_LINE = /^\s*at\s/;
1691
+ MAX_STACK_LENGTH = 16 * 1024;
1692
+ MAX_LINE_LENGTH = 1e3;
1693
+ REDACTED_FRAME = " at [REDACTED]";
1694
+ }
1695
+ });
1696
+
1235
1697
  // libs/core/src/memory-tracker.ts
1236
1698
  function estimateStringSize2(str) {
1237
1699
  return str.length * 2 + 40;
@@ -1387,16 +1849,16 @@ var init_memory_tracker = __esm({
1387
1849
  });
1388
1850
 
1389
1851
  // libs/core/src/tool-bridge.ts
1390
- function utf8ByteLength(value) {
1852
+ function utf8ByteLength2(value) {
1391
1853
  return Buffer.byteLength(value, "utf8");
1392
1854
  }
1393
- function jsonReplacer(_key, value) {
1855
+ function jsonReplacer2(_key, value) {
1394
1856
  if (typeof value === "bigint") return value.toString();
1395
1857
  if (typeof value === "number" && !Number.isFinite(value)) return null;
1396
1858
  return value;
1397
1859
  }
1398
1860
  function safeJsonStringify(value) {
1399
- return JSON.stringify(value, jsonReplacer);
1861
+ return JSON.stringify(value, jsonReplacer2);
1400
1862
  }
1401
1863
  function truncateForErrorMessage(value, maxChars) {
1402
1864
  if (value.length <= maxChars) return value;
@@ -1437,7 +1899,7 @@ function serializeResponse(response, maxPayloadBytes) {
1437
1899
  }
1438
1900
  });
1439
1901
  }
1440
- if (utf8ByteLength(json) <= maxPayloadBytes) return json;
1902
+ if (utf8ByteLength2(json) <= maxPayloadBytes) return json;
1441
1903
  const minimal = {
1442
1904
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
1443
1905
  ok: false,
@@ -1493,7 +1955,7 @@ function createHostToolBridge(executionContext, options) {
1493
1955
  maxPayloadBytes
1494
1956
  );
1495
1957
  }
1496
- if (utf8ByteLength(requestJson) > maxPayloadBytes) {
1958
+ if (utf8ByteLength2(requestJson) > maxPayloadBytes) {
1497
1959
  return serializeResponse(
1498
1960
  {
1499
1961
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -1634,7 +2096,7 @@ function createHostToolBridge(executionContext, options) {
1634
2096
  {
1635
2097
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
1636
2098
  ok: false,
1637
- error: safeError
2099
+ error: { ...safeError, toolError: true }
1638
2100
  },
1639
2101
  maxPayloadBytes
1640
2102
  );
@@ -1658,13 +2120,13 @@ function createHostToolBridge(executionContext, options) {
1658
2120
  {
1659
2121
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
1660
2122
  ok: false,
1661
- error: safeError
2123
+ error: { ...safeError, toolError: true }
1662
2124
  },
1663
2125
  maxPayloadBytes
1664
2126
  );
1665
2127
  }
1666
2128
  if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
1667
- const size = utf8ByteLength(sanitizedResult);
2129
+ const size = utf8ByteLength2(sanitizedResult);
1668
2130
  if (size >= referenceConfig.extractionThreshold) {
1669
2131
  try {
1670
2132
  const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
@@ -1688,12 +2150,12 @@ function createHostToolBridge(executionContext, options) {
1688
2150
  {
1689
2151
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
1690
2152
  ok: false,
1691
- error: safeError
2153
+ error: { ...safeError, toolError: true }
1692
2154
  },
1693
2155
  maxPayloadBytes
1694
2156
  );
1695
2157
  }
1696
- if (utf8ByteLength(okJson) > maxPayloadBytes) {
2158
+ if (utf8ByteLength2(okJson) > maxPayloadBytes) {
1697
2159
  return serializeResponse(
1698
2160
  {
1699
2161
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -1701,7 +2163,8 @@ function createHostToolBridge(executionContext, options) {
1701
2163
  error: {
1702
2164
  name: "ToolBridgeError",
1703
2165
  message: `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
1704
- code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
2166
+ code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE",
2167
+ toolError: true
1705
2168
  }
1706
2169
  },
1707
2170
  maxPayloadBytes
@@ -1731,6 +2194,64 @@ var init_tool_bridge = __esm({
1731
2194
  }
1732
2195
  });
1733
2196
 
2197
+ // libs/core/src/tool-namespaces.ts
2198
+ function buildToolNamespaceBindings(install, callTool, namespaces) {
2199
+ if (namespaces.length === 0) return [];
2200
+ if (typeof install !== "function") {
2201
+ throw new Error("Tool namespace factory is not available in the sandbox");
2202
+ }
2203
+ const built = install(
2204
+ callTool,
2205
+ JSON.stringify(namespaces)
2206
+ );
2207
+ return namespaces.map((ns) => ({ name: ns.name, value: built[ns.name] }));
2208
+ }
2209
+ var TOOL_NAMESPACE_FACTORY_SOURCE;
2210
+ var init_tool_namespaces = __esm({
2211
+ "libs/core/src/tool-namespaces.ts"() {
2212
+ "use strict";
2213
+ TOOL_NAMESPACE_FACTORY_SOURCE = `
2214
+ (function () {
2215
+ 'use strict';
2216
+ var parse = JSON.parse;
2217
+ var freeze = Object.freeze;
2218
+ var isArray = Array.isArray;
2219
+
2220
+ function isSafeKey(key) {
2221
+ return typeof key === 'string' && key.length > 0 &&
2222
+ !(key.charAt(0) === '_' && key.charAt(1) === '_') &&
2223
+ key !== 'constructor' && key !== 'prototype';
2224
+ }
2225
+
2226
+ function bind(callTool, toolName) {
2227
+ return (args, options) => callTool(toolName, args === undefined ? {} : args, options);
2228
+ }
2229
+
2230
+ return function install(callTool, namespacesJson) {
2231
+ var spec = parse(namespacesJson);
2232
+ var namespaces = { __proto__: null };
2233
+ if (isArray(spec)) {
2234
+ for (var i = 0; i < spec.length; i++) {
2235
+ var ns = spec[i];
2236
+ if (!ns || !isSafeKey(ns.name) || !isArray(ns.methods)) continue;
2237
+ var target = { __proto__: null };
2238
+ for (var j = 0; j < ns.methods.length; j++) {
2239
+ var method = ns.methods[j];
2240
+ if (!method || !isSafeKey(method.name) || typeof method.toolName !== 'string') continue;
2241
+ target[method.name] = bind(callTool, method.toolName);
2242
+ }
2243
+ freeze(target);
2244
+ namespaces[ns.name] = target;
2245
+ }
2246
+ }
2247
+ freeze(namespaces);
2248
+ return namespaces;
2249
+ };
2250
+ })()
2251
+ `.trim();
2252
+ }
2253
+ });
2254
+
1734
2255
  // libs/core/src/double-vm/parent-vm-bootstrap.ts
1735
2256
  function generateSanitizeContextCode(securityLevel) {
1736
2257
  const globalsToRemove = NODEJS_24_DANGEROUS_GLOBALS[securityLevel];
@@ -1772,7 +2293,9 @@ function generateParentVmBootstrap(options) {
1772
2293
  blockedProperties,
1773
2294
  allowComposites = false,
1774
2295
  memoryLimit = 0,
1775
- throwOnBlocked = true
2296
+ throwOnBlocked = true,
2297
+ maxGlobalFunctionCalls = 1e3,
2298
+ toolNamespaces = []
1776
2299
  } = options;
1777
2300
  const sanitizeContextCode = generateSanitizeContextCode(securityLevel);
1778
2301
  const patternDetectorsCode = generatePatternDetectorsCode(suspiciousPatterns);
@@ -2208,6 +2731,8 @@ ${stackTraceHardeningCode}
2208
2731
  const hostReportViolation = __host_reportViolation__;
2209
2732
  const hostConfig = __host_config__;
2210
2733
  const hostMemoryTrack = typeof __host_memory_track__ === 'function' ? __host_memory_track__ : function(){};
2734
+ const hostInvokeGlobal = typeof __host_invokeGlobal__ === 'function' ? __host_invokeGlobal__ : null;
2735
+ const hostIsBuiltinMethod = typeof __host_isBuiltinMethod__ === 'function' ? __host_isBuiltinMethod__ : function() { return false; };
2211
2736
  const toolBridgeMode = ${JSON.stringify(toolBridgeMode)};
2212
2737
  const toolBridgeMaxPayloadBytes = ${toolBridgeMaxPayloadBytes};
2213
2738
 
@@ -2220,6 +2745,8 @@ ${stackTraceHardeningCode}
2220
2745
  try { delete globalThis.__host_reportViolation__; } catch (e) { /* ignore */ }
2221
2746
  try { delete globalThis.__host_config__; } catch (e) { /* ignore */ }
2222
2747
  try { delete globalThis.__host_memory_track__; } catch (e) { /* ignore */ }
2748
+ try { delete globalThis.__host_invokeGlobal__; } catch (e) { /* ignore */ }
2749
+ try { delete globalThis.__host_isBuiltinMethod__; } catch (e) { /* ignore */ }
2223
2750
 
2224
2751
  // Policy violation reporter (best-effort; host decides how to handle based on security level)
2225
2752
  function __ag_reportViolation(kind) {
@@ -2238,6 +2765,29 @@ ${stackTraceHardeningCode}
2238
2765
  } catch (e) { /* ignore */ }
2239
2766
  }
2240
2767
 
2768
+ // SECURITY (GHSA-3279): pin pristine intrinsics BEFORE any sandbox code runs, so the membrane
2769
+ // traps and the error hardening below never re-read a realm global the sandbox can overwrite.
2770
+ // The reported escape replaced Object.getOwnPropertyDescriptor with a hook; the get trap then
2771
+ // called it and handed the attacker the RAW target of a membrane proxy (the host Promise from
2772
+ // callTool), reaching the host Function constructor. The same gadget aimed at the Object.*
2773
+ // mutators below would let an attacker observe safe-error construction or defeat the final
2774
+ // freeze, leaving the returned error with a live prototype and constructor chain. Using
2775
+ // captured references makes a later monkeypatch a no-op.
2776
+ const __ag_getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
2777
+ const __ag_defineProperty = Object.defineProperty;
2778
+ const __ag_defineProperties = Object.defineProperties;
2779
+ const __ag_setPrototypeOf = Object.setPrototypeOf;
2780
+ const __ag_objectCreate = Object.create;
2781
+ const __ag_objectFreeze = Object.freeze;
2782
+ const __ag_ReflectGet = Reflect.get;
2783
+ const __ag_ReflectSet = Reflect.set;
2784
+ const __ag_ReflectDefineProperty = Reflect.defineProperty;
2785
+ const __ag_ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
2786
+ const __ag_ReflectOwnKeys = Reflect.ownKeys;
2787
+ const __ag_ReflectApply = Reflect.apply;
2788
+ const __ag_hasOwnProperty = Object.prototype.hasOwnProperty;
2789
+ const __ag_functionBind = Function.prototype.bind;
2790
+
2241
2791
  /**
2242
2792
  * Creates a "safe" error object that cannot be used to escape the sandbox.
2243
2793
  *
@@ -2260,7 +2810,7 @@ ${stackTraceHardeningCode}
2260
2810
  var error = new Error(message);
2261
2811
  // NOTE: Use Object.defineProperty instead of direct assignment because
2262
2812
  // Error.prototype.name is frozen, and in strict mode direct assignment fails.
2263
- Object.defineProperty(error, 'name', {
2813
+ __ag_defineProperty(error, 'name', {
2264
2814
  value: name,
2265
2815
  writable: true,
2266
2816
  enumerable: false,
@@ -2269,12 +2819,12 @@ ${stackTraceHardeningCode}
2269
2819
 
2270
2820
  // CRITICAL: sever the *actual* prototype chain (native getters / Object.getPrototypeOf).
2271
2821
  // A shadowing __proto__ data property is not sufficient.
2272
- Object.setPrototypeOf(error, null);
2822
+ __ag_setPrototypeOf(error, null);
2273
2823
 
2274
2824
  // Create a null-prototype object to use as a safe "constructor"
2275
2825
  // This object has no prototype chain to climb
2276
- var SafeConstructor = Object.create(null);
2277
- Object.defineProperties(SafeConstructor, {
2826
+ var SafeConstructor = __ag_objectCreate(null);
2827
+ __ag_defineProperties(SafeConstructor, {
2278
2828
  // Make constructor point to itself to break the chain
2279
2829
  constructor: {
2280
2830
  value: SafeConstructor,
@@ -2297,11 +2847,11 @@ ${stackTraceHardeningCode}
2297
2847
  configurable: false
2298
2848
  }
2299
2849
  });
2300
- Object.freeze(SafeConstructor);
2850
+ __ag_objectFreeze(SafeConstructor);
2301
2851
 
2302
2852
  // Override the constructor property on the error instance
2303
2853
  // This breaks the prototype chain: err.constructor.constructor no longer reaches Function
2304
- Object.defineProperty(error, 'constructor', {
2854
+ __ag_defineProperty(error, 'constructor', {
2305
2855
  value: SafeConstructor,
2306
2856
  writable: false,
2307
2857
  enumerable: false,
@@ -2310,7 +2860,7 @@ ${stackTraceHardeningCode}
2310
2860
 
2311
2861
  // SECURITY: Override __proto__ on the error instance to prevent prototype chain escape
2312
2862
  // Attack vector blocked: err.__proto__.constructor.constructor('malicious code')()
2313
- Object.defineProperty(error, '__proto__', {
2863
+ __ag_defineProperty(error, '__proto__', {
2314
2864
  value: null,
2315
2865
  writable: false,
2316
2866
  enumerable: false,
@@ -2320,7 +2870,7 @@ ${stackTraceHardeningCode}
2320
2870
  // SECURITY: Remove the stack property to prevent information leakage (Vector 1230)
2321
2871
  // The stack trace can reveal internal implementation details like function names,
2322
2872
  // file paths, and line numbers which can be used for reconnaissance attacks.
2323
- Object.defineProperty(error, 'stack', {
2873
+ __ag_defineProperty(error, 'stack', {
2324
2874
  value: undefined,
2325
2875
  writable: false,
2326
2876
  enumerable: false,
@@ -2329,7 +2879,7 @@ ${stackTraceHardeningCode}
2329
2879
 
2330
2880
  // Add a unique marker to identify this as a safe error from our runtime
2331
2881
  // This is used by suspicious pattern detection to distinguish our errors from user errors
2332
- Object.defineProperty(error, SAFE_ERROR_MARKER, {
2882
+ __ag_defineProperty(error, SAFE_ERROR_MARKER, {
2333
2883
  value: true,
2334
2884
  writable: false,
2335
2885
  enumerable: false,
@@ -2337,7 +2887,7 @@ ${stackTraceHardeningCode}
2337
2887
  });
2338
2888
 
2339
2889
  // Freeze the error to prevent modifications
2340
- Object.freeze(error);
2890
+ __ag_objectFreeze(error);
2341
2891
 
2342
2892
  return error;
2343
2893
  }
@@ -2366,6 +2916,22 @@ ${stackTraceHardeningCode}
2366
2916
  // Tool call stats for rate limiting
2367
2917
  let toolCallCount = 0;
2368
2918
 
2919
+ // Calls into host functions passed in globals: counted against their own cap, and their
2920
+ // timestamps share the operation rate limit with tool calls. They are not recorded in
2921
+ // operationHistory, so the tool-call suspicious-sequence detectors only see tool calls.
2922
+ let globalFunctionCallCount = 0;
2923
+ const globalFunctionCallTimes = [];
2924
+
2925
+ // Fail-closed: every call into a host function goes through the gate, except the built-in
2926
+ // prototype methods of host data (Array.prototype.map, iterators, Date methods, ...), which
2927
+ // the get trap binds and records here so data globals keep working as before.
2928
+ const ungatedHostFunctions = new WeakSet();
2929
+
2930
+ // Errors that report a failure of the tool itself (the handler threw, or its result could not
2931
+ // be delivered), as opposed to a refusal by the enclave. callTool(..., { throwOnError: false })
2932
+ // turns only these into { success: false, error } results. Keyed by the safe error thrown.
2933
+ const toolFailures = new WeakMap();
2934
+
2369
2935
  // Blocked properties for secure proxy (from security level)
2370
2936
  const blockedPropertiesSet = new Set(${JSON.stringify(blockedProperties)});
2371
2937
 
@@ -2427,7 +2993,7 @@ ${stackTraceHardeningCode}
2427
2993
  var propName = String(property);
2428
2994
 
2429
2995
  // Check if property is non-configurable (proxy invariant requires returning actual value)
2430
- var descriptor = Object.getOwnPropertyDescriptor(target, property);
2996
+ var descriptor = __ag_getOwnPropertyDescriptor(target, property);
2431
2997
  var isNonConfigurable = descriptor && !descriptor.configurable;
2432
2998
 
2433
2999
  // Proxy invariant: if the target has a non-configurable, non-writable data property,
@@ -2448,15 +3014,14 @@ ${stackTraceHardeningCode}
2448
3014
  return exactValue;
2449
3015
  }
2450
3016
 
2451
- // Block dangerous properties - but respect proxy invariants
3017
+ // Block dangerous properties. The ONLY [[Get]] invariant that forces a specific return
3018
+ // value is for a non-writable + non-configurable DATA property \u2014 already handled above.
3019
+ // Anything reaching here is configurable, a non-configurable WRITABLE data property (such
3020
+ // as a function own prototype), or a non-configurable accessor; the invariant constrains
3021
+ // none of these, so the trap must never hand back the raw value. GHSA-3279: the old
3022
+ // "isNonConfigurable and not host -> return Reflect.get(...)" branch leaked the raw
3023
+ // writable prototype, exposing a parent-realm Object and defeating the membrane.
2452
3024
  if (blockedPropertiesSet.has(propName)) {
2453
- // For non-configurable properties, we MUST return the actual value
2454
- // (JavaScript proxy invariant - can't hide non-configurable properties).
2455
- // Host-owned values instead deny the read: every descriptor shape that could force
2456
- // the trap's result was handled above, so returning undefined is invariant-safe.
2457
- if (isNonConfigurable && !host) {
2458
- return Reflect.get(target, property, receiver);
2459
- }
2460
3025
  if (throwOnBlocked) {
2461
3026
  throw createSafeError(
2462
3027
  "Security violation: Access to '" + propName + "' is blocked. " +
@@ -2466,12 +3031,15 @@ ${stackTraceHardeningCode}
2466
3031
  return undefined;
2467
3032
  }
2468
3033
 
2469
- var value = Reflect.get(target, property, receiver);
3034
+ var value = __ag_ReflectGet(target, property, receiver);
2470
3035
 
2471
3036
  // For function values, bind to target first (preserves internal slot access for Promises, etc.)
2472
3037
  // Then recursively proxy the bound function to block constructor access
2473
3038
  if (typeof value === 'function') {
2474
- var boundMethod = value.bind(target);
3039
+ var boundMethod = __ag_functionBind.call(value, target);
3040
+ if (host && hostIsBuiltinMethod(value)) {
3041
+ ungatedHostFunctions.add(boundMethod);
3042
+ }
2475
3043
  return createSecureProxy(boundMethod, depth + 1, host);
2476
3044
  }
2477
3045
 
@@ -2494,7 +3062,7 @@ ${stackTraceHardeningCode}
2494
3062
  }
2495
3063
  return false;
2496
3064
  }
2497
- return Reflect.set(target, property, value, receiver);
3065
+ return __ag_ReflectSet(target, property, value, receiver);
2498
3066
  },
2499
3067
  defineProperty: function(target, property, descriptor) {
2500
3068
  var propName = String(property);
@@ -2507,11 +3075,11 @@ ${stackTraceHardeningCode}
2507
3075
  }
2508
3076
  return false;
2509
3077
  }
2510
- return Reflect.defineProperty(target, property, descriptor);
3078
+ return __ag_ReflectDefineProperty(target, property, descriptor);
2511
3079
  },
2512
3080
  getOwnPropertyDescriptor: function(target, property) {
2513
3081
  var propName = String(property);
2514
- var descriptor = Reflect.getOwnPropertyDescriptor(target, property);
3082
+ var descriptor = __ag_ReflectGetOwnPropertyDescriptor(target, property);
2515
3083
 
2516
3084
  // Mirror the get trap's host-owned pinned-value refusal: a non-configurable, non-writable
2517
3085
  // data property must be reported with its exact value (proxy invariant), so on a HOST-owned
@@ -2560,7 +3128,7 @@ ${stackTraceHardeningCode}
2560
3128
  // hands back a raw function that leads to the host Function constructor.
2561
3129
  if (descriptor && (typeof descriptor.get === 'function' || typeof descriptor.set === 'function')) {
2562
3130
  var accessorWrapped = {};
2563
- for (var ak in descriptor) { if (Object.prototype.hasOwnProperty.call(descriptor, ak)) accessorWrapped[ak] = descriptor[ak]; }
3131
+ for (var ak in descriptor) { if (__ag_hasOwnProperty.call(descriptor, ak)) accessorWrapped[ak] = descriptor[ak]; }
2564
3132
  if (typeof descriptor.get === 'function') accessorWrapped.get = createSecureProxy(descriptor.get, depth + 1, host);
2565
3133
  if (typeof descriptor.set === 'function') accessorWrapped.set = createSecureProxy(descriptor.set, depth + 1, host);
2566
3134
  return accessorWrapped;
@@ -2572,7 +3140,7 @@ ${stackTraceHardeningCode}
2572
3140
  var value = descriptor.value;
2573
3141
  if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
2574
3142
  var wrapped = {};
2575
- for (var dk in descriptor) { if (Object.prototype.hasOwnProperty.call(descriptor, dk)) wrapped[dk] = descriptor[dk]; }
3143
+ for (var dk in descriptor) { if (__ag_hasOwnProperty.call(descriptor, dk)) wrapped[dk] = descriptor[dk]; }
2576
3144
  wrapped.value = createSecureProxy(value, depth + 1, host);
2577
3145
  return wrapped;
2578
3146
  }
@@ -2580,7 +3148,7 @@ ${stackTraceHardeningCode}
2580
3148
  return descriptor;
2581
3149
  },
2582
3150
  ownKeys: function(target) {
2583
- var keys = Reflect.ownKeys(target);
3151
+ var keys = __ag_ReflectOwnKeys(target);
2584
3152
  return keys.filter(function(key) {
2585
3153
  var keyStr = String(key);
2586
3154
  // Keep non-blocked properties
@@ -2588,7 +3156,7 @@ ${stackTraceHardeningCode}
2588
3156
  return true;
2589
3157
  }
2590
3158
  // Must keep non-configurable properties (proxy invariant)
2591
- var descriptor = Object.getOwnPropertyDescriptor(target, key);
3159
+ var descriptor = __ag_getOwnPropertyDescriptor(target, key);
2592
3160
  if (descriptor && !descriptor.configurable) {
2593
3161
  return true;
2594
3162
  }
@@ -2608,18 +3176,29 @@ ${stackTraceHardeningCode}
2608
3176
  // (Promise.prototype up to Function) to reach the host Function constructor for RCE.
2609
3177
  // Results are re-wrapped at a FRESH depth (0) so a chain of calls such as
2610
3178
  // then().then() cannot inflate depth past the recursion cap and leak an unwrapped value.
3179
+ //
3180
+ // SECURITY: a call into a HOST function (a custom global, a method read off one, or
3181
+ // call/apply/bind on one) goes through the global-function gate instead: abort check,
3182
+ // maxGlobalFunctionCalls, the shared operation rate limit, and a sanitized, parent-realm
3183
+ // copy of the result. Without it those calls skipped every limit that guards callTool, and
3184
+ // their results arrived unsanitized. Only built-in methods of host data are exempt.
2611
3185
  apply: function(target, thisArg, args) {
2612
- return createSecureProxy(Reflect.apply(target, thisArg, args), 0, host);
2613
- }
2614
- // NOTE: intentionally NO construct trap here (unlike the standalone secure-proxy used
2615
- // for single-VM mode). Every constructor reachable from sandbox code resolves to an
3186
+ if (host && !ungatedHostFunctions.has(target)) {
3187
+ return callHostFunction(target, thisArg, args);
3188
+ }
3189
+ return createSecureProxy(__ag_ReflectApply(target, thisArg, args), 0, host);
3190
+ },
3191
+ // Constructing a HOST function would hand back a raw host instance without passing the
3192
+ // gate, so it is refused. Realm-owned values keep NO construct trap (undefined here means
3193
+ // the default behavior): every constructor reachable from sandbox code resolves to an
2616
3194
  // inner-VM or parent-VM intrinsic, and BOTH of those realms run with code generation
2617
3195
  // from strings disabled, so a 'new X()' result cannot reach a usable Function
2618
- // constructor. The only code-generation-enabled realm (the host) is reached solely via
2619
- // host return values (callTool), which is an apply-path and is covered above. Wrapping
2620
- // construct results would additionally break the proxy invariant for the frozen (non-
2621
- // extensible) Error objects the harness throws (getPrototypeOf must not report null for
2622
- // a non-extensible target), masking legitimate errors.
3196
+ // constructor. Wrapping construct results would additionally break the proxy invariant
3197
+ // for the frozen (non-extensible) Error objects the harness throws (getPrototypeOf must
3198
+ // not report null for a non-extensible target), masking legitimate errors.
3199
+ construct: host ? function() {
3200
+ throw createSafeError('Host functions cannot be called with new', 'TypeError');
3201
+ } : undefined
2623
3202
  });
2624
3203
 
2625
3204
  cache.set(obj, proxy);
@@ -2631,19 +3210,91 @@ ${stackTraceHardeningCode}
2631
3210
  }
2632
3211
 
2633
3212
  /**
2634
- * Validate an operation before forwarding to host
3213
+ * Operation rate limit, shared by tool calls and calls into host functions.
3214
+ * Sliding one-second window; entries older than two seconds are dropped.
2635
3215
  */
2636
- function validateOperation(operationName, args) {
2637
- // Rate limiting check with sliding window cleanup
2638
- const now = Date.now();
2639
- // Clean up old entries to prevent unbounded growth (keep only last 2 seconds)
3216
+ function enforceRateLimit(now) {
2640
3217
  while (operationHistory.length > 0 && now - operationHistory[0].timestamp > 2000) {
2641
3218
  operationHistory.shift();
2642
3219
  }
2643
- const recentOperations = operationHistory.filter(function(h) { return now - h.timestamp < 1000; });
2644
- if (recentOperations.length >= validationConfig.maxOperationsPerSecond) {
3220
+ while (globalFunctionCallTimes.length > 0 && now - globalFunctionCallTimes[0] > 2000) {
3221
+ globalFunctionCallTimes.shift();
3222
+ }
3223
+ var recent = 0;
3224
+ for (var r = 0; r < operationHistory.length; r++) {
3225
+ if (now - operationHistory[r].timestamp < 1000) recent++;
3226
+ }
3227
+ for (var g = 0; g < globalFunctionCallTimes.length; g++) {
3228
+ if (now - globalFunctionCallTimes[g] < 1000) recent++;
3229
+ }
3230
+ if (recent >= validationConfig.maxOperationsPerSecond) {
2645
3231
  throw createSafeError('Operation rate limit exceeded (' + validationConfig.maxOperationsPerSecond + ' operations/second)');
2646
3232
  }
3233
+ }
3234
+
3235
+ /**
3236
+ * Parse the host invoker's JSON envelope into a parent-realm value, or throw its error.
3237
+ */
3238
+ function decodeGlobalFunctionResult(envelopeJson) {
3239
+ if (typeof envelopeJson !== 'string') {
3240
+ throw createSafeError('Global function bridge returned an invalid response');
3241
+ }
3242
+ var envelope;
3243
+ try {
3244
+ envelope = JSON.parse(envelopeJson);
3245
+ } catch (e) {
3246
+ throw createSafeError('Global function bridge returned invalid JSON');
3247
+ }
3248
+ if (!envelope || typeof envelope !== 'object' || envelope.v !== 1) {
3249
+ throw createSafeError('Global function bridge returned an invalid response');
3250
+ }
3251
+ if (envelope.ok === true) {
3252
+ return __ag_hasOwnProperty.call(envelope, 'value') ? envelope.value : undefined;
3253
+ }
3254
+ var failure = envelope.error;
3255
+ var message = (failure && typeof failure.message === 'string') ? failure.message : 'Global function call failed';
3256
+ var name = (failure && typeof failure.name === 'string') ? failure.name : 'Error';
3257
+ throw createSafeError(message, name);
3258
+ }
3259
+
3260
+ /**
3261
+ * The global-function gate: every call from the sandbox into a host function passed in
3262
+ * globals (including functions nested in objects) comes through here.
3263
+ */
3264
+ function callHostFunction(target, thisArg, args) {
3265
+ if (hostAbortCheck()) {
3266
+ throw createSafeError('Execution aborted');
3267
+ }
3268
+ if (typeof hostInvokeGlobal !== 'function') {
3269
+ throw createSafeError('Global function bridge is not available');
3270
+ }
3271
+
3272
+ globalFunctionCallCount++;
3273
+ if (globalFunctionCallCount > ${maxGlobalFunctionCalls}) {
3274
+ throw createSafeError(${JSON.stringify(globalFunctionLimitMessage(maxGlobalFunctionCalls))});
3275
+ }
3276
+
3277
+ var now = Date.now();
3278
+ enforceRateLimit(now);
3279
+ globalFunctionCallTimes.push(now);
3280
+
3281
+ var outcome = hostInvokeGlobal(target, thisArg, args);
3282
+ if (typeof outcome === 'string') {
3283
+ return createSecureProxy(decodeGlobalFunctionResult(outcome));
3284
+ }
3285
+
3286
+ // A host function that returned a thenable: settle to a sanitized parent-realm value.
3287
+ return createSecureProxy(outcome.then(decodeGlobalFunctionResult).then(function(value) {
3288
+ return createSecureProxy(value);
3289
+ }));
3290
+ }
3291
+
3292
+ /**
3293
+ * Validate an operation before forwarding to host
3294
+ */
3295
+ function validateOperation(operationName, args) {
3296
+ // Rate limiting check with sliding window cleanup
3297
+ enforceRateLimit(Date.now());
2647
3298
 
2648
3299
  // Operation name format validation
2649
3300
  if (typeof operationName !== 'string' || !operationName) {
@@ -2685,11 +3336,64 @@ ${stackTraceHardeningCode}
2685
3336
  }
2686
3337
  }
2687
3338
 
3339
+ /**
3340
+ * Read a script's callTool options. Only { throwOnError: false } changes behavior.
3341
+ */
3342
+ function readThrowOnError(options) {
3343
+ if (options === undefined || options === null) return true;
3344
+ if (typeof options !== 'object') {
3345
+ throw createSafeError('callTool options must be an object', 'TypeError');
3346
+ }
3347
+ return options.throwOnError !== false;
3348
+ }
3349
+
3350
+ /**
3351
+ * Remember that a safe error reports a failure of the tool itself (see toolFailures).
3352
+ */
3353
+ function markToolFailure(error, toolName, name, message, code) {
3354
+ var info = { name: name, message: message, toolName: toolName };
3355
+ if (typeof code === 'string') info.code = code;
3356
+ toolFailures.set(error, info);
3357
+ return error;
3358
+ }
3359
+
3360
+ /**
3361
+ * Whether a tool bridge payload is larger than the limit in UTF-8 bytes, as the host counts it.
3362
+ * A code unit is 1 to 3 bytes (a surrogate pair is 4), so only lengths in between are counted.
3363
+ */
3364
+ function exceedsPayloadLimit(str, maxBytes) {
3365
+ if (str.length > maxBytes) return true;
3366
+ if (str.length * 3 <= maxBytes) return false;
3367
+ var bytes = 0;
3368
+ for (var i = 0; i < str.length; i++) {
3369
+ var c = str.charCodeAt(i);
3370
+ if (c < 0x80) bytes += 1;
3371
+ else if (c < 0x800) bytes += 2;
3372
+ else if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
3373
+ var d = str.charCodeAt(i + 1);
3374
+ if (d >= 0xdc00 && d <= 0xdfff) {
3375
+ bytes += 4;
3376
+ i++;
3377
+ } else {
3378
+ bytes += 3;
3379
+ }
3380
+ } else bytes += 3;
3381
+ if (bytes > maxBytes) return true;
3382
+ }
3383
+ return false;
3384
+ }
3385
+
2688
3386
  /**
2689
3387
  * Inner VM's callTool function
2690
3388
  * Proxies through parent VM with validation
3389
+ *
3390
+ * options.throwOnError === false: a failing tool resolves to { success: false, error } and a
3391
+ * working one to { success: true, data }. Refusals by the enclave (abort, tool-call cap, rate
3392
+ * limit, operation-name and suspicious-sequence checks, invalid arguments) still throw.
2691
3393
  */
2692
- function innerCallTool(toolName, args) {
3394
+ function innerCallTool(toolName, args, options) {
3395
+ var throwOnError = readThrowOnError(options);
3396
+
2693
3397
  // Check if aborted
2694
3398
  if (hostAbortCheck()) {
2695
3399
  throw createSafeError('Execution aborted');
@@ -2738,8 +3442,8 @@ ${stackTraceHardeningCode}
2738
3442
  throw createSafeError('Tool request must be JSON-serializable');
2739
3443
  }
2740
3444
 
2741
- // Conservative byte estimate: UTF-8 is at most 4 bytes per code unit.
2742
- if (requestJson && (requestJson.length * 4) > toolBridgeMaxPayloadBytes) {
3445
+ // Counted in UTF-8 bytes, as the host counts it, so both sides agree on the limit.
3446
+ if (requestJson && exceedsPayloadLimit(requestJson, toolBridgeMaxPayloadBytes)) {
2743
3447
  throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
2744
3448
  }
2745
3449
 
@@ -2748,8 +3452,17 @@ ${stackTraceHardeningCode}
2748
3452
  throw createSafeError('Tool bridge returned non-string response');
2749
3453
  }
2750
3454
 
2751
- if ((responseJson.length * 4) > toolBridgeMaxPayloadBytes) {
2752
- throw createSafeError('Tool response exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
3455
+ // The host refuses an oversized response as a tool failure; this check only backs it up,
3456
+ // and reports the same way so { throwOnError: false } resolves it to a result.
3457
+ if (exceedsPayloadLimit(responseJson, toolBridgeMaxPayloadBytes)) {
3458
+ var tooLarge = 'Tool response exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)';
3459
+ throw markToolFailure(
3460
+ createSafeError(tooLarge, 'RangeError'),
3461
+ toolName,
3462
+ 'RangeError',
3463
+ tooLarge,
3464
+ 'TOOL_BRIDGE_RESPONSE_TOO_LARGE'
3465
+ );
2753
3466
  }
2754
3467
 
2755
3468
  var response;
@@ -2768,7 +3481,7 @@ ${stackTraceHardeningCode}
2768
3481
  }
2769
3482
 
2770
3483
  if (response.ok === true) {
2771
- if (Object.prototype.hasOwnProperty.call(response, 'value')) {
3484
+ if (__ag_hasOwnProperty.call(response, 'value')) {
2772
3485
  return response.value;
2773
3486
  }
2774
3487
  return undefined;
@@ -2778,13 +3491,36 @@ ${stackTraceHardeningCode}
2778
3491
  var err = response.error;
2779
3492
  var msg = (err && typeof err.message === 'string') ? err.message : 'Tool call failed';
2780
3493
  var name = (err && typeof err.name === 'string') ? err.name : 'Error';
2781
- throw createSafeError(msg, name);
3494
+ var failure = createSafeError(msg, name);
3495
+ if (err && err.toolError === true) {
3496
+ markToolFailure(failure, toolName, name, msg, err.code);
3497
+ }
3498
+ throw failure;
2782
3499
  }
2783
3500
 
2784
3501
  throw createSafeError('Tool bridge returned invalid response');
2785
3502
  });
2786
3503
  } else {
2787
- promise = hostCallTool(toolName, sanitizedArgs);
3504
+ promise = hostCallTool(toolName, sanitizedArgs).then(undefined, function(error) {
3505
+ // Direct mode: the host marks failures of the tool itself with this code.
3506
+ if (error && error.code === 'TOOL_CALL_FAILED') {
3507
+ var message = typeof error.message === 'string' ? error.message : 'Tool call failed';
3508
+ throw markToolFailure(createSafeError(message), toolName, 'Error', message, 'TOOL_CALL_FAILED');
3509
+ }
3510
+ throw error;
3511
+ });
3512
+ }
3513
+
3514
+ if (!throwOnError) {
3515
+ promise = promise.then(function(result) {
3516
+ return { success: true, data: result };
3517
+ }, function(error) {
3518
+ var info = toolFailures.get(error);
3519
+ if (info) {
3520
+ return { success: false, error: info };
3521
+ }
3522
+ throw error;
3523
+ });
2788
3524
  }
2789
3525
 
2790
3526
  // Create a secure promise that wraps both the promise object and its result
@@ -3437,6 +4173,36 @@ ${stackTraceHardeningCode}
3437
4173
  innerRuntimeScript.runInContext(innerContext);
3438
4174
  } catch (e) { /* ignore */ }
3439
4175
 
4176
+ // Tool namespaces (mail.list(args)): built INSIDE the inner realm by a factory evaluated there
4177
+ // (before Object/JSON are replaced by the safe globals below), so each namespace is a frozen,
4178
+ // null-prototype inner-realm object whose methods call the gated callTool. A namespace call is
4179
+ // therefore an ordinary tool call: counted, rate-limited, pattern-checked and sanitized.
4180
+ var toolNamespaceNames = ${JSON.stringify(toolNamespaces.map((ns) => ns.name))};
4181
+ if (toolNamespaceNames.length > 0) {
4182
+ var installToolNamespaces = new vm.Script(${JSON.stringify(TOOL_NAMESPACE_FACTORY_SOURCE)}, {
4183
+ filename: 'inner-tool-namespaces.js'
4184
+ }).runInContext(innerContext);
4185
+ var builtToolNamespaces = installToolNamespaces(safeRuntime.__safe_callTool, ${JSON.stringify(
4186
+ JSON.stringify(toolNamespaces)
4187
+ )});
4188
+ for (var tn = 0; tn < toolNamespaceNames.length; tn++) {
4189
+ var toolNamespaceName = toolNamespaceNames[tn];
4190
+ var toolNamespace = builtToolNamespaces[toolNamespaceName];
4191
+ __ag_defineProperty(innerContext, toolNamespaceName, {
4192
+ value: toolNamespace,
4193
+ writable: false,
4194
+ configurable: false,
4195
+ enumerable: false
4196
+ });
4197
+ __ag_defineProperty(innerContext, '__safe_' + toolNamespaceName, {
4198
+ value: toolNamespace,
4199
+ writable: false,
4200
+ configurable: false,
4201
+ enumerable: false
4202
+ });
4203
+ }
4204
+ }
4205
+
3440
4206
  // Defense-in-depth: Remove host callback from inner sandbox after all scripts have captured it
3441
4207
  try { delete innerContext['__host_memory_track__']; } catch (e) { /* ignore */ }
3442
4208
 
@@ -3680,6 +4446,8 @@ var MEMBRANE_MAX_RECURSION_DEPTH, NODEJS_24_DANGEROUS_GLOBALS;
3680
4446
  var init_parent_vm_bootstrap = __esm({
3681
4447
  "libs/core/src/double-vm/parent-vm-bootstrap.ts"() {
3682
4448
  "use strict";
4449
+ init_global_function_gate();
4450
+ init_tool_namespaces();
3683
4451
  MEMBRANE_MAX_RECURSION_DEPTH = 256;
3684
4452
  NODEJS_24_DANGEROUS_GLOBALS = {
3685
4453
  STRICT: [
@@ -3891,36 +4659,7 @@ var init_suspicious_patterns = __esm({
3891
4659
  });
3892
4660
 
3893
4661
  // libs/core/src/double-vm/double-vm-wrapper.ts
3894
- function sanitizeStackTrace(stack, sanitize = true) {
3895
- if (!stack || !sanitize) return stack;
3896
- let sanitized = stack;
3897
- for (const pattern of SENSITIVE_STACK_PATTERNS) {
3898
- pattern.lastIndex = 0;
3899
- sanitized = sanitized.replace(pattern, "[REDACTED]");
3900
- }
3901
- const lines = sanitized.split("\n");
3902
- for (let i = 0; i < lines.length; i++) {
3903
- const line = lines[i];
3904
- if (line.length > 1e3) continue;
3905
- if (/:\d+:\d+\)/.test(line)) {
3906
- const atIdx = line.indexOf("at ");
3907
- if (atIdx !== -1) {
3908
- const afterAt = line.substring(atIdx + 3).trimStart();
3909
- const spaceIdx = afterAt.indexOf(" ");
3910
- if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === "(") {
3911
- const funcName = afterAt.substring(0, spaceIdx);
3912
- lines[i] = line.substring(0, atIdx) + "at " + funcName + " ([REDACTED])";
3913
- continue;
3914
- }
3915
- }
3916
- }
3917
- if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
3918
- lines[i] = line.replace(/:\d+:\d+$/, "") + "[REDACTED]";
3919
- }
3920
- }
3921
- return lines.join("\n");
3922
- }
3923
- var vm2, SENSITIVE_STACK_PATTERNS, DoubleVmWrapper;
4662
+ var vm2, DoubleVmWrapper;
3924
4663
  var init_double_vm_wrapper = __esm({
3925
4664
  "libs/core/src/double-vm/double-vm-wrapper.ts"() {
3926
4665
  "use strict";
@@ -3931,14 +4670,10 @@ var init_double_vm_wrapper = __esm({
3931
4670
  init_reference_resolver();
3932
4671
  init_memory_tracker();
3933
4672
  init_tool_bridge();
4673
+ init_stack_trace();
4674
+ init_global_function_gate();
3934
4675
  init_parent_vm_bootstrap();
3935
4676
  init_suspicious_patterns();
3936
- SENSITIVE_STACK_PATTERNS = [
3937
- /\/Users\/[^/]+\/[^\s):]*/gi,
3938
- /\/home\/[^/]+\/[^\s):]*/gi,
3939
- /\/var\/[^\s):]*/gi,
3940
- /node_modules\/[^\s):]+/gi
3941
- ];
3942
4677
  DoubleVmWrapper = class {
3943
4678
  constructor(config, securityLevel) {
3944
4679
  this.config = config;
@@ -4102,6 +4837,18 @@ var init_double_vm_wrapper = __esm({
4102
4837
  configurable: true
4103
4838
  // Allow deletion after capture for defense-in-depth
4104
4839
  });
4840
+ Object.defineProperty(parentContext, "__host_invokeGlobal__", {
4841
+ value: createHostGlobalFunctionInvoker(executionContext),
4842
+ writable: false,
4843
+ configurable: true
4844
+ // Allow deletion after capture for defense-in-depth
4845
+ });
4846
+ Object.defineProperty(parentContext, "__host_isBuiltinMethod__", {
4847
+ value: (fn) => isBuiltinMethod(fn),
4848
+ writable: false,
4849
+ configurable: true
4850
+ // Allow deletion after capture for defense-in-depth
4851
+ });
4105
4852
  Object.defineProperty(parentContext, "__host_stats__", {
4106
4853
  value: stats,
4107
4854
  writable: false,
@@ -4237,7 +4984,11 @@ var init_double_vm_wrapper = __esm({
4237
4984
  return sanitized;
4238
4985
  } catch (error) {
4239
4986
  const err = error;
4240
- throw createSafeError(`Tool call failed: ${toolName} - ${err.message || "Unknown error"}`);
4987
+ throw createSafeError(
4988
+ `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`,
4989
+ "Error",
4990
+ "TOOL_CALL_FAILED"
4991
+ );
4241
4992
  }
4242
4993
  };
4243
4994
  }
@@ -4282,7 +5033,9 @@ var init_double_vm_wrapper = __esm({
4282
5033
  memoryLimit: config.memoryLimit,
4283
5034
  throwOnBlocked,
4284
5035
  toolBridgeMode,
4285
- toolBridgeMaxPayloadBytes
5036
+ toolBridgeMaxPayloadBytes,
5037
+ maxGlobalFunctionCalls: resolveMaxGlobalFunctionCalls(config),
5038
+ toolNamespaces: executionContext.toolNamespaces ?? []
4286
5039
  });
4287
5040
  }
4288
5041
  /**
@@ -4463,6 +5216,16 @@ var init_memory_proxy = __esm({
4463
5216
  });
4464
5217
 
4465
5218
  // libs/core/src/safe-runtime.ts
5219
+ function readThrowOnError(options) {
5220
+ if (options === void 0 || options === null) return true;
5221
+ if (typeof options !== "object") {
5222
+ throw createSafeTypeError("callTool options must be an object");
5223
+ }
5224
+ return options.throwOnError !== false;
5225
+ }
5226
+ function plainResult(fields) {
5227
+ return Object.assign(/* @__PURE__ */ Object.create(null), fields);
5228
+ }
4466
5229
  function createSafeRuntime(context, options) {
4467
5230
  const { config, stats } = context;
4468
5231
  const sidecar = options?.sidecar;
@@ -4471,7 +5234,8 @@ function createSafeRuntime(context, options) {
4471
5234
  const memoryTracker = options?.memoryTracker;
4472
5235
  const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
4473
5236
  const proxyOptions = secureProxyConfig ? { levelConfig: secureProxyConfig } : {};
4474
- async function __safe_callTool(toolName, args) {
5237
+ async function __safe_callTool(toolName, args, options2) {
5238
+ const throwOnError = readThrowOnError(options2);
4475
5239
  if (context.aborted) {
4476
5240
  throw createSafeError("Execution aborted");
4477
5241
  }
@@ -4515,21 +5279,34 @@ function createSafeRuntime(context, options) {
4515
5279
  allowDates: true,
4516
5280
  allowErrors: true
4517
5281
  });
5282
+ let value = sanitized;
4518
5283
  if (sidecar && referenceConfig && typeof sanitized === "string") {
4519
5284
  const size = Buffer.byteLength(sanitized, "utf-8");
4520
5285
  if (size >= referenceConfig.extractionThreshold) {
4521
5286
  try {
4522
- const refId = sidecar.store(sanitized, "tool-result", { origin: toolName });
4523
- return refId;
5287
+ value = sidecar.store(sanitized, "tool-result", { origin: toolName });
4524
5288
  } catch {
4525
- return sanitized;
5289
+ value = sanitized;
4526
5290
  }
4527
5291
  }
4528
5292
  }
4529
- return sanitized;
5293
+ return throwOnError ? value : plainResult({ success: true, data: value });
4530
5294
  } catch (error) {
4531
5295
  const err = error;
4532
- throw createSafeError(`Tool call failed: ${toolName} - ${err.message || "Unknown error"}`);
5296
+ const message = `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`;
5297
+ if (!throwOnError) {
5298
+ const code = error?.code;
5299
+ return plainResult({
5300
+ success: false,
5301
+ error: plainResult({
5302
+ name: "Error",
5303
+ message,
5304
+ ...typeof code === "string" ? { code } : {},
5305
+ toolName
5306
+ })
5307
+ });
5308
+ }
5309
+ throw createSafeError(message);
4533
5310
  }
4534
5311
  }
4535
5312
  function* __safe_forOf(iterable) {
@@ -4726,7 +5503,8 @@ ${errorMessages}`);
4726
5503
  }
4727
5504
  const customGlobalsWithPrefix = {};
4728
5505
  if (config.globals) {
4729
- const wrappedCustomGlobals = wrapGlobalsWithSecureProxy(config.globals, proxyOptions);
5506
+ const customGlobalProxyOptions = options?.globalFunctionGate ? { ...proxyOptions, callGate: options.globalFunctionGate } : proxyOptions;
5507
+ const wrappedCustomGlobals = wrapGlobalsWithSecureProxy(config.globals, customGlobalProxyOptions);
4730
5508
  for (const [key, value] of Object.entries(wrappedCustomGlobals)) {
4731
5509
  customGlobalsWithPrefix[`__safe_${key}`] = value;
4732
5510
  }
@@ -4781,18 +5559,22 @@ ${errorMessages}`);
4781
5559
  }
4782
5560
  function serializeSafeRuntime() {
4783
5561
  return `
4784
- // Safe callTool implementation
4785
- async function __safe_callTool(toolName, args) {
5562
+ // Safe callTool implementation. The options ({ throwOnError: false }) are passed on:
5563
+ // only the adapter's __internal_callTool can tell a failure of the tool from a refusal.
5564
+ async function __safe_callTool(toolName, args, options) {
4786
5565
  if (typeof toolName !== 'string' || !toolName) {
4787
5566
  throw new TypeError('Tool name must be a non-empty string');
4788
5567
  }
4789
5568
  if (typeof args !== 'object' || args === null || Array.isArray(args)) {
4790
5569
  throw new TypeError('Tool arguments must be an object');
4791
5570
  }
5571
+ if (options !== undefined && options !== null && typeof options !== 'object') {
5572
+ throw new TypeError('callTool options must be an object');
5573
+ }
4792
5574
 
4793
5575
  // This will be replaced by the sandbox adapter with actual implementation
4794
5576
  if (typeof __internal_callTool === 'function') {
4795
- return await __internal_callTool(toolName, args);
5577
+ return await __internal_callTool(toolName, args, options);
4796
5578
  }
4797
5579
  throw new Error('Tool handler not available');
4798
5580
  }
@@ -4961,36 +5743,6 @@ var vm_adapter_exports = {};
4961
5743
  __export(vm_adapter_exports, {
4962
5744
  VmAdapter: () => VmAdapter
4963
5745
  });
4964
- function sanitizeStackTrace2(stack, sanitize = true) {
4965
- if (!stack) return stack;
4966
- if (!sanitize) return stack;
4967
- let sanitized = stack;
4968
- for (const pattern of SENSITIVE_STACK_PATTERNS2) {
4969
- pattern.lastIndex = 0;
4970
- sanitized = sanitized.replace(pattern, "[REDACTED]");
4971
- }
4972
- const lines = sanitized.split("\n");
4973
- for (let i = 0; i < lines.length; i++) {
4974
- const line = lines[i];
4975
- if (line.length > 1e3) continue;
4976
- if (/:\d+:\d+\)/.test(line)) {
4977
- const atIdx = line.indexOf("at ");
4978
- if (atIdx !== -1) {
4979
- const afterAt = line.substring(atIdx + 3).trimStart();
4980
- const spaceIdx = afterAt.indexOf(" ");
4981
- if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === "(") {
4982
- const funcName = afterAt.substring(0, spaceIdx);
4983
- lines[i] = line.substring(0, atIdx) + "at " + funcName + " ([REDACTED])";
4984
- continue;
4985
- }
4986
- }
4987
- }
4988
- if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
4989
- lines[i] = line.replace(/:\d+:\d+$/, "") + "[REDACTED]";
4990
- }
4991
- }
4992
- return lines.join("\n");
4993
- }
4994
5746
  function createSafeConsole(config, stats) {
4995
5747
  const wrap = (method) => (...args) => {
4996
5748
  stats.callCount++;
@@ -5154,7 +5906,7 @@ function sanitizeVmContext(context, securityLevel) {
5154
5906
  enumerable: true
5155
5907
  });
5156
5908
  }
5157
- var vm3, 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;
5909
+ var vm3, 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, SANDBOX_REALM_BRIDGE_SCRIPT, TOOL_NAMESPACE_FACTORY_SCRIPT, PROTECTED_PREFIXES, DANGEROUS_OBJECT_STATIC_METHODS, NODEJS_24_DANGEROUS_GLOBALS2, VmAdapter;
5158
5910
  var init_vm_adapter = __esm({
5159
5911
  "libs/core/src/adapters/vm-adapter.ts"() {
5160
5912
  "use strict";
@@ -5165,130 +5917,9 @@ var init_vm_adapter = __esm({
5165
5917
  init_memory_tracker();
5166
5918
  init_tool_bridge();
5167
5919
  init_value_sanitizer();
5168
- SENSITIVE_STACK_PATTERNS2 = [
5169
- // Unix file system paths
5170
- /\/Users\/[^/]+\/[^\s):]*/gi,
5171
- // macOS home directories
5172
- /\/home\/[^/]+\/[^\s):]*/gi,
5173
- // Linux home directories
5174
- /\/var\/[^\s):]*/gi,
5175
- // System var directories
5176
- /\/opt\/[^\s):]*/gi,
5177
- // Optional software
5178
- /\/tmp\/[^\s):]*/gi,
5179
- // Temporary files
5180
- /\/etc\/[^\s):]*/gi,
5181
- // System configuration
5182
- /\/root\/[^\s):]*/gi,
5183
- // Root home directory
5184
- /\/mnt\/[^\s):]*/gi,
5185
- // Mount points
5186
- /\/srv\/[^\s):]*/gi,
5187
- // Service data
5188
- /\/data\/[^\s):]*/gi,
5189
- // Data directories
5190
- /\/app\/[^\s):]*/gi,
5191
- // Application directories
5192
- /\/proc\/[^\s):]*/gi,
5193
- // Process information
5194
- /\/sys\/[^\s):]*/gi,
5195
- // System files
5196
- // Windows paths
5197
- /\\\\[^\s):]*/g,
5198
- // UNC paths
5199
- /[A-Z]:\\[^\s):]+/gi,
5200
- // Windows drive paths
5201
- // URL-based paths
5202
- /file:\/\/[^\s):]+/gi,
5203
- // File URLs
5204
- /webpack:\/\/[^\s):]+/gi,
5205
- // Webpack paths
5206
- /%2F[^\s):]+/gi,
5207
- // URL-encoded paths
5208
- // Package managers and node
5209
- /node_modules\/[^\s):]+/gi,
5210
- // Node modules paths
5211
- /\/nix\/store\/[^\s):]*/gi,
5212
- // Nix store paths
5213
- /\.npm\/[^\s):]*/gi,
5214
- // NPM cache
5215
- /\.yarn\/[^\s):]*/gi,
5216
- // Yarn cache
5217
- /\.pnpm\/[^\s):]*/gi,
5218
- // PNPM cache
5219
- // Container and orchestration
5220
- /\/run\/secrets\/[^\s):]*/gi,
5221
- // Docker/K8s secrets
5222
- /\/var\/run\/[^\s):]*/gi,
5223
- // Runtime directories
5224
- /\/docker\/[^\s):]*/gi,
5225
- // Docker paths
5226
- /\/containers\/[^\s):]*/gi,
5227
- // Container paths
5228
- /\/kubelet\/[^\s):]*/gi,
5229
- // Kubernetes kubelet
5230
- // CI/CD systems
5231
- /\/github\/workspace\/[^\s):]*/gi,
5232
- // GitHub Actions
5233
- /\/runner\/[^\s):]*/gi,
5234
- // GitHub/GitLab runner
5235
- /\/builds\/[^\s):]*/gi,
5236
- // CI builds
5237
- /\/workspace\/[^\s):]*/gi,
5238
- // Generic workspace
5239
- /\/pipeline\/[^\s):]*/gi,
5240
- // CI pipelines
5241
- /\/jenkins\/[^\s):]*/gi,
5242
- // Jenkins
5243
- /\/bamboo\/[^\s):]*/gi,
5244
- // Bamboo
5245
- /\/teamcity\/[^\s):]*/gi,
5246
- // TeamCity
5247
- /\/circleci\/[^\s):]*/gi,
5248
- // CircleCI
5249
- // Cloud providers
5250
- /\/aws\/[^\s):]*/gi,
5251
- // AWS paths
5252
- /\/gcloud\/[^\s):]*/gi,
5253
- // Google Cloud
5254
- /\/azure\/[^\s):]*/gi,
5255
- // Azure paths
5256
- /s3:\/\/[^\s):]+/gi,
5257
- // S3 URIs
5258
- /gs:\/\/[^\s):]+/gi,
5259
- // GCS URIs
5260
- // Secrets and credentials (patterns that might appear in paths or errors)
5261
- /[A-Z0-9]{20,}/g,
5262
- // AWS-style access keys (20+ uppercase chars)
5263
- /sk-[a-zA-Z0-9]{32,}/g,
5264
- // OpenAI/Stripe-style secret keys
5265
- /ghp_[a-zA-Z0-9]{36,}/g,
5266
- // GitHub personal access tokens
5267
- /gho_[a-zA-Z0-9]{36,}/g,
5268
- // GitHub OAuth tokens
5269
- /github_pat_[a-zA-Z0-9_]{22,}/g,
5270
- // GitHub fine-grained tokens
5271
- /xox[baprs]-[a-zA-Z0-9-]+/g,
5272
- // Slack tokens
5273
- /Bearer\s+[a-zA-Z0-9._-]+/gi,
5274
- // Bearer tokens
5275
- /Basic\s+[a-zA-Z0-9+/=]+/gi,
5276
- // Basic auth
5277
- // Internal network info
5278
- /(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
5279
- // Private IPs
5280
- /[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
5281
- // Internal hostnames
5282
- /localhost:\d+/gi,
5283
- // Localhost with port
5284
- /127\.0\.0\.1:\d+/gi,
5285
- // Loopback with port
5286
- // User information
5287
- /\/u\/[^/]+\//gi,
5288
- // User subdirectories
5289
- /~[a-z_][a-z0-9_-]*/gi
5290
- // Unix user home shorthand
5291
- ];
5920
+ init_stack_trace();
5921
+ init_global_function_gate();
5922
+ init_tool_namespaces();
5292
5923
  STACK_TRACE_HARDENING_CODE = `
5293
5924
  (function() {
5294
5925
  function __ag_redactStackString(stackStr) {
@@ -5454,6 +6085,20 @@ var init_vm_adapter = __esm({
5454
6085
  })();
5455
6086
  `;
5456
6087
  INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new vm3.Script(INTRINSIC_OBJECT_NEUTRALIZATION_CODE);
6088
+ SANDBOX_REALM_BRIDGE_SCRIPT = new vm3.Script(`
6089
+ (function () {
6090
+ 'use strict';
6091
+ var parse = JSON.parse;
6092
+ var SandboxPromise = Promise;
6093
+ return Object.freeze({
6094
+ parseJson: function (json) { return parse(json); },
6095
+ adoptPromise: function (hostPromise) {
6096
+ return new SandboxPromise(function (resolve, reject) { hostPromise.then(resolve, reject); });
6097
+ }
6098
+ });
6099
+ })()
6100
+ `);
6101
+ TOOL_NAMESPACE_FACTORY_SCRIPT = new vm3.Script(TOOL_NAMESPACE_FACTORY_SOURCE, { filename: "tool-namespaces.js" });
5457
6102
  PROTECTED_PREFIXES = ["__safe_", "__ag_"];
5458
6103
  DANGEROUS_OBJECT_STATIC_METHODS = [
5459
6104
  "defineProperty",
@@ -5569,19 +6214,23 @@ var init_vm_adapter = __esm({
5569
6214
  }) : void 0;
5570
6215
  memoryTracker?.start();
5571
6216
  try {
5572
- const safeRuntime = createSafeRuntime(executionContext, {
5573
- sidecar: executionContext.sidecar,
5574
- referenceConfig: executionContext.referenceConfig,
5575
- secureProxyConfig: executionContext.secureProxyConfig,
5576
- memoryTracker
5577
- // Pass tracker for allocation monitoring
5578
- });
5579
6217
  const baseSandbox = vm3.createContext(
5580
6218
  {},
5581
6219
  {
5582
6220
  codeGeneration: { strings: false, wasm: false }
5583
6221
  }
5584
6222
  );
6223
+ const realmBridge = SANDBOX_REALM_BRIDGE_SCRIPT.runInContext(baseSandbox);
6224
+ const installToolNamespaces = executionContext.toolNamespaces?.length ? TOOL_NAMESPACE_FACTORY_SCRIPT.runInContext(baseSandbox) : void 0;
6225
+ const globalFunctionGate = createGlobalFunctionGate(executionContext, realmBridge);
6226
+ const safeRuntime = createSafeRuntime(executionContext, {
6227
+ sidecar: executionContext.sidecar,
6228
+ referenceConfig: executionContext.referenceConfig,
6229
+ secureProxyConfig: executionContext.secureProxyConfig,
6230
+ memoryTracker,
6231
+ // Pass tracker for allocation monitoring
6232
+ globalFunctionGate
6233
+ });
5585
6234
  if (memoryTracker && config.memoryLimit && config.memoryLimit > 0) {
5586
6235
  Object.defineProperty(baseSandbox, "__host_memory_track__", {
5587
6236
  value: (bytes) => {
@@ -5745,9 +6394,28 @@ var init_vm_adapter = __esm({
5745
6394
  // Remove global handle after capture (defense-in-depth)
5746
6395
  try { delete globalThis.__host_callToolBridge__; } catch (e) { /* ignore */ }
5747
6396
 
5748
- function estimateBytes(str) {
5749
- // Conservative: UTF-8 can be up to 4 bytes per code unit.
5750
- return str.length * 4;
6397
+ // Whether a payload is larger than the limit in UTF-8 bytes, as the host counts it. A code
6398
+ // unit is 1 to 3 bytes (a surrogate pair is 4), so only lengths in between are counted.
6399
+ function exceedsPayloadLimit(str) {
6400
+ if (str.length > maxBytes) return true;
6401
+ if (str.length * 3 <= maxBytes) return false;
6402
+ var bytes = 0;
6403
+ for (var i = 0; i < str.length; i++) {
6404
+ var c = str.charCodeAt(i);
6405
+ if (c < 0x80) bytes += 1;
6406
+ else if (c < 0x800) bytes += 2;
6407
+ else if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
6408
+ var d = str.charCodeAt(i + 1);
6409
+ if (d >= 0xdc00 && d <= 0xdfff) {
6410
+ bytes += 4;
6411
+ i++;
6412
+ } else {
6413
+ bytes += 3;
6414
+ }
6415
+ } else bytes += 3;
6416
+ if (bytes > maxBytes) return true;
6417
+ }
6418
+ return false;
5751
6419
  }
5752
6420
 
5753
6421
  function makeError(message, name) {
@@ -5756,7 +6424,16 @@ var init_vm_adapter = __esm({
5756
6424
  return err;
5757
6425
  }
5758
6426
 
5759
- return async function __safe_callTool(toolName, args) {
6427
+ return async function __safe_callTool(toolName, args, options) {
6428
+ // callTool options: only { throwOnError: false } changes behavior. Tool failures
6429
+ // then resolve to { success: false, error }; the enclave's own refusals still throw.
6430
+ var throwOnError = true;
6431
+ if (options !== undefined && options !== null) {
6432
+ if (typeof options !== 'object') {
6433
+ throw makeError('callTool options must be an object', 'TypeError');
6434
+ }
6435
+ throwOnError = options.throwOnError !== false;
6436
+ }
5760
6437
  if (typeof toolName !== 'string' || !toolName) {
5761
6438
  throw makeError('Tool name must be a non-empty string', 'TypeError');
5762
6439
  }
@@ -5782,7 +6459,7 @@ var init_vm_adapter = __esm({
5782
6459
  throw makeError('Tool request must be JSON-serializable', 'TypeError');
5783
6460
  }
5784
6461
 
5785
- if (estimateBytes(requestJson) > maxBytes) {
6462
+ if (exceedsPayloadLimit(requestJson)) {
5786
6463
  throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
5787
6464
  }
5788
6465
 
@@ -5790,8 +6467,24 @@ var init_vm_adapter = __esm({
5790
6467
  if (typeof responseJson !== 'string') {
5791
6468
  throw makeError('Tool bridge returned invalid response', 'Error');
5792
6469
  }
5793
- if (estimateBytes(responseJson) > maxBytes) {
5794
- throw makeError('Tool response exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
6470
+ // The host refuses an oversized response as a tool failure; this check only backs it
6471
+ // up, and reports the same way so { throwOnError: false } resolves it to a result.
6472
+ if (exceedsPayloadLimit(responseJson)) {
6473
+ var tooLarge = 'Tool response exceeds maximum size (' + maxBytes + ' bytes)';
6474
+ if (!throwOnError) {
6475
+ return {
6476
+ __proto__: null,
6477
+ success: false,
6478
+ error: {
6479
+ __proto__: null,
6480
+ name: 'RangeError',
6481
+ message: tooLarge,
6482
+ toolName: toolName,
6483
+ code: 'TOOL_BRIDGE_RESPONSE_TOO_LARGE',
6484
+ },
6485
+ };
6486
+ }
6487
+ throw makeError(tooLarge, 'RangeError');
5795
6488
  }
5796
6489
 
5797
6490
  var response;
@@ -5806,13 +6499,18 @@ var init_vm_adapter = __esm({
5806
6499
  }
5807
6500
 
5808
6501
  if (response.ok === true) {
5809
- if (hasOwn.call(response, 'value')) return response.value;
5810
- return undefined;
6502
+ var value = hasOwn.call(response, 'value') ? response.value : undefined;
6503
+ return throwOnError ? value : { __proto__: null, success: true, data: value };
5811
6504
  }
5812
6505
 
5813
6506
  if (response.ok === false && response.error) {
5814
6507
  var msg = (typeof response.error.message === 'string') ? response.error.message : 'Tool call failed';
5815
6508
  var name = (typeof response.error.name === 'string') ? response.error.name : 'Error';
6509
+ if (!throwOnError && response.error.toolError === true) {
6510
+ var info = { __proto__: null, name: name, message: msg, toolName: toolName };
6511
+ if (typeof response.error.code === 'string') info.code = response.error.code;
6512
+ return { __proto__: null, success: false, error: info };
6513
+ }
5816
6514
  throw makeError(msg, name);
5817
6515
  }
5818
6516
 
@@ -5846,8 +6544,9 @@ var init_vm_adapter = __esm({
5846
6544
  }
5847
6545
  if (config.globals) {
5848
6546
  for (const [key, value2] of Object.entries(config.globals)) {
5849
- const wrappedValue = value2 !== null && typeof value2 === "object" ? createSecureProxy(value2, {
5850
- levelConfig: executionContext.secureProxyConfig
6547
+ const wrappedValue = value2 !== null && (typeof value2 === "object" || typeof value2 === "function") ? createSecureProxy(value2, {
6548
+ levelConfig: executionContext.secureProxyConfig,
6549
+ callGate: globalFunctionGate
5851
6550
  }) : value2;
5852
6551
  Object.defineProperty(baseSandbox, key, {
5853
6552
  value: wrappedValue,
@@ -5857,6 +6556,23 @@ var init_vm_adapter = __esm({
5857
6556
  });
5858
6557
  }
5859
6558
  }
6559
+ if (executionContext.toolNamespaces?.length) {
6560
+ const callTool = baseSandbox["__safe_callTool"];
6561
+ for (const binding of buildToolNamespaceBindings(
6562
+ installToolNamespaces,
6563
+ callTool,
6564
+ executionContext.toolNamespaces
6565
+ )) {
6566
+ for (const name of [binding.name, `__safe_${binding.name}`]) {
6567
+ Object.defineProperty(baseSandbox, name, {
6568
+ value: binding.value,
6569
+ writable: false,
6570
+ configurable: false,
6571
+ enumerable: false
6572
+ });
6573
+ }
6574
+ }
6575
+ }
5860
6576
  if (!("__safe_console" in safeRuntime)) {
5861
6577
  const consoleStats = { totalBytes: 0, callCount: 0 };
5862
6578
  Object.defineProperty(baseSandbox, "__safe_console", {
@@ -5964,7 +6680,7 @@ var init_vm_adapter = __esm({
5964
6680
  error: {
5965
6681
  name: err.name || "VMExecutionError",
5966
6682
  message: err.message || "Unknown VM execution error",
5967
- stack: sanitizeStackTrace2(err.stack, shouldSanitize),
6683
+ stack: sanitizeStackTrace(err.stack, shouldSanitize),
5968
6684
  code: "VM_EXECUTION_ERROR"
5969
6685
  },
5970
6686
  stats
@@ -6116,12 +6832,13 @@ function isExecutionResultMessage(msg) {
6116
6832
  function isConsoleMessage(msg) {
6117
6833
  return msg.type === "console";
6118
6834
  }
6119
- var import_zod, TOOL_NAME_PATTERN, ID_PATTERN, toolCallMessageSchema, executionResultMessageSchema, memoryReportResultMessageSchema, consoleMessageSchema, workerReadyMessageSchema, workerToMainMessageSchema;
6835
+ var import_zod, import_ast3, TOOL_NAME_PATTERN, ID_PATTERN, toolCallMessageSchema, executionResultMessageSchema, memoryReportResultMessageSchema, consoleMessageSchema, workerReadyMessageSchema, workerToMainMessageSchema;
6120
6836
  var init_protocol = __esm({
6121
6837
  "libs/core/src/adapters/worker-pool/protocol.ts"() {
6122
6838
  "use strict";
6123
6839
  import_zod = require("zod");
6124
- TOOL_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9:_-]*$/;
6840
+ import_ast3 = require("@enclave-vm/ast");
6841
+ TOOL_NAME_PATTERN = import_ast3.TOOL_NAMESPACE_TOOL_NAME_PATTERN;
6125
6842
  ID_PATTERN = /^[a-zA-Z0-9-]+$/;
6126
6843
  toolCallMessageSchema = import_zod.z.object({
6127
6844
  type: import_zod.z.literal("tool-call"),
@@ -6309,7 +7026,7 @@ var init_errors = __esm({
6309
7026
 
6310
7027
  // libs/core/src/adapters/worker-pool/safe-deserialize.ts
6311
7028
  function mapArraySafely(value, sanitizeItem) {
6312
- const rawLen = ReflectGet3(value, "length");
7029
+ const rawLen = ReflectGet4(value, "length");
6313
7030
  const len = typeof rawLen === "number" && NumberIsFinite3(rawLen) && rawLen >= 0 ? MathFloor3(rawLen) : 0;
6314
7031
  if (len > MAX_ARRAY_LENGTH) {
6315
7032
  throw new MessageValidationError(`Array exceeds maximum length of ${MAX_ARRAY_LENGTH}`);
@@ -6318,7 +7035,7 @@ function mapArraySafely(value, sanitizeItem) {
6318
7035
  for (let i = 0; i < len; i++) {
6319
7036
  let item;
6320
7037
  try {
6321
- item = ReflectGet3(value, i);
7038
+ item = ReflectGet4(value, i);
6322
7039
  } catch {
6323
7040
  item = void 0;
6324
7041
  }
@@ -6353,7 +7070,7 @@ function sanitizeObjectWithDepthCheck(value, depth) {
6353
7070
  if (typeof value !== "object") {
6354
7071
  return value;
6355
7072
  }
6356
- if (ArrayIsArray2(value)) {
7073
+ if (ArrayIsArray3(value)) {
6357
7074
  return mapArraySafely(value, (item) => sanitizeObjectWithDepthCheck(item, depth + 1));
6358
7075
  }
6359
7076
  const result = /* @__PURE__ */ Object.create(null);
@@ -6382,7 +7099,7 @@ function sanitizeObject(value, depth = 0) {
6382
7099
  if (typeof value !== "object") {
6383
7100
  return value;
6384
7101
  }
6385
- if (ArrayIsArray2(value)) {
7102
+ if (ArrayIsArray3(value)) {
6386
7103
  return mapArraySafely(value, (item) => sanitizeObject(item, depth + 1));
6387
7104
  }
6388
7105
  const result = /* @__PURE__ */ Object.create(null);
@@ -6393,13 +7110,13 @@ function sanitizeObject(value, depth = 0) {
6393
7110
  }
6394
7111
  return result;
6395
7112
  }
6396
- var ReflectGet3, ArrayIsArray2, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
7113
+ var ReflectGet4, ArrayIsArray3, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
6397
7114
  var init_safe_deserialize = __esm({
6398
7115
  "libs/core/src/adapters/worker-pool/safe-deserialize.ts"() {
6399
7116
  "use strict";
6400
7117
  init_errors();
6401
- ReflectGet3 = Reflect.get;
6402
- ArrayIsArray2 = Array.isArray;
7118
+ ReflectGet4 = Reflect.get;
7119
+ ArrayIsArray3 = Array.isArray;
6403
7120
  NumberIsFinite3 = Number.isFinite;
6404
7121
  MathFloor3 = Math.floor;
6405
7122
  MAX_ARRAY_LENGTH = 1e6;
@@ -7112,6 +7829,7 @@ var init_worker_pool_adapter = __esm({
7112
7829
  init_rate_limiter();
7113
7830
  init_safe_deserialize();
7114
7831
  init_errors();
7832
+ init_stack_trace();
7115
7833
  WorkerPoolAdapter = class {
7116
7834
  config;
7117
7835
  securityLevel;
@@ -7350,7 +8068,8 @@ var init_worker_pool_adapter = __esm({
7350
8068
  globals: context.config.globals,
7351
8069
  // Security level determines which globals are available in sandbox
7352
8070
  // This mirrors AST guard's allowed globals for defense-in-depth
7353
- securityLevel: this.securityLevel
8071
+ securityLevel: this.securityLevel,
8072
+ toolNamespaces: context.toolNamespaces ? [...context.toolNamespaces] : void 0
7354
8073
  };
7355
8074
  return new Promise((resolve, reject) => {
7356
8075
  const pendingToolCalls = /* @__PURE__ */ new Map();
@@ -7367,7 +8086,7 @@ var init_worker_pool_adapter = __esm({
7367
8086
  } else if (isExecutionResultMessage(msg) && msg.requestId === requestId) {
7368
8087
  cleanup();
7369
8088
  const duration = Date.now() - startTime;
7370
- const result = this.buildResult(msg, duration);
8089
+ const result = this.buildResult(msg, duration, context.config.sanitizeStackTraces);
7371
8090
  resolve(result);
7372
8091
  } else if (isConsoleMessage(msg) && msg.requestId === requestId) {
7373
8092
  this.handleConsoleMessage(msg);
@@ -7408,17 +8127,30 @@ var init_worker_pool_adapter = __esm({
7408
8127
  pendingToolCalls.set(msg.callId, true);
7409
8128
  let result;
7410
8129
  let error;
8130
+ let toolError = false;
7411
8131
  try {
7412
8132
  if (!context.toolHandler) {
7413
8133
  throw new Error("No tool handler configured");
7414
8134
  }
7415
8135
  const sanitizedArgs = sanitizeObject(msg.args);
7416
- result = await context.toolHandler(msg.toolName, sanitizedArgs);
8136
+ toolError = true;
8137
+ const handlerResult = await context.toolHandler(msg.toolName, sanitizedArgs);
8138
+ try {
8139
+ result = sanitizeObject(handlerResult);
8140
+ } catch {
8141
+ throw Object.assign(new Error("Tool returned an unsupported value"), {
8142
+ name: "ToolBridgeError",
8143
+ code: "TOOL_RESULT_NOT_SAFE"
8144
+ });
8145
+ }
8146
+ toolError = false;
7417
8147
  } catch (e) {
7418
8148
  const err = e;
8149
+ const code = e?.code;
7419
8150
  error = {
7420
8151
  name: err.name || "Error",
7421
- message: err.message || "Unknown error"
8152
+ message: err.message || "Unknown error",
8153
+ ...toolError && typeof code === "string" ? { code } : {}
7422
8154
  };
7423
8155
  } finally {
7424
8156
  pendingToolCalls.delete(msg.callId);
@@ -7427,8 +8159,9 @@ var init_worker_pool_adapter = __esm({
7427
8159
  type: "tool-response",
7428
8160
  requestId: msg.requestId,
7429
8161
  callId: msg.callId,
7430
- result: sanitizeObject(result),
7431
- error
8162
+ result,
8163
+ error,
8164
+ ...error && toolError ? { toolError: true } : {}
7432
8165
  });
7433
8166
  }
7434
8167
  handleConsoleMessage(msg) {
@@ -7445,7 +8178,7 @@ var init_worker_pool_adapter = __esm({
7445
8178
  * before sending, but full runtime type validation would require schema
7446
8179
  * definitions which are not available at this layer.
7447
8180
  */
7448
- buildResult(msg, duration) {
8181
+ buildResult(msg, duration, sanitizeStacks) {
7449
8182
  if (msg.success) {
7450
8183
  return {
7451
8184
  success: true,
@@ -7466,7 +8199,8 @@ var init_worker_pool_adapter = __esm({
7466
8199
  name: error.name,
7467
8200
  message: error.message,
7468
8201
  code: error.code,
7469
- stack: error.stack
8202
+ // The worker trims its stack; sanitize it here too so the result obeys the option.
8203
+ stack: sanitizeStackTrace(error.stack, sanitizeStacks)
7470
8204
  },
7471
8205
  stats: {
7472
8206
  duration,
@@ -7668,7 +8402,7 @@ __export(index_exports, {
7668
8402
  module.exports = __toCommonJS(index_exports);
7669
8403
 
7670
8404
  // libs/core/src/enclave.ts
7671
- var import_ast3 = require("@enclave-vm/ast");
8405
+ var import_ast4 = require("@enclave-vm/ast");
7672
8406
 
7673
8407
  // libs/core/src/babel/babel-wrapper.ts
7674
8408
  var vm = __toESM(require("vm"));
@@ -8171,8 +8905,8 @@ function transformMultiple(files, options, limits, singleFileTransform) {
8171
8905
  }
8172
8906
 
8173
8907
  // libs/core/src/enclave.ts
8174
- var import_ast4 = require("@enclave-vm/ast");
8175
8908
  var import_ast5 = require("@enclave-vm/ast");
8909
+ var import_ast6 = require("@enclave-vm/ast");
8176
8910
  var acorn2 = __toESM(require("acorn"));
8177
8911
  var import_astring = require("astring");
8178
8912
 
@@ -8354,6 +9088,7 @@ var DEFAULT_DOUBLE_VM_CONFIG = {
8354
9088
  };
8355
9089
 
8356
9090
  // libs/core/src/globals-validator.ts
9091
+ var import_util = require("util");
8357
9092
  var DANGEROUS_FUNCTION_PATTERNS = [
8358
9093
  /\beval\b/,
8359
9094
  // eval() calls
@@ -8381,7 +9116,55 @@ var DANGEROUS_FUNCTION_PATTERNS = [
8381
9116
  // Synchronous spawn
8382
9117
  ];
8383
9118
  var DANGEROUS_GLOBAL_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
8384
- function validateGlobalValue(key, value, options = {}, path2 = [], visited = /* @__PURE__ */ new WeakSet()) {
9119
+ var MapEntries = Map.prototype.entries;
9120
+ var SetValues = Set.prototype.values;
9121
+ var ReflectApply = Reflect.apply;
9122
+ var ReflectOwnKeys = Reflect.ownKeys;
9123
+ var ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
9124
+ var ObjectGetPrototypeOf = Object.getPrototypeOf;
9125
+ var ArrayPrototype = Array.prototype;
9126
+ var MapPrototype = Map.prototype;
9127
+ var SetPrototype = Set.prototype;
9128
+ var IteratorPrototype = ObjectGetPrototypeOf(ObjectGetPrototypeOf([][Symbol.iterator]()));
9129
+ var AsyncIteratorPrototype = ObjectGetPrototypeOf(
9130
+ ObjectGetPrototypeOf(
9131
+ async function* () {
9132
+ }.prototype
9133
+ )
9134
+ );
9135
+ function describeOpaqueContainer(obj) {
9136
+ if (import_util.types.isPromise(obj)) return "a Promise";
9137
+ if (import_util.types.isWeakMap(obj)) return "a WeakMap";
9138
+ if (import_util.types.isGeneratorObject(obj)) return "a generator";
9139
+ if (import_util.types.isMapIterator(obj) || import_util.types.isSetIterator(obj) || Object.prototype.isPrototypeOf.call(IteratorPrototype, obj) || Object.prototype.isPrototypeOf.call(AsyncIteratorPrototype, obj)) {
9140
+ return "an iterator";
9141
+ }
9142
+ return void 0;
9143
+ }
9144
+ function isPlainDataObject(obj) {
9145
+ const proto = ObjectGetPrototypeOf(obj);
9146
+ return proto === null || proto === Object.prototype || import_util.types.isDate(obj) || import_util.types.isRegExp(obj) || import_util.types.isArrayBufferView(obj) || import_util.types.isAnyArrayBuffer(obj);
9147
+ }
9148
+ function describeInstance(obj) {
9149
+ try {
9150
+ const name = ObjectGetPrototypeOf(obj)?.constructor?.name;
9151
+ if (typeof name === "string" && name) return `a ${name} instance`;
9152
+ } catch {
9153
+ }
9154
+ return "a non-plain object";
9155
+ }
9156
+ function collectionError(key, what, path2) {
9157
+ return new Error(
9158
+ `Custom global "${key}" contains ${what} inside a collection at ${path2.join(".") || "root"}. Only plain data (primitives, plain objects, arrays, Maps, Sets, Dates, RegExps, typed arrays) is allowed inside arrays, Maps and Sets: their built-in methods (forEach, iteration, get) hand elements to the script directly, so a function there would be called without the enclave's global-function gate. Expose functions as properties of a plain object, or as tools.`
9159
+ );
9160
+ }
9161
+ function mapValueSegment(mapKey, index) {
9162
+ if (typeof mapKey === "string" || typeof mapKey === "number" || typeof mapKey === "boolean") {
9163
+ return `get(${JSON.stringify(mapKey)})`;
9164
+ }
9165
+ return `values()[${index}]`;
9166
+ }
9167
+ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /* @__PURE__ */ new WeakSet(), collectionVisited = /* @__PURE__ */ new WeakSet(), inCollection = false) {
8385
9168
  const maxDepth = options.maxDepth ?? 10;
8386
9169
  const allowFunctions = options.allowFunctions ?? false;
8387
9170
  const allowGettersSetters = options.allowGettersSetters ?? false;
@@ -8405,6 +9188,9 @@ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /*
8405
9188
  }
8406
9189
  if (type === "function") {
8407
9190
  const funcName = value.name || "anonymous";
9191
+ if (inCollection && (allowFunctions || allowedFunctionNames.includes(funcName))) {
9192
+ throw collectionError(key, "a function", path2);
9193
+ }
8408
9194
  if (allowedFunctionNames.includes(funcName)) {
8409
9195
  return;
8410
9196
  }
@@ -8431,35 +9217,89 @@ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /*
8431
9217
  }
8432
9218
  if (type === "object") {
8433
9219
  const obj = value;
8434
- if (visited.has(obj)) {
9220
+ const seen = inCollection ? collectionVisited : visited;
9221
+ if (seen.has(obj)) {
8435
9222
  return;
8436
9223
  }
8437
- visited.add(obj);
9224
+ seen.add(obj);
9225
+ const opaque = describeOpaqueContainer(obj);
9226
+ if (opaque) {
9227
+ throw new Error(
9228
+ `Custom global "${key}" contains ${opaque} at ${path2.join(".") || "root"}. Promises, WeakMaps, iterators and generators are not allowed in custom globals: their contents cannot be validated, and their built-in methods hand those contents to the script directly.`
9229
+ );
9230
+ }
9231
+ const isArray = Array.isArray(obj);
9232
+ const isMap = import_util.types.isMap(obj);
9233
+ const isSet = import_util.types.isSet(obj);
9234
+ if (isArray) {
9235
+ const hidden = import_util.types.isProxy(obj) ? "a Proxy array" : ObjectGetPrototypeOf(obj) !== ArrayPrototype ? "an array with a custom prototype" : void 0;
9236
+ if (hidden) {
9237
+ throw new Error(
9238
+ `Custom global "${key}" contains ${hidden} at ${path2.join(".") || "root"}. Only plain arrays are allowed in custom globals: their built-in methods (forEach, iteration) read entries that a Proxy or a prototype can hide from validation, and hand them to the script directly.`
9239
+ );
9240
+ }
9241
+ }
9242
+ if (inCollection) {
9243
+ if (import_util.types.isProxy(obj)) {
9244
+ throw collectionError(key, "a Proxy", path2);
9245
+ }
9246
+ if (!isArray && !isMap && !isSet && !isPlainDataObject(obj)) {
9247
+ throw collectionError(key, describeInstance(obj), path2);
9248
+ }
9249
+ if ((isMap || isSet) && ObjectGetPrototypeOf(obj) !== (isMap ? MapPrototype : SetPrototype)) {
9250
+ throw collectionError(key, describeInstance(obj), path2);
9251
+ }
9252
+ }
8438
9253
  if (!allowGettersSetters) {
8439
- const descriptors = Object.getOwnPropertyDescriptors(obj);
8440
- for (const [prop, desc] of Object.entries(descriptors)) {
8441
- if (desc.get || desc.set) {
9254
+ for (const prop of ReflectOwnKeys(obj)) {
9255
+ const desc = ReflectGetOwnPropertyDescriptor(obj, prop);
9256
+ if (desc && (desc.get || desc.set)) {
9257
+ const at = [...path2, typeof prop === "string" ? prop : `[${String(prop)}]`].join(".");
8442
9258
  throw new Error(
8443
- `Custom global "${key}" has a getter/setter at ${[...path2, prop].join(".")}. Getters and setters are not allowed because they can execute arbitrary code on property access. Use allowGettersSetters: true if you understand the security implications.`
9259
+ `Custom global "${key}" has a getter/setter at ${at}. Getters and setters are not allowed because they can execute arbitrary code on property access. Use allowGettersSetters: true if you understand the security implications.`
8444
9260
  );
8445
9261
  }
8446
9262
  }
8447
9263
  }
8448
- if (Array.isArray(obj)) {
8449
- for (let i = 0; i < obj.length; i++) {
8450
- validateGlobalValue(key, obj[i], options, [...path2, String(i)], visited);
9264
+ if (isMap) {
9265
+ let index = 0;
9266
+ for (const [mapKey, mapValue] of ReflectApply(MapEntries, obj, [])) {
9267
+ validateGlobalValue(key, mapKey, options, [...path2, `keys()[${index}]`], visited, collectionVisited, true);
9268
+ validateGlobalValue(
9269
+ key,
9270
+ mapValue,
9271
+ options,
9272
+ [...path2, mapValueSegment(mapKey, index)],
9273
+ visited,
9274
+ collectionVisited,
9275
+ true
9276
+ );
9277
+ index++;
9278
+ }
9279
+ } else if (isSet) {
9280
+ let index = 0;
9281
+ for (const element of ReflectApply(SetValues, obj, [])) {
9282
+ validateGlobalValue(key, element, options, [...path2, `values()[${index}]`], visited, collectionVisited, true);
9283
+ index++;
8451
9284
  }
8452
- return;
8453
9285
  }
8454
- const keys = Object.keys(obj);
9286
+ const keys = isArray || inCollection ? ReflectOwnKeys(obj) : Object.keys(obj);
8455
9287
  for (const prop of keys) {
8456
- if (DANGEROUS_GLOBAL_KEYS.has(prop)) {
9288
+ if (typeof prop === "string" && DANGEROUS_GLOBAL_KEYS.has(prop)) {
8457
9289
  throw new Error(
8458
9290
  `Custom global "${key}" contains dangerous key "${prop}" at ${path2.join(".") || "root"}. Keys like "__proto__", "constructor", and "prototype" are not allowed.`
8459
9291
  );
8460
9292
  }
8461
9293
  const propValue = obj[prop];
8462
- validateGlobalValue(key, propValue, options, [...path2, prop], visited);
9294
+ validateGlobalValue(
9295
+ key,
9296
+ propValue,
9297
+ options,
9298
+ [...path2, typeof prop === "string" ? prop : `[${String(prop)}]`],
9299
+ visited,
9300
+ collectionVisited,
9301
+ inCollection || isArray
9302
+ );
8463
9303
  }
8464
9304
  return;
8465
9305
  }
@@ -10353,6 +11193,8 @@ function createScoringGate(config) {
10353
11193
  }
10354
11194
 
10355
11195
  // libs/core/src/enclave.ts
11196
+ init_global_function_gate();
11197
+ init_stack_trace();
10356
11198
  var DEFAULT_SECURITY_LEVEL = "STANDARD";
10357
11199
  var DEFAULT_TOOL_BRIDGE_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
10358
11200
  function getConfigFromSecurityLevel(securityLevel, options) {
@@ -10407,6 +11249,7 @@ var Enclave = class {
10407
11249
  scoringGate;
10408
11250
  doubleVmConfig;
10409
11251
  customGlobalNames;
11252
+ toolNamespaces;
10410
11253
  adapter;
10411
11254
  constructor(options = {}) {
10412
11255
  this.securityLevel = options.securityLevel ?? DEFAULT_SECURITY_LEVEL;
@@ -10440,7 +11283,7 @@ var Enclave = class {
10440
11283
  };
10441
11284
  const presetName = options.preset ?? "agentscript";
10442
11285
  if (presetName === "babel") {
10443
- const babelConfig = (0, import_ast3.getBabelConfig)(this.securityLevel);
11286
+ const babelConfig = (0, import_ast4.getBabelConfig)(this.securityLevel);
10444
11287
  const restrictedBabel = createRestrictedBabel({
10445
11288
  maxInputSize: babelConfig.maxInputSize,
10446
11289
  maxOutputSize: babelConfig.maxOutputSize,
@@ -10462,6 +11305,12 @@ var Enclave = class {
10462
11305
  }
10463
11306
  };
10464
11307
  }
11308
+ this.toolNamespaces = (0, import_ast6.normalizeToolNamespaces)(options.toolNamespaces, {
11309
+ reservedNames: Object.keys(initialGlobals)
11310
+ });
11311
+ if (options.maxGlobalFunctionCalls !== void 0 && !(Number.isInteger(options.maxGlobalFunctionCalls) && options.maxGlobalFunctionCalls >= 0)) {
11312
+ throw new TypeError("maxGlobalFunctionCalls must be a non-negative integer");
11313
+ }
10465
11314
  this.config = {
10466
11315
  ...BASE_CONFIG,
10467
11316
  timeout: securityConfig.timeout,
@@ -10476,9 +11325,13 @@ var Enclave = class {
10476
11325
  toolBridge: normalizedToolBridge,
10477
11326
  // secureProxyConfig must come AFTER options spread to use the merged config
10478
11327
  secureProxyConfig: securityConfig.secureProxyConfig,
10479
- globals: initialGlobals
11328
+ globals: initialGlobals,
11329
+ maxGlobalFunctionCalls: resolveMaxGlobalFunctionCalls({
11330
+ maxToolCalls: securityConfig.maxToolCalls,
11331
+ maxGlobalFunctionCalls: options.maxGlobalFunctionCalls
11332
+ })
10480
11333
  };
10481
- this.customGlobalNames = Object.keys(initialGlobals);
11334
+ this.customGlobalNames = [...Object.keys(initialGlobals), ...this.toolNamespaces.map((ns) => ns.name)];
10482
11335
  const customAllowedGlobals = this.customGlobalNames.flatMap((name) => [name, `__safe_${name}`]);
10483
11336
  this.validator = this.createValidator(presetName, customAllowedGlobals);
10484
11337
  this.validateCode = options.validate !== false;
@@ -10522,11 +11375,31 @@ var Enclave = class {
10522
11375
  /**
10523
11376
  * Execute AgentScript code
10524
11377
  *
11378
+ * Every error returned obeys `sanitizeStackTraces`, whichever stage raised it.
11379
+ *
10525
11380
  * @param code AgentScript code to execute
10526
11381
  * @param toolHandler Optional tool handler (overrides constructor config)
10527
11382
  * @returns Execution result
10528
11383
  */
10529
11384
  async run(code, toolHandler) {
11385
+ const result = await this.execute(code, toolHandler);
11386
+ return this.applyStackTracePolicy(result);
11387
+ }
11388
+ /**
11389
+ * Single exit for returned errors: with `sanitizeStackTraces` on, strip host paths, file
11390
+ * locations and frames from the stack, whichever stage (validation, transform, compile,
11391
+ * execution, tool call) and adapter produced the error.
11392
+ */
11393
+ applyStackTracePolicy(result) {
11394
+ if (result.success || !result.error?.stack || !this.config.sanitizeStackTraces) {
11395
+ return result;
11396
+ }
11397
+ return { ...result, error: { ...result.error, stack: sanitizeStackTrace(result.error.stack, true) } };
11398
+ }
11399
+ /**
11400
+ * Transform, validate and execute. `run` applies the stack-trace policy to what this returns.
11401
+ */
11402
+ async execute(code, toolHandler) {
10530
11403
  const startTime = Date.now();
10531
11404
  const stats = {
10532
11405
  duration: 0,
@@ -10539,8 +11412,8 @@ var Enclave = class {
10539
11412
  try {
10540
11413
  let transformedCode = code;
10541
11414
  if (this.transformCode) {
10542
- const needsWrapping = !(0, import_ast4.isWrappedInMain)(code);
10543
- transformedCode = (0, import_ast4.transformAgentScript)(code, {
11415
+ const needsWrapping = !(0, import_ast5.isWrappedInMain)(code);
11416
+ transformedCode = (0, import_ast5.transformAgentScript)(code, {
10544
11417
  wrapInMain: needsWrapping,
10545
11418
  transformCallTool: true,
10546
11419
  transformLoops: true,
@@ -10611,7 +11484,8 @@ ${errorMessages}`,
10611
11484
  toolHandler: toolHandler || this.config.toolHandler,
10612
11485
  sidecar,
10613
11486
  referenceConfig: this.referenceConfig,
10614
- secureProxyConfig: this.config.secureProxyConfig
11487
+ secureProxyConfig: this.config.secureProxyConfig,
11488
+ toolNamespaces: this.toolNamespaces
10615
11489
  };
10616
11490
  const timeoutId = setTimeout(() => {
10617
11491
  context.aborted = true;
@@ -10683,7 +11557,7 @@ ${errorMessages}`,
10683
11557
  const throwOnBlocked = proxyConfig.throwOnBlocked ?? true;
10684
11558
  const parseModule = (source) => acorn2.parse(source, { ecmaVersion: "latest", sourceType: "module" });
10685
11559
  const ast = parseModule(code);
10686
- const { guardedCount } = (0, import_ast5.guardComputedMemberKeys)(ast, parseModule, { blockedKeys, throwOnBlocked });
11560
+ const { guardedCount } = (0, import_ast6.guardComputedMemberKeys)(ast, parseModule, { blockedKeys, throwOnBlocked });
10687
11561
  if (guardedCount === 0) {
10688
11562
  return code;
10689
11563
  }
@@ -10694,8 +11568,8 @@ ${errorMessages}`,
10694
11568
  ecmaVersion: "latest",
10695
11569
  sourceType: "module"
10696
11570
  });
10697
- (0, import_ast5.transformConcatenation)(ast);
10698
- (0, import_ast5.transformTemplateLiterals)(ast);
11571
+ (0, import_ast6.transformConcatenation)(ast);
11572
+ (0, import_ast6.transformTemplateLiterals)(ast);
10699
11573
  return (0, import_astring.generate)(ast);
10700
11574
  }
10701
11575
  /**
@@ -10713,15 +11587,15 @@ ${errorMessages}`,
10713
11587
  sourceType: "module"
10714
11588
  });
10715
11589
  if (this.referenceConfig?.extractionThreshold) {
10716
- (0, import_ast5.extractLargeStrings)(ast, {
11590
+ (0, import_ast6.extractLargeStrings)(ast, {
10717
11591
  threshold: this.referenceConfig.extractionThreshold,
10718
11592
  onExtract: (value) => {
10719
11593
  return sidecar.store(value, "extraction");
10720
11594
  }
10721
11595
  });
10722
11596
  }
10723
- (0, import_ast5.transformConcatenation)(ast);
10724
- (0, import_ast5.transformTemplateLiterals)(ast);
11597
+ (0, import_ast6.transformConcatenation)(ast);
11598
+ (0, import_ast6.transformTemplateLiterals)(ast);
10725
11599
  return (0, import_astring.generate)(ast);
10726
11600
  }
10727
11601
  /**
@@ -10800,7 +11674,7 @@ ${errorMessages}`,
10800
11674
  * @returns A configured JSAstValidator
10801
11675
  */
10802
11676
  createValidator(presetName, customAllowedGlobals) {
10803
- const securityLevelGlobals = (0, import_ast3.getAgentScriptGlobals)(this.securityLevel);
11677
+ const securityLevelGlobals = (0, import_ast4.getAgentScriptGlobals)(this.securityLevel);
10804
11678
  const enclaveSpecificGlobals = [
10805
11679
  "parallel",
10806
11680
  // Parallel execution API
@@ -10814,24 +11688,24 @@ ${errorMessages}`,
10814
11688
  const allAllowedGlobals = [...securityLevelGlobals, ...enclaveSpecificGlobals, ...customAllowedGlobals];
10815
11689
  switch (presetName) {
10816
11690
  case "agentscript":
10817
- return new import_ast3.JSAstValidator(
10818
- (0, import_ast3.createAgentScriptPreset)({
11691
+ return new import_ast4.JSAstValidator(
11692
+ (0, import_ast4.createAgentScriptPreset)({
10819
11693
  securityLevel: this.securityLevel,
10820
11694
  allowedGlobals: allAllowedGlobals,
10821
11695
  allowDynamicArrayFill: this.config.memoryLimit > 0
10822
11696
  })
10823
11697
  );
10824
11698
  case "strict":
10825
- return new import_ast3.JSAstValidator((0, import_ast3.createStrictPreset)());
11699
+ return new import_ast4.JSAstValidator((0, import_ast4.createStrictPreset)());
10826
11700
  case "secure":
10827
- return new import_ast3.JSAstValidator((0, import_ast3.createSecurePreset)());
11701
+ return new import_ast4.JSAstValidator((0, import_ast4.createSecurePreset)());
10828
11702
  case "standard":
10829
- return new import_ast3.JSAstValidator((0, import_ast3.createStandardPreset)());
11703
+ return new import_ast4.JSAstValidator((0, import_ast4.createStandardPreset)());
10830
11704
  case "permissive":
10831
- return new import_ast3.JSAstValidator((0, import_ast3.createPermissivePreset)());
11705
+ return new import_ast4.JSAstValidator((0, import_ast4.createPermissivePreset)());
10832
11706
  case "babel":
10833
- return new import_ast3.JSAstValidator(
10834
- (0, import_ast3.createBabelPreset)({
11707
+ return new import_ast4.JSAstValidator(
11708
+ (0, import_ast4.createBabelPreset)({
10835
11709
  securityLevel: this.securityLevel,
10836
11710
  allowedGlobals: allAllowedGlobals,
10837
11711
  allowDynamicArrayFill: this.config.memoryLimit > 0
@@ -11422,7 +12296,11 @@ var Interpreter = class {
11422
12296
  const obj = value ?? {};
11423
12297
  for (const prop of pattern.properties) {
11424
12298
  if (prop.type === "RestElement") continue;
11425
- const key = prop.key.name;
12299
+ if (prop.computed) throw new InterpreterError("Computed destructuring keys are not allowed");
12300
+ let key;
12301
+ if (prop.key.type === "Identifier") key = prop.key.name;
12302
+ else if (prop.key.type === "Literal") key = String(prop.key.value);
12303
+ else throw new InterpreterError("Unsupported destructuring key");
11426
12304
  if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden destructured key: ${key}`);
11427
12305
  this.bindPattern(prop.value, obj[key], scope, mutable);
11428
12306
  }
@@ -11485,6 +12363,7 @@ function applyBinary(op, l, r) {
11485
12363
  }
11486
12364
 
11487
12365
  // libs/core/src/adapters/interpreter-adapter.ts
12366
+ init_stack_trace();
11488
12367
  var SAFE_GLOBALS = Object.freeze({ Math, JSON });
11489
12368
  var DEFAULT_MAX_STEPS = 5e6;
11490
12369
  var DEFAULT_MAX_CALL_DEPTH = 256;
@@ -11495,6 +12374,7 @@ var InterpreterAdapter = class {
11495
12374
  async execute(code, context) {
11496
12375
  const startTime = Date.now();
11497
12376
  let toolCallCount = 0;
12377
+ const sanitizeStacks = context.config.sanitizeStackTraces === true;
11498
12378
  const maxToolCalls = context.config.maxToolCalls ?? Number.POSITIVE_INFINITY;
11499
12379
  const toolHandler = context.toolHandler ?? context.config.toolHandler;
11500
12380
  const __safe_callTool = async (name, args) => {
@@ -11511,7 +12391,7 @@ var InterpreterAdapter = class {
11511
12391
  try {
11512
12392
  program = acorn3.parse(code, { ecmaVersion: "latest", sourceType: "script" });
11513
12393
  } catch (error) {
11514
- return this.fail(error, startTime, toolCallCount, 0, "SyntaxError");
12394
+ return this.fail(error, startTime, toolCallCount, 0, sanitizeStacks, "SyntaxError");
11515
12395
  }
11516
12396
  const timeout = context.config.timeout;
11517
12397
  const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
@@ -11536,6 +12416,7 @@ var InterpreterAdapter = class {
11536
12416
  startTime,
11537
12417
  toolCallCount,
11538
12418
  interpreter.stepCount,
12419
+ sanitizeStacks,
11539
12420
  "TimeoutError",
11540
12421
  "EXECUTION_TIMEOUT"
11541
12422
  );
@@ -11547,7 +12428,7 @@ var InterpreterAdapter = class {
11547
12428
  };
11548
12429
  } catch (error) {
11549
12430
  const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
11550
- return this.fail(error, startTime, toolCallCount, interpreter.stepCount, void 0, code2);
12431
+ return this.fail(error, startTime, toolCallCount, interpreter.stepCount, sanitizeStacks, void 0, code2);
11551
12432
  } finally {
11552
12433
  if (timer) clearTimeout(timer);
11553
12434
  if (timeoutHandle) clearTimeout(timeoutHandle);
@@ -11559,12 +12440,13 @@ var InterpreterAdapter = class {
11559
12440
  const endTime = Date.now();
11560
12441
  return { duration: endTime - startTime, toolCallCount, iterationCount, startTime, endTime };
11561
12442
  }
11562
- fail(error, startTime, toolCallCount, iterationCount, name, code) {
12443
+ fail(error, startTime, toolCallCount, iterationCount, sanitizeStacks, name, code) {
11563
12444
  const err = error instanceof Error ? error : new Error(String(error));
12445
+ const stack = sanitizeStackTrace(err.stack, sanitizeStacks);
11564
12446
  const execError = {
11565
12447
  message: err.message,
11566
12448
  name: name ?? err.name,
11567
- ...err.stack ? { stack: err.stack } : {},
12449
+ ...stack ? { stack } : {},
11568
12450
  ...code ? { code } : {}
11569
12451
  };
11570
12452
  return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };