@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/esm/index.mjs CHANGED
@@ -9,9 +9,17 @@ var __export = (target, all) => {
9
9
  };
10
10
 
11
11
  // libs/core/src/safe-error.ts
12
- function createSafeError(message, name = "Error") {
12
+ function createSafeError(message, name = "Error", code) {
13
13
  const error = new Error(message);
14
14
  error.name = name;
15
+ if (typeof code === "string") {
16
+ Object.defineProperty(error, "code", {
17
+ value: code,
18
+ writable: false,
19
+ enumerable: false,
20
+ configurable: false
21
+ });
22
+ }
15
23
  const SafeConstructor = /* @__PURE__ */ Object.create(null);
16
24
  Object.defineProperties(SafeConstructor, {
17
25
  constructor: {
@@ -70,6 +78,7 @@ function getBlockedPropertiesForLevel(level) {
70
78
  const blocked = /* @__PURE__ */ new Set();
71
79
  if (level !== "PERMISSIVE") {
72
80
  BLOCKED_PROPERTY_CATEGORIES.PROTOTYPE.forEach((p) => blocked.add(p));
81
+ BLOCKED_PROPERTY_CATEGORIES.DESCRIPTOR_MUTATION.forEach((p) => blocked.add(p));
73
82
  }
74
83
  switch (level) {
75
84
  case "STRICT":
@@ -90,6 +99,7 @@ function buildBlockedPropertiesFromConfig(config) {
90
99
  const blocked = /* @__PURE__ */ new Set();
91
100
  if (config.blockConstructor) {
92
101
  blocked.add("constructor");
102
+ BLOCKED_PROPERTY_CATEGORIES.DESCRIPTOR_MUTATION.forEach((p) => blocked.add(p));
93
103
  }
94
104
  if (config.blockPrototype) {
95
105
  blocked.add("__proto__");
@@ -112,27 +122,35 @@ function createSafeReflect(securityLevel) {
112
122
  dangerousMethods.add("apply");
113
123
  dangerousMethods.add("defineProperty");
114
124
  }
115
- return new Proxy(Reflect, {
116
- get(target, prop) {
125
+ const refuseMutation = () => {
126
+ throw createSafeError("Reflect is read-only in the sandbox", "SecurityError");
127
+ };
128
+ return new Proxy(ReflectObject, {
129
+ set: refuseMutation,
130
+ defineProperty: refuseMutation,
131
+ deleteProperty: refuseMutation,
132
+ setPrototypeOf: refuseMutation,
133
+ preventExtensions: refuseMutation,
134
+ get(_target, prop) {
117
135
  if (typeof prop === "string" && dangerousMethods.has(prop)) {
118
136
  return void 0;
119
137
  }
120
- const value = Reflect.get(target, prop);
138
+ if (!PINNED_REFLECT_VALUES.has(prop)) {
139
+ return void 0;
140
+ }
141
+ const value = PINNED_REFLECT_VALUES.get(prop);
121
142
  if (typeof value === "function" && prop === "construct") {
122
- const safeConstruct = function(ctorTarget, args, newTarget) {
123
- const AsyncFunction = async function() {
124
- }.constructor;
125
- const GeneratorFunction = function* () {
126
- }.constructor;
127
- const AsyncGeneratorFunction = async function* () {
128
- }.constructor;
129
- if (ctorTarget === Function || ctorTarget === AsyncFunction || ctorTarget === GeneratorFunction || ctorTarget === AsyncGeneratorFunction) {
143
+ const safeConstruct = function(ctorTarget, args, ...newTarget) {
144
+ if (ctorTarget === FunctionCtor || ctorTarget === AsyncFunctionCtor || ctorTarget === GeneratorFunctionCtor || ctorTarget === AsyncGeneratorFunctionCtor) {
130
145
  throw createSafeError("Reflect.construct with function constructors is blocked", "SecurityError");
131
146
  }
132
- return Reflect.construct(
147
+ if (newTarget.length === 0) {
148
+ return ReflectConstruct(ctorTarget, args);
149
+ }
150
+ return ReflectConstruct(
133
151
  ctorTarget,
134
152
  args,
135
- newTarget
153
+ newTarget[0]
136
154
  );
137
155
  };
138
156
  return createSecureProxy(safeConstruct);
@@ -144,6 +162,14 @@ function createSafeReflect(securityLevel) {
144
162
  }
145
163
  });
146
164
  }
165
+ function gatedProxyCache(gate) {
166
+ let cache = gatedProxyCaches.get(gate);
167
+ if (!cache) {
168
+ cache = /* @__PURE__ */ new WeakMap();
169
+ gatedProxyCaches.set(gate, cache);
170
+ }
171
+ return cache;
172
+ }
147
173
  function getFullCacheKey(options) {
148
174
  const parts = [];
149
175
  if (options.levelConfig) {
@@ -169,7 +195,7 @@ function getFullCacheKey(options) {
169
195
  function isProxyable(value) {
170
196
  if (value === null) return false;
171
197
  if (typeof value !== "object" && typeof value !== "function") return false;
172
- const tag = Object.prototype.toString.call(value);
198
+ const tag = ReflectApply2(ObjectToString, value, []);
173
199
  if (NON_PROXYABLE_TYPES.has(tag)) {
174
200
  return false;
175
201
  }
@@ -180,12 +206,11 @@ function createSecureProxy(target, options = {}) {
180
206
  return target;
181
207
  }
182
208
  const cacheKey = getFullCacheKey(options);
183
- const targetCache = proxyCache.get(target);
184
- if (targetCache) {
185
- const cached = targetCache.get(cacheKey);
186
- if (cached) {
187
- return cached;
188
- }
209
+ const gateCache = options.callGate ? gatedProxyCache(options.callGate) : void 0;
210
+ const lookupCached = (obj) => gateCache ? gateCache.get(obj) : proxyCache.get(obj)?.get(cacheKey);
211
+ const cached = lookupCached(target);
212
+ if (cached) {
213
+ return cached;
189
214
  }
190
215
  const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
191
216
  const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
@@ -196,12 +221,9 @@ function createSecureProxy(target, options = {}) {
196
221
  if (!isProxyable(obj)) {
197
222
  return obj;
198
223
  }
199
- const objCache = proxyCache.get(obj);
200
- if (objCache) {
201
- const cachedProxy = objCache.get(cacheKey);
202
- if (cachedProxy) {
203
- return cachedProxy;
204
- }
224
+ const cachedProxy = lookupCached(obj);
225
+ if (cachedProxy) {
226
+ return cachedProxy;
205
227
  }
206
228
  if (depth > maxDepth) {
207
229
  throw createSafeError(
@@ -212,7 +234,7 @@ function createSecureProxy(target, options = {}) {
212
234
  const proxy = new Proxy(obj, {
213
235
  get(target2, property, receiver) {
214
236
  const propName = typeof property === "symbol" ? property.toString() : property;
215
- const descriptor = Object.getOwnPropertyDescriptor(target2, property);
237
+ const descriptor = ObjectGetOwnPropertyDescriptor(target2, property);
216
238
  if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
217
239
  const exactValue = descriptor.value;
218
240
  if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
@@ -247,11 +269,11 @@ function createSecureProxy(target, options = {}) {
247
269
  }
248
270
  return void 0;
249
271
  }
250
- const value = Reflect.get(target2, property, receiver);
272
+ const value = ReflectGet(target2, property, receiver);
251
273
  if (typeof value === "function") {
252
- const tag = Object.prototype.toString.call(target2);
274
+ const tag = ReflectApply2(ObjectToString, target2, []);
253
275
  if (INTERNAL_SLOT_TYPES.has(tag)) {
254
- const boundMethod = value.bind(target2);
276
+ const boundMethod = ReflectApply2(FunctionBind, value, [target2]);
255
277
  return proxyWithDepth(boundMethod, depth + 1);
256
278
  }
257
279
  }
@@ -275,7 +297,7 @@ function createSecureProxy(target, options = {}) {
275
297
  }
276
298
  return false;
277
299
  }
278
- return Reflect.set(target2, property, value, receiver);
300
+ return ReflectSet(target2, property, value, receiver);
279
301
  },
280
302
  // Block defining dangerous properties
281
303
  defineProperty(target2, property, descriptor) {
@@ -292,18 +314,18 @@ function createSecureProxy(target, options = {}) {
292
314
  }
293
315
  return false;
294
316
  }
295
- return Reflect.defineProperty(target2, property, descriptor);
317
+ return ReflectDefineProperty(target2, property, descriptor);
296
318
  },
297
319
  // Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
298
320
  // Must respect proxy invariants: non-configurable own properties cannot be hidden
299
321
  ownKeys(target2) {
300
- const keys = Reflect.ownKeys(target2);
322
+ const keys = ReflectOwnKeys2(target2);
301
323
  return keys.filter((key) => {
302
324
  const keyStr = typeof key === "symbol" ? key.toString() : key;
303
325
  if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
304
326
  return true;
305
327
  }
306
- const descriptor = Object.getOwnPropertyDescriptor(target2, key);
328
+ const descriptor = ObjectGetOwnPropertyDescriptor(target2, key);
307
329
  if (descriptor && !descriptor.configurable) {
308
330
  return true;
309
331
  }
@@ -314,7 +336,7 @@ function createSecureProxy(target, options = {}) {
314
336
  // Must respect proxy invariants: non-configurable properties must return actual descriptor
315
337
  getOwnPropertyDescriptor(target2, property) {
316
338
  const propName = typeof property === "symbol" ? property.toString() : property;
317
- const descriptor = Reflect.getOwnPropertyDescriptor(target2, property);
339
+ const descriptor = ReflectGetOwnPropertyDescriptor2(target2, property);
318
340
  if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
319
341
  const exactValue = descriptor.value;
320
342
  if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
@@ -373,7 +395,10 @@ function createSecureProxy(target, options = {}) {
373
395
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
374
396
  apply(target2, thisArg, argArray) {
375
397
  const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
376
- const result = Reflect.apply(target2, unwrappedThis, argArray);
398
+ if (options.callGate && options.callGate.gates(target2)) {
399
+ return options.callGate.call(target2, unwrappedThis, argArray);
400
+ }
401
+ const result = ReflectApply2(target2, unwrappedThis, argArray);
377
402
  if (isProxyable(result)) {
378
403
  return proxyWithDepth(result, depth + 1);
379
404
  }
@@ -384,19 +409,26 @@ function createSecureProxy(target, options = {}) {
384
409
  // host Function constructor — the same escape class the apply trap closes for calls.
385
410
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
386
411
  construct(target2, argArray, newTarget) {
387
- const instance = Reflect.construct(target2, argArray, newTarget === proxy ? target2 : newTarget);
412
+ if (options.callGate && options.callGate.gates(target2)) {
413
+ throw createSafeError("Host functions cannot be called with new", "TypeError");
414
+ }
415
+ const instance = ReflectConstruct(target2, argArray, newTarget === proxy ? target2 : newTarget);
388
416
  if (isProxyable(instance)) {
389
417
  return proxyWithDepth(instance, depth + 1);
390
418
  }
391
419
  return instance;
392
420
  }
393
421
  });
394
- let objCacheMap = proxyCache.get(obj);
395
- if (!objCacheMap) {
396
- objCacheMap = /* @__PURE__ */ new Map();
397
- proxyCache.set(obj, objCacheMap);
422
+ if (gateCache) {
423
+ gateCache.set(obj, proxy);
424
+ } else {
425
+ let objCacheMap = proxyCache.get(obj);
426
+ if (!objCacheMap) {
427
+ objCacheMap = /* @__PURE__ */ new Map();
428
+ proxyCache.set(obj, objCacheMap);
429
+ }
430
+ objCacheMap.set(cacheKey, proxy);
398
431
  }
399
- objCacheMap.set(cacheKey, proxy);
400
432
  proxySet.add(proxy);
401
433
  proxyToTarget.set(proxy, obj);
402
434
  return proxy;
@@ -438,11 +470,33 @@ function isSecureProxy(obj) {
438
470
  }
439
471
  return proxySet.has(obj);
440
472
  }
441
- 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;
473
+ 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;
442
474
  var init_secure_proxy = __esm({
443
475
  "libs/core/src/secure-proxy.ts"() {
444
476
  "use strict";
445
477
  init_safe_error();
478
+ ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
479
+ ObjectToString = Object.prototype.toString;
480
+ FunctionBind = Function.prototype.bind;
481
+ ReflectGet = Reflect.get;
482
+ ReflectSet = Reflect.set;
483
+ ReflectDefineProperty = Reflect.defineProperty;
484
+ ReflectGetOwnPropertyDescriptor2 = Reflect.getOwnPropertyDescriptor;
485
+ ReflectOwnKeys2 = Reflect.ownKeys;
486
+ ReflectApply2 = Reflect.apply;
487
+ ReflectConstruct = Reflect.construct;
488
+ ReflectObject = Reflect;
489
+ PINNED_REFLECT_VALUES = /* @__PURE__ */ new Map();
490
+ for (const key of ReflectOwnKeys2(ReflectObject)) {
491
+ PINNED_REFLECT_VALUES.set(key, ReflectGet(ReflectObject, key));
492
+ }
493
+ FunctionCtor = Function;
494
+ AsyncFunctionCtor = async function() {
495
+ }.constructor;
496
+ GeneratorFunctionCtor = function* () {
497
+ }.constructor;
498
+ AsyncGeneratorFunctionCtor = async function* () {
499
+ }.constructor;
446
500
  MIN_MEMBRANE_RECURSION_DEPTH = 256;
447
501
  BLOCKED_PROPERTY_CATEGORIES = {
448
502
  /**
@@ -457,6 +511,23 @@ var init_secure_proxy = __esm({
457
511
  "__lookupGetter__",
458
512
  "__lookupSetter__"
459
513
  ]),
514
+ /**
515
+ * Property-descriptor and prototype MUTATION gadgets. These are the primitives behind the
516
+ * GHSA-3279 membrane self-leak (`Object.defineProperty(Object, 'getOwnPropertyDescriptor', hook)`
517
+ * to intercept the trap's raw target) and classic prototype pollution (`setPrototypeOf`). They
518
+ * are never needed by AgentScript and are already refused by the single-VM SafeObject
519
+ * (`DANGEROUS_OBJECT_STATIC_METHODS`), so they are blocked at every level that blocks the
520
+ * constructor (all except PERMISSIVE). Read-only reflection (getPrototypeOf, keys, entries,
521
+ * getOwnPropertyNames) is intentionally NOT here: the membrane's own getPrototypeOf/ownKeys traps
522
+ * already neutralize it for proxied values, and it has legitimate uses.
523
+ */
524
+ DESCRIPTOR_MUTATION: /* @__PURE__ */ new Set([
525
+ "getOwnPropertyDescriptor",
526
+ "getOwnPropertyDescriptors",
527
+ "defineProperty",
528
+ "defineProperties",
529
+ "setPrototypeOf"
530
+ ]),
460
531
  /**
461
532
  * Node.js 24 Iterator helper method names
462
533
  * Blocked at STRICT/SECURE to prevent prototype chain access via iterators
@@ -498,7 +569,13 @@ var init_secure_proxy = __esm({
498
569
  "__defineGetter__",
499
570
  "__defineSetter__",
500
571
  "__lookupGetter__",
501
- "__lookupSetter__"
572
+ "__lookupSetter__",
573
+ // Descriptor / prototype mutation gadgets (GHSA-3279 self-leak + prototype pollution)
574
+ "getOwnPropertyDescriptor",
575
+ "getOwnPropertyDescriptors",
576
+ "defineProperty",
577
+ "defineProperties",
578
+ "setPrototypeOf"
502
579
  ]);
503
580
  DEFAULT_SECURE_PROXY_CONFIG = {
504
581
  blockConstructor: true,
@@ -519,6 +596,7 @@ var init_secure_proxy = __esm({
519
596
  // 'call',
520
597
  // 'apply',
521
598
  ]);
599
+ gatedProxyCaches = /* @__PURE__ */ new WeakMap();
522
600
  proxyCache = /* @__PURE__ */ new WeakMap();
523
601
  proxySet = /* @__PURE__ */ new WeakSet();
524
602
  proxyToTarget = /* @__PURE__ */ new WeakMap();
@@ -674,7 +752,7 @@ var init_reference_config = __esm({
674
752
 
675
753
  // libs/core/src/sidecar/reference-resolver.ts
676
754
  function untrustedLength(value) {
677
- const rawLen = ReflectGet(value, "length");
755
+ const rawLen = ReflectGet2(value, "length");
678
756
  if (typeof rawLen !== "number" || !NumberIsFinite(rawLen) || rawLen < 0) {
679
757
  return 0;
680
758
  }
@@ -691,7 +769,7 @@ function untrustedLength(value) {
691
769
  }
692
770
  function untrustedAt(value, index) {
693
771
  try {
694
- return ReflectGet(value, index);
772
+ return ReflectGet2(value, index);
695
773
  } catch {
696
774
  return void 0;
697
775
  }
@@ -700,12 +778,12 @@ function isCompositeHandle(value) {
700
778
  const obj = value;
701
779
  return typeof value === "object" && value !== null && obj["__type"] === "composite" && Array.isArray(obj["__parts"]);
702
780
  }
703
- var ReflectGet, NumberIsFinite, MathFloor, MAX_TRAVERSAL_LENGTH, ResolutionLimitError, ReferenceResolver;
781
+ var ReflectGet2, NumberIsFinite, MathFloor, MAX_TRAVERSAL_LENGTH, ResolutionLimitError, ReferenceResolver;
704
782
  var init_reference_resolver = __esm({
705
783
  "libs/core/src/sidecar/reference-resolver.ts"() {
706
784
  "use strict";
707
785
  init_reference_config();
708
- ReflectGet = Reflect.get;
786
+ ReflectGet2 = Reflect.get;
709
787
  NumberIsFinite = Number.isFinite;
710
788
  MathFloor = Math.floor;
711
789
  MAX_TRAVERSAL_LENGTH = 1e6;
@@ -977,7 +1055,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
977
1055
  context.visited.add(value);
978
1056
  }
979
1057
  if (ArrayIsArray(value)) {
980
- const rawLen = ReflectGet2(value, "length");
1058
+ const rawLen = ReflectGet3(value, "length");
981
1059
  const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
982
1060
  context.propCount.count += len;
983
1061
  if (context.propCount.count > maxProperties) {
@@ -987,7 +1065,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
987
1065
  for (let i = 0; i < len; i++) {
988
1066
  let item;
989
1067
  try {
990
- item = ReflectGet2(value, i);
1068
+ item = ReflectGet3(value, i);
991
1069
  } catch {
992
1070
  item = void 0;
993
1071
  }
@@ -996,15 +1074,15 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
996
1074
  return result;
997
1075
  }
998
1076
  if (value instanceof Date) {
999
- const time = ReflectApply(DateProtoGetTime, value, []);
1077
+ const time = ReflectApply3(DateProtoGetTime, value, []);
1000
1078
  if (allowDates) {
1001
1079
  return new Date(time);
1002
1080
  }
1003
- return ReflectApply(DateProtoToISOString, value, []);
1081
+ return ReflectApply3(DateProtoToISOString, value, []);
1004
1082
  }
1005
1083
  if (value instanceof Error) {
1006
- const rawName = ReflectGet2(value, "name");
1007
- const rawMessage = ReflectGet2(value, "message");
1084
+ const rawName = ReflectGet3(value, "name");
1085
+ const rawMessage = ReflectGet3(value, "message");
1008
1086
  const name = typeof rawName === "string" ? rawName : "Error";
1009
1087
  const message = typeof rawMessage === "string" ? rawMessage : "";
1010
1088
  if (allowErrors) {
@@ -1017,11 +1095,11 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1017
1095
  return { error: message };
1018
1096
  }
1019
1097
  if (value instanceof RegExp) {
1020
- return ReflectApply(RegExpProtoToString, value, []);
1098
+ return ReflectApply3(RegExpProtoToString, value, []);
1021
1099
  }
1022
1100
  if (value instanceof Map) {
1023
1101
  const sanitizedMap = ObjectCreate(null);
1024
- const entries = ReflectApply(MapProtoEntries, value, []);
1102
+ const entries = ReflectApply3(MapProtoEntries, value, []);
1025
1103
  for (const [key, val] of entries) {
1026
1104
  if (typeof key !== "string") continue;
1027
1105
  if (DANGEROUS_KEYS.has(key)) continue;
@@ -1031,7 +1109,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1031
1109
  return sanitizedMap;
1032
1110
  }
1033
1111
  if (value instanceof Set) {
1034
- const iter = ReflectApply(SetProtoValues, value, []);
1112
+ const iter = ReflectApply3(SetProtoValues, value, []);
1035
1113
  const result = [];
1036
1114
  for (const item of iter) {
1037
1115
  context.propCount.count++;
@@ -1052,7 +1130,7 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1052
1130
  }
1053
1131
  let propValue;
1054
1132
  try {
1055
- propValue = ReflectGet2(value, key);
1133
+ propValue = ReflectGet3(value, key);
1056
1134
  } catch {
1057
1135
  continue;
1058
1136
  }
@@ -1190,13 +1268,13 @@ function checkSerializedSize(value, maxBytes) {
1190
1268
  return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
1191
1269
  }
1192
1270
  }
1193
- var DANGEROUS_KEYS, ReflectApply, ReflectGet2, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
1271
+ var DANGEROUS_KEYS, ReflectApply3, ReflectGet3, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
1194
1272
  var init_value_sanitizer = __esm({
1195
1273
  "libs/core/src/value-sanitizer.ts"() {
1196
1274
  "use strict";
1197
1275
  DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
1198
- ReflectApply = Reflect.apply;
1199
- ReflectGet2 = Reflect.get;
1276
+ ReflectApply3 = Reflect.apply;
1277
+ ReflectGet3 = Reflect.get;
1200
1278
  ArrayIsArray = Array.isArray;
1201
1279
  ObjectKeys = Object.keys;
1202
1280
  ObjectCreate = Object.create;
@@ -1210,6 +1288,390 @@ var init_value_sanitizer = __esm({
1210
1288
  }
1211
1289
  });
1212
1290
 
1291
+ // libs/core/src/global-function-gate.ts
1292
+ function isBuiltinMethod(fn) {
1293
+ return (typeof fn === "function" || typeof fn === "object" && fn !== null) && BUILTIN_METHODS.has(fn);
1294
+ }
1295
+ function resolveMaxGlobalFunctionCalls(config) {
1296
+ const explicit = config.maxGlobalFunctionCalls;
1297
+ if (typeof explicit === "number" && Number.isFinite(explicit) && explicit >= 0) {
1298
+ return Math.floor(explicit);
1299
+ }
1300
+ const maxToolCalls = typeof config.maxToolCalls === "number" && Number.isFinite(config.maxToolCalls) ? config.maxToolCalls : 100;
1301
+ return Math.max(0, Math.floor(maxToolCalls)) * DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL;
1302
+ }
1303
+ function globalFunctionLimitMessage(max) {
1304
+ return `Maximum global function call limit exceeded (${max}). This limit prevents runaway calls into host functions.`;
1305
+ }
1306
+ function resultLimits(context) {
1307
+ const { config } = context;
1308
+ return {
1309
+ maxDepth: config.maxSanitizeDepth,
1310
+ maxProperties: config.maxSanitizeProperties,
1311
+ maxPayloadBytes: config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES
1312
+ };
1313
+ }
1314
+ function truncate(value, max) {
1315
+ return value.length <= max ? value : `${value.slice(0, max)}\u2026`;
1316
+ }
1317
+ function failure(error) {
1318
+ let name = "Error";
1319
+ let message = "Global function call failed";
1320
+ try {
1321
+ if (error && typeof error === "object") {
1322
+ const rawName = error.name;
1323
+ const rawMessage = error.message;
1324
+ if (typeof rawName === "string" && rawName) name = rawName;
1325
+ if (typeof rawMessage === "string" && rawMessage) message = rawMessage;
1326
+ } else if (typeof error === "string" && error) {
1327
+ message = error;
1328
+ }
1329
+ } catch {
1330
+ }
1331
+ return {
1332
+ ok: false,
1333
+ name: truncate(name, MAX_ERROR_NAME_LENGTH),
1334
+ message: truncate(message, MAX_ERROR_MESSAGE_LENGTH)
1335
+ };
1336
+ }
1337
+ function jsonReplacer(_key, value) {
1338
+ if (typeof value === "bigint") return value.toString();
1339
+ if (typeof value === "number" && !Number.isFinite(value)) return null;
1340
+ return value;
1341
+ }
1342
+ function utf8ByteLength(value) {
1343
+ return Buffer.byteLength(value, "utf8");
1344
+ }
1345
+ function encodeResult(value, limits) {
1346
+ if (value === void 0) return { ok: true };
1347
+ let json;
1348
+ try {
1349
+ const sanitized = sanitizeValue(value, {
1350
+ maxDepth: limits.maxDepth,
1351
+ maxProperties: limits.maxProperties,
1352
+ allowDates: false,
1353
+ allowErrors: true
1354
+ });
1355
+ json = JsonStringify(sanitized, jsonReplacer);
1356
+ } catch {
1357
+ return { ok: false, name: "GlobalFunctionError", message: UNSAFE_RESULT_MESSAGE };
1358
+ }
1359
+ if (json === void 0) return { ok: true };
1360
+ if (utf8ByteLength(json) > limits.maxPayloadBytes) {
1361
+ return {
1362
+ ok: false,
1363
+ name: "GlobalFunctionError",
1364
+ message: `Global function result exceeds maximum size (${limits.maxPayloadBytes} bytes)`
1365
+ };
1366
+ }
1367
+ return { ok: true, json };
1368
+ }
1369
+ function isThenable(value) {
1370
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
1371
+ try {
1372
+ return typeof value.then === "function";
1373
+ } catch {
1374
+ return false;
1375
+ }
1376
+ }
1377
+ function invokeGlobalFunction(fn, thisArg, args, limits) {
1378
+ if (typeof fn !== "function") {
1379
+ return { ok: false, name: "TypeError", message: "Global is not a function" };
1380
+ }
1381
+ let result;
1382
+ try {
1383
+ result = ReflectApply4(fn, thisArg, ArrayIsArray2(args) ? args : []);
1384
+ } catch (error) {
1385
+ return failure(error);
1386
+ }
1387
+ if (isThenable(result)) {
1388
+ return Promise.resolve(result).then(
1389
+ (value) => encodeResult(value, limits),
1390
+ (error) => failure(error)
1391
+ );
1392
+ }
1393
+ return encodeResult(result, limits);
1394
+ }
1395
+ function toEnvelope(outcome) {
1396
+ if (outcome.ok) {
1397
+ return outcome.json === void 0 ? '{"v":1,"ok":true}' : `{"v":1,"ok":true,"value":${outcome.json}}`;
1398
+ }
1399
+ return JsonStringify({ v: 1, ok: false, error: { name: outcome.name, message: outcome.message } });
1400
+ }
1401
+ function createHostGlobalFunctionInvoker(context) {
1402
+ const limits = resultLimits(context);
1403
+ return (fn, thisArg, args) => {
1404
+ const outcome = invokeGlobalFunction(fn, thisArg, args, limits);
1405
+ return outcome instanceof Promise ? outcome.then(toEnvelope) : toEnvelope(outcome);
1406
+ };
1407
+ }
1408
+ function createGlobalFunctionGate(context, realm) {
1409
+ const limits = resultLimits(context);
1410
+ const max = resolveMaxGlobalFunctionCalls(context.config);
1411
+ let calls = 0;
1412
+ const settle = (outcome) => {
1413
+ if (!outcome.ok) {
1414
+ throw createSafeError(outcome.message, outcome.name);
1415
+ }
1416
+ return outcome.json === void 0 ? void 0 : realm.parseJson(outcome.json);
1417
+ };
1418
+ return {
1419
+ gates: (target) => !isBuiltinMethod(target),
1420
+ call: (target, thisArg, args) => {
1421
+ if (context.aborted) {
1422
+ throw createSafeError("Execution aborted");
1423
+ }
1424
+ calls++;
1425
+ if (calls > max) {
1426
+ throw createSafeError(globalFunctionLimitMessage(max));
1427
+ }
1428
+ const outcome = invokeGlobalFunction(target, thisArg, args, limits);
1429
+ if (outcome instanceof Promise) {
1430
+ return realm.adoptPromise(outcome.then(settle));
1431
+ }
1432
+ return settle(outcome);
1433
+ }
1434
+ };
1435
+ }
1436
+ 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;
1437
+ var init_global_function_gate = __esm({
1438
+ "libs/core/src/global-function-gate.ts"() {
1439
+ "use strict";
1440
+ init_value_sanitizer();
1441
+ init_safe_error();
1442
+ ReflectApply4 = Reflect.apply;
1443
+ ReflectOwnKeys3 = Reflect.ownKeys;
1444
+ ObjectGetOwnPropertyDescriptor2 = Object.getOwnPropertyDescriptor;
1445
+ ObjectGetPrototypeOf2 = Object.getPrototypeOf;
1446
+ ArrayIsArray2 = Array.isArray;
1447
+ JsonStringify = JSON.stringify;
1448
+ BUILTIN_METHODS = (() => {
1449
+ const methods = /* @__PURE__ */ new WeakSet();
1450
+ const typedArrays = [
1451
+ Int8Array,
1452
+ Uint8Array,
1453
+ Uint8ClampedArray,
1454
+ Int16Array,
1455
+ Uint16Array,
1456
+ Int32Array,
1457
+ Uint32Array,
1458
+ Float32Array,
1459
+ Float64Array,
1460
+ BigInt64Array,
1461
+ BigUint64Array
1462
+ ];
1463
+ const arrayIteratorPrototype = ObjectGetPrototypeOf2([][Symbol.iterator]());
1464
+ const prototypes = [
1465
+ Object.prototype,
1466
+ Array.prototype,
1467
+ String.prototype,
1468
+ Number.prototype,
1469
+ Boolean.prototype,
1470
+ Symbol.prototype,
1471
+ BigInt.prototype,
1472
+ Date.prototype,
1473
+ RegExp.prototype,
1474
+ Error.prototype,
1475
+ EvalError.prototype,
1476
+ RangeError.prototype,
1477
+ ReferenceError.prototype,
1478
+ SyntaxError.prototype,
1479
+ TypeError.prototype,
1480
+ URIError.prototype,
1481
+ Map.prototype,
1482
+ Set.prototype,
1483
+ WeakMap.prototype,
1484
+ WeakSet.prototype,
1485
+ Promise.prototype,
1486
+ ArrayBuffer.prototype,
1487
+ DataView.prototype,
1488
+ ObjectGetPrototypeOf2(Uint8Array.prototype),
1489
+ // %TypedArray%.prototype
1490
+ ...typedArrays.map((TypedArray) => TypedArray.prototype),
1491
+ arrayIteratorPrototype,
1492
+ ObjectGetPrototypeOf2(arrayIteratorPrototype),
1493
+ // %IteratorPrototype%
1494
+ ObjectGetPrototypeOf2((/* @__PURE__ */ new Map())[Symbol.iterator]()),
1495
+ ObjectGetPrototypeOf2((/* @__PURE__ */ new Set())[Symbol.iterator]()),
1496
+ ObjectGetPrototypeOf2(""[Symbol.iterator]())
1497
+ ];
1498
+ for (const prototype of prototypes) {
1499
+ if (prototype === null || typeof prototype !== "object") continue;
1500
+ for (const key of ReflectOwnKeys3(prototype)) {
1501
+ if (key === "constructor") continue;
1502
+ const descriptor = ObjectGetOwnPropertyDescriptor2(prototype, key);
1503
+ if (descriptor && typeof descriptor.value === "function") {
1504
+ methods.add(descriptor.value);
1505
+ }
1506
+ }
1507
+ }
1508
+ return methods;
1509
+ })();
1510
+ DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL = 10;
1511
+ DEFAULT_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
1512
+ MAX_ERROR_MESSAGE_LENGTH = 4096;
1513
+ MAX_ERROR_NAME_LENGTH = 128;
1514
+ 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)";
1515
+ }
1516
+ });
1517
+
1518
+ // libs/core/src/stack-trace.ts
1519
+ function redactLine(line) {
1520
+ let out = line.length > MAX_LINE_LENGTH ? `${line.slice(0, MAX_LINE_LENGTH)}\u2026` : line;
1521
+ for (const pattern of SENSITIVE_STACK_PATTERNS) {
1522
+ pattern.lastIndex = 0;
1523
+ out = out.replace(pattern, "[REDACTED]");
1524
+ }
1525
+ return out;
1526
+ }
1527
+ function sanitizeStackTrace(stack, sanitize = true) {
1528
+ if (typeof stack !== "string" || !stack || !sanitize) return stack;
1529
+ const bounded = stack.length > MAX_STACK_LENGTH ? stack.slice(0, MAX_STACK_LENGTH) : stack;
1530
+ return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
1531
+ }
1532
+ var SENSITIVE_STACK_PATTERNS, FRAME_LINE, MAX_STACK_LENGTH, MAX_LINE_LENGTH, REDACTED_FRAME;
1533
+ var init_stack_trace = __esm({
1534
+ "libs/core/src/stack-trace.ts"() {
1535
+ "use strict";
1536
+ SENSITIVE_STACK_PATTERNS = [
1537
+ // Unix file system paths
1538
+ /\/Users\/[^/]+\/[^\s):]*/gi,
1539
+ // macOS home directories
1540
+ /\/home\/[^/]+\/[^\s):]*/gi,
1541
+ // Linux home directories
1542
+ /\/var\/[^\s):]*/gi,
1543
+ // System var directories
1544
+ /\/opt\/[^\s):]*/gi,
1545
+ // Optional software
1546
+ /\/tmp\/[^\s):]*/gi,
1547
+ // Temporary files
1548
+ /\/etc\/[^\s):]*/gi,
1549
+ // System configuration
1550
+ /\/root\/[^\s):]*/gi,
1551
+ // Root home directory
1552
+ /\/mnt\/[^\s):]*/gi,
1553
+ // Mount points
1554
+ /\/srv\/[^\s):]*/gi,
1555
+ // Service data
1556
+ /\/data\/[^\s):]*/gi,
1557
+ // Data directories
1558
+ /\/app\/[^\s):]*/gi,
1559
+ // Application directories
1560
+ /\/proc\/[^\s):]*/gi,
1561
+ // Process information
1562
+ /\/sys\/[^\s):]*/gi,
1563
+ // System files
1564
+ // Windows paths
1565
+ /\\\\[^\s):]*/g,
1566
+ // UNC paths
1567
+ /[A-Z]:\\[^\s):]+/gi,
1568
+ // Windows drive paths
1569
+ // URL-based paths
1570
+ /file:\/\/[^\s):]+/gi,
1571
+ // File URLs
1572
+ /webpack:\/\/[^\s):]+/gi,
1573
+ // Webpack paths
1574
+ /%2F[^\s):]+/gi,
1575
+ // URL-encoded paths
1576
+ // Package managers and node
1577
+ /node_modules\/[^\s):]+/gi,
1578
+ // Node modules paths
1579
+ /\/nix\/store\/[^\s):]*/gi,
1580
+ // Nix store paths
1581
+ /\.npm\/[^\s):]*/gi,
1582
+ // NPM cache
1583
+ /\.yarn\/[^\s):]*/gi,
1584
+ // Yarn cache
1585
+ /\.pnpm\/[^\s):]*/gi,
1586
+ // PNPM cache
1587
+ // Container and orchestration
1588
+ /\/run\/secrets\/[^\s):]*/gi,
1589
+ // Docker/K8s secrets
1590
+ /\/var\/run\/[^\s):]*/gi,
1591
+ // Runtime directories
1592
+ /\/docker\/[^\s):]*/gi,
1593
+ // Docker paths
1594
+ /\/containers\/[^\s):]*/gi,
1595
+ // Container paths
1596
+ /\/kubelet\/[^\s):]*/gi,
1597
+ // Kubernetes kubelet
1598
+ // CI/CD systems
1599
+ /\/github\/workspace\/[^\s):]*/gi,
1600
+ // GitHub Actions
1601
+ /\/runner\/[^\s):]*/gi,
1602
+ // GitHub/GitLab runner
1603
+ /\/builds\/[^\s):]*/gi,
1604
+ // CI builds
1605
+ /\/workspace\/[^\s):]*/gi,
1606
+ // Generic workspace
1607
+ /\/pipeline\/[^\s):]*/gi,
1608
+ // CI pipelines
1609
+ /\/jenkins\/[^\s):]*/gi,
1610
+ // Jenkins
1611
+ /\/bamboo\/[^\s):]*/gi,
1612
+ // Bamboo
1613
+ /\/teamcity\/[^\s):]*/gi,
1614
+ // TeamCity
1615
+ /\/circleci\/[^\s):]*/gi,
1616
+ // CircleCI
1617
+ // Cloud providers
1618
+ /\/aws\/[^\s):]*/gi,
1619
+ // AWS paths
1620
+ /\/gcloud\/[^\s):]*/gi,
1621
+ // Google Cloud
1622
+ /\/azure\/[^\s):]*/gi,
1623
+ // Azure paths
1624
+ /s3:\/\/[^\s):]+/gi,
1625
+ // S3 URIs
1626
+ /gs:\/\/[^\s):]+/gi,
1627
+ // GCS URIs
1628
+ // Secrets and credentials (patterns that might appear in paths or errors)
1629
+ /[A-Z0-9]{20,}/g,
1630
+ // AWS-style access keys (20+ uppercase chars)
1631
+ /sk-[a-zA-Z0-9]{32,}/g,
1632
+ // OpenAI/Stripe-style secret keys
1633
+ /ghp_[a-zA-Z0-9]{36,}/g,
1634
+ // GitHub personal access tokens
1635
+ /gho_[a-zA-Z0-9]{36,}/g,
1636
+ // GitHub OAuth tokens
1637
+ /github_pat_[a-zA-Z0-9_]{22,}/g,
1638
+ // GitHub fine-grained tokens
1639
+ /xox[baprs]-[a-zA-Z0-9-]+/g,
1640
+ // Slack tokens
1641
+ /Bearer\s+[a-zA-Z0-9._-]+/gi,
1642
+ // Bearer tokens
1643
+ /Basic\s+[a-zA-Z0-9+/=]+/gi,
1644
+ // Basic auth
1645
+ // Internal network info
1646
+ /(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
1647
+ // Private IPs
1648
+ /[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
1649
+ // Internal hostnames
1650
+ /localhost:\d+/gi,
1651
+ // Localhost with port
1652
+ /127\.0\.0\.1:\d+/gi,
1653
+ // Loopback with port
1654
+ // User information
1655
+ /\/u\/[^/]+\//gi,
1656
+ // User subdirectories
1657
+ /~[a-z_][a-z0-9_-]*/gi,
1658
+ // Unix user home shorthand
1659
+ // Anything else that is still shaped like a location: an absolute path of two or more
1660
+ // segments, a URL, or a script location such as `agentscript.js:3` / `index.mjs:10:5`.
1661
+ /[a-z][a-z0-9+.-]*:\/\/[^\s)]+/gi,
1662
+ // Other URLs (http://host/bundle.js:1:2)
1663
+ /(?:\/[\w.@%+-]+){2,}\/?/g,
1664
+ // Remaining absolute paths
1665
+ /[\w.@-]+\.(?:[cm]?[jt]sx?|json|node|wasm)(?::\d+){1,2}/gi
1666
+ // file.ext:line[:column]
1667
+ ];
1668
+ FRAME_LINE = /^\s*at\s/;
1669
+ MAX_STACK_LENGTH = 16 * 1024;
1670
+ MAX_LINE_LENGTH = 1e3;
1671
+ REDACTED_FRAME = " at [REDACTED]";
1672
+ }
1673
+ });
1674
+
1213
1675
  // libs/core/src/memory-tracker.ts
1214
1676
  function estimateStringSize2(str) {
1215
1677
  return str.length * 2 + 40;
@@ -1365,16 +1827,16 @@ var init_memory_tracker = __esm({
1365
1827
  });
1366
1828
 
1367
1829
  // libs/core/src/tool-bridge.ts
1368
- function utf8ByteLength(value) {
1830
+ function utf8ByteLength2(value) {
1369
1831
  return Buffer.byteLength(value, "utf8");
1370
1832
  }
1371
- function jsonReplacer(_key, value) {
1833
+ function jsonReplacer2(_key, value) {
1372
1834
  if (typeof value === "bigint") return value.toString();
1373
1835
  if (typeof value === "number" && !Number.isFinite(value)) return null;
1374
1836
  return value;
1375
1837
  }
1376
1838
  function safeJsonStringify(value) {
1377
- return JSON.stringify(value, jsonReplacer);
1839
+ return JSON.stringify(value, jsonReplacer2);
1378
1840
  }
1379
1841
  function truncateForErrorMessage(value, maxChars) {
1380
1842
  if (value.length <= maxChars) return value;
@@ -1415,7 +1877,7 @@ function serializeResponse(response, maxPayloadBytes) {
1415
1877
  }
1416
1878
  });
1417
1879
  }
1418
- if (utf8ByteLength(json) <= maxPayloadBytes) return json;
1880
+ if (utf8ByteLength2(json) <= maxPayloadBytes) return json;
1419
1881
  const minimal = {
1420
1882
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
1421
1883
  ok: false,
@@ -1471,7 +1933,7 @@ function createHostToolBridge(executionContext, options) {
1471
1933
  maxPayloadBytes
1472
1934
  );
1473
1935
  }
1474
- if (utf8ByteLength(requestJson) > maxPayloadBytes) {
1936
+ if (utf8ByteLength2(requestJson) > maxPayloadBytes) {
1475
1937
  return serializeResponse(
1476
1938
  {
1477
1939
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -1612,7 +2074,7 @@ function createHostToolBridge(executionContext, options) {
1612
2074
  {
1613
2075
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
1614
2076
  ok: false,
1615
- error: safeError
2077
+ error: { ...safeError, toolError: true }
1616
2078
  },
1617
2079
  maxPayloadBytes
1618
2080
  );
@@ -1636,13 +2098,13 @@ function createHostToolBridge(executionContext, options) {
1636
2098
  {
1637
2099
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
1638
2100
  ok: false,
1639
- error: safeError
2101
+ error: { ...safeError, toolError: true }
1640
2102
  },
1641
2103
  maxPayloadBytes
1642
2104
  );
1643
2105
  }
1644
2106
  if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
1645
- const size = utf8ByteLength(sanitizedResult);
2107
+ const size = utf8ByteLength2(sanitizedResult);
1646
2108
  if (size >= referenceConfig.extractionThreshold) {
1647
2109
  try {
1648
2110
  const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
@@ -1666,12 +2128,12 @@ function createHostToolBridge(executionContext, options) {
1666
2128
  {
1667
2129
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
1668
2130
  ok: false,
1669
- error: safeError
2131
+ error: { ...safeError, toolError: true }
1670
2132
  },
1671
2133
  maxPayloadBytes
1672
2134
  );
1673
2135
  }
1674
- if (utf8ByteLength(okJson) > maxPayloadBytes) {
2136
+ if (utf8ByteLength2(okJson) > maxPayloadBytes) {
1675
2137
  return serializeResponse(
1676
2138
  {
1677
2139
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -1679,7 +2141,8 @@ function createHostToolBridge(executionContext, options) {
1679
2141
  error: {
1680
2142
  name: "ToolBridgeError",
1681
2143
  message: `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
1682
- code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
2144
+ code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE",
2145
+ toolError: true
1683
2146
  }
1684
2147
  },
1685
2148
  maxPayloadBytes
@@ -1709,6 +2172,64 @@ var init_tool_bridge = __esm({
1709
2172
  }
1710
2173
  });
1711
2174
 
2175
+ // libs/core/src/tool-namespaces.ts
2176
+ function buildToolNamespaceBindings(install, callTool, namespaces) {
2177
+ if (namespaces.length === 0) return [];
2178
+ if (typeof install !== "function") {
2179
+ throw new Error("Tool namespace factory is not available in the sandbox");
2180
+ }
2181
+ const built = install(
2182
+ callTool,
2183
+ JSON.stringify(namespaces)
2184
+ );
2185
+ return namespaces.map((ns) => ({ name: ns.name, value: built[ns.name] }));
2186
+ }
2187
+ var TOOL_NAMESPACE_FACTORY_SOURCE;
2188
+ var init_tool_namespaces = __esm({
2189
+ "libs/core/src/tool-namespaces.ts"() {
2190
+ "use strict";
2191
+ TOOL_NAMESPACE_FACTORY_SOURCE = `
2192
+ (function () {
2193
+ 'use strict';
2194
+ var parse = JSON.parse;
2195
+ var freeze = Object.freeze;
2196
+ var isArray = Array.isArray;
2197
+
2198
+ function isSafeKey(key) {
2199
+ return typeof key === 'string' && key.length > 0 &&
2200
+ !(key.charAt(0) === '_' && key.charAt(1) === '_') &&
2201
+ key !== 'constructor' && key !== 'prototype';
2202
+ }
2203
+
2204
+ function bind(callTool, toolName) {
2205
+ return (args, options) => callTool(toolName, args === undefined ? {} : args, options);
2206
+ }
2207
+
2208
+ return function install(callTool, namespacesJson) {
2209
+ var spec = parse(namespacesJson);
2210
+ var namespaces = { __proto__: null };
2211
+ if (isArray(spec)) {
2212
+ for (var i = 0; i < spec.length; i++) {
2213
+ var ns = spec[i];
2214
+ if (!ns || !isSafeKey(ns.name) || !isArray(ns.methods)) continue;
2215
+ var target = { __proto__: null };
2216
+ for (var j = 0; j < ns.methods.length; j++) {
2217
+ var method = ns.methods[j];
2218
+ if (!method || !isSafeKey(method.name) || typeof method.toolName !== 'string') continue;
2219
+ target[method.name] = bind(callTool, method.toolName);
2220
+ }
2221
+ freeze(target);
2222
+ namespaces[ns.name] = target;
2223
+ }
2224
+ }
2225
+ freeze(namespaces);
2226
+ return namespaces;
2227
+ };
2228
+ })()
2229
+ `.trim();
2230
+ }
2231
+ });
2232
+
1712
2233
  // libs/core/src/double-vm/parent-vm-bootstrap.ts
1713
2234
  function generateSanitizeContextCode(securityLevel) {
1714
2235
  const globalsToRemove = NODEJS_24_DANGEROUS_GLOBALS[securityLevel];
@@ -1750,7 +2271,9 @@ function generateParentVmBootstrap(options) {
1750
2271
  blockedProperties,
1751
2272
  allowComposites = false,
1752
2273
  memoryLimit = 0,
1753
- throwOnBlocked = true
2274
+ throwOnBlocked = true,
2275
+ maxGlobalFunctionCalls = 1e3,
2276
+ toolNamespaces = []
1754
2277
  } = options;
1755
2278
  const sanitizeContextCode = generateSanitizeContextCode(securityLevel);
1756
2279
  const patternDetectorsCode = generatePatternDetectorsCode(suspiciousPatterns);
@@ -2186,6 +2709,8 @@ ${stackTraceHardeningCode}
2186
2709
  const hostReportViolation = __host_reportViolation__;
2187
2710
  const hostConfig = __host_config__;
2188
2711
  const hostMemoryTrack = typeof __host_memory_track__ === 'function' ? __host_memory_track__ : function(){};
2712
+ const hostInvokeGlobal = typeof __host_invokeGlobal__ === 'function' ? __host_invokeGlobal__ : null;
2713
+ const hostIsBuiltinMethod = typeof __host_isBuiltinMethod__ === 'function' ? __host_isBuiltinMethod__ : function() { return false; };
2189
2714
  const toolBridgeMode = ${JSON.stringify(toolBridgeMode)};
2190
2715
  const toolBridgeMaxPayloadBytes = ${toolBridgeMaxPayloadBytes};
2191
2716
 
@@ -2198,6 +2723,8 @@ ${stackTraceHardeningCode}
2198
2723
  try { delete globalThis.__host_reportViolation__; } catch (e) { /* ignore */ }
2199
2724
  try { delete globalThis.__host_config__; } catch (e) { /* ignore */ }
2200
2725
  try { delete globalThis.__host_memory_track__; } catch (e) { /* ignore */ }
2726
+ try { delete globalThis.__host_invokeGlobal__; } catch (e) { /* ignore */ }
2727
+ try { delete globalThis.__host_isBuiltinMethod__; } catch (e) { /* ignore */ }
2201
2728
 
2202
2729
  // Policy violation reporter (best-effort; host decides how to handle based on security level)
2203
2730
  function __ag_reportViolation(kind) {
@@ -2216,6 +2743,29 @@ ${stackTraceHardeningCode}
2216
2743
  } catch (e) { /* ignore */ }
2217
2744
  }
2218
2745
 
2746
+ // SECURITY (GHSA-3279): pin pristine intrinsics BEFORE any sandbox code runs, so the membrane
2747
+ // traps and the error hardening below never re-read a realm global the sandbox can overwrite.
2748
+ // The reported escape replaced Object.getOwnPropertyDescriptor with a hook; the get trap then
2749
+ // called it and handed the attacker the RAW target of a membrane proxy (the host Promise from
2750
+ // callTool), reaching the host Function constructor. The same gadget aimed at the Object.*
2751
+ // mutators below would let an attacker observe safe-error construction or defeat the final
2752
+ // freeze, leaving the returned error with a live prototype and constructor chain. Using
2753
+ // captured references makes a later monkeypatch a no-op.
2754
+ const __ag_getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
2755
+ const __ag_defineProperty = Object.defineProperty;
2756
+ const __ag_defineProperties = Object.defineProperties;
2757
+ const __ag_setPrototypeOf = Object.setPrototypeOf;
2758
+ const __ag_objectCreate = Object.create;
2759
+ const __ag_objectFreeze = Object.freeze;
2760
+ const __ag_ReflectGet = Reflect.get;
2761
+ const __ag_ReflectSet = Reflect.set;
2762
+ const __ag_ReflectDefineProperty = Reflect.defineProperty;
2763
+ const __ag_ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
2764
+ const __ag_ReflectOwnKeys = Reflect.ownKeys;
2765
+ const __ag_ReflectApply = Reflect.apply;
2766
+ const __ag_hasOwnProperty = Object.prototype.hasOwnProperty;
2767
+ const __ag_functionBind = Function.prototype.bind;
2768
+
2219
2769
  /**
2220
2770
  * Creates a "safe" error object that cannot be used to escape the sandbox.
2221
2771
  *
@@ -2238,7 +2788,7 @@ ${stackTraceHardeningCode}
2238
2788
  var error = new Error(message);
2239
2789
  // NOTE: Use Object.defineProperty instead of direct assignment because
2240
2790
  // Error.prototype.name is frozen, and in strict mode direct assignment fails.
2241
- Object.defineProperty(error, 'name', {
2791
+ __ag_defineProperty(error, 'name', {
2242
2792
  value: name,
2243
2793
  writable: true,
2244
2794
  enumerable: false,
@@ -2247,12 +2797,12 @@ ${stackTraceHardeningCode}
2247
2797
 
2248
2798
  // CRITICAL: sever the *actual* prototype chain (native getters / Object.getPrototypeOf).
2249
2799
  // A shadowing __proto__ data property is not sufficient.
2250
- Object.setPrototypeOf(error, null);
2800
+ __ag_setPrototypeOf(error, null);
2251
2801
 
2252
2802
  // Create a null-prototype object to use as a safe "constructor"
2253
2803
  // This object has no prototype chain to climb
2254
- var SafeConstructor = Object.create(null);
2255
- Object.defineProperties(SafeConstructor, {
2804
+ var SafeConstructor = __ag_objectCreate(null);
2805
+ __ag_defineProperties(SafeConstructor, {
2256
2806
  // Make constructor point to itself to break the chain
2257
2807
  constructor: {
2258
2808
  value: SafeConstructor,
@@ -2275,11 +2825,11 @@ ${stackTraceHardeningCode}
2275
2825
  configurable: false
2276
2826
  }
2277
2827
  });
2278
- Object.freeze(SafeConstructor);
2828
+ __ag_objectFreeze(SafeConstructor);
2279
2829
 
2280
2830
  // Override the constructor property on the error instance
2281
2831
  // This breaks the prototype chain: err.constructor.constructor no longer reaches Function
2282
- Object.defineProperty(error, 'constructor', {
2832
+ __ag_defineProperty(error, 'constructor', {
2283
2833
  value: SafeConstructor,
2284
2834
  writable: false,
2285
2835
  enumerable: false,
@@ -2288,7 +2838,7 @@ ${stackTraceHardeningCode}
2288
2838
 
2289
2839
  // SECURITY: Override __proto__ on the error instance to prevent prototype chain escape
2290
2840
  // Attack vector blocked: err.__proto__.constructor.constructor('malicious code')()
2291
- Object.defineProperty(error, '__proto__', {
2841
+ __ag_defineProperty(error, '__proto__', {
2292
2842
  value: null,
2293
2843
  writable: false,
2294
2844
  enumerable: false,
@@ -2298,7 +2848,7 @@ ${stackTraceHardeningCode}
2298
2848
  // SECURITY: Remove the stack property to prevent information leakage (Vector 1230)
2299
2849
  // The stack trace can reveal internal implementation details like function names,
2300
2850
  // file paths, and line numbers which can be used for reconnaissance attacks.
2301
- Object.defineProperty(error, 'stack', {
2851
+ __ag_defineProperty(error, 'stack', {
2302
2852
  value: undefined,
2303
2853
  writable: false,
2304
2854
  enumerable: false,
@@ -2307,7 +2857,7 @@ ${stackTraceHardeningCode}
2307
2857
 
2308
2858
  // Add a unique marker to identify this as a safe error from our runtime
2309
2859
  // This is used by suspicious pattern detection to distinguish our errors from user errors
2310
- Object.defineProperty(error, SAFE_ERROR_MARKER, {
2860
+ __ag_defineProperty(error, SAFE_ERROR_MARKER, {
2311
2861
  value: true,
2312
2862
  writable: false,
2313
2863
  enumerable: false,
@@ -2315,7 +2865,7 @@ ${stackTraceHardeningCode}
2315
2865
  });
2316
2866
 
2317
2867
  // Freeze the error to prevent modifications
2318
- Object.freeze(error);
2868
+ __ag_objectFreeze(error);
2319
2869
 
2320
2870
  return error;
2321
2871
  }
@@ -2344,6 +2894,22 @@ ${stackTraceHardeningCode}
2344
2894
  // Tool call stats for rate limiting
2345
2895
  let toolCallCount = 0;
2346
2896
 
2897
+ // Calls into host functions passed in globals: counted against their own cap, and their
2898
+ // timestamps share the operation rate limit with tool calls. They are not recorded in
2899
+ // operationHistory, so the tool-call suspicious-sequence detectors only see tool calls.
2900
+ let globalFunctionCallCount = 0;
2901
+ const globalFunctionCallTimes = [];
2902
+
2903
+ // Fail-closed: every call into a host function goes through the gate, except the built-in
2904
+ // prototype methods of host data (Array.prototype.map, iterators, Date methods, ...), which
2905
+ // the get trap binds and records here so data globals keep working as before.
2906
+ const ungatedHostFunctions = new WeakSet();
2907
+
2908
+ // Errors that report a failure of the tool itself (the handler threw, or its result could not
2909
+ // be delivered), as opposed to a refusal by the enclave. callTool(..., { throwOnError: false })
2910
+ // turns only these into { success: false, error } results. Keyed by the safe error thrown.
2911
+ const toolFailures = new WeakMap();
2912
+
2347
2913
  // Blocked properties for secure proxy (from security level)
2348
2914
  const blockedPropertiesSet = new Set(${JSON.stringify(blockedProperties)});
2349
2915
 
@@ -2405,7 +2971,7 @@ ${stackTraceHardeningCode}
2405
2971
  var propName = String(property);
2406
2972
 
2407
2973
  // Check if property is non-configurable (proxy invariant requires returning actual value)
2408
- var descriptor = Object.getOwnPropertyDescriptor(target, property);
2974
+ var descriptor = __ag_getOwnPropertyDescriptor(target, property);
2409
2975
  var isNonConfigurable = descriptor && !descriptor.configurable;
2410
2976
 
2411
2977
  // Proxy invariant: if the target has a non-configurable, non-writable data property,
@@ -2426,15 +2992,14 @@ ${stackTraceHardeningCode}
2426
2992
  return exactValue;
2427
2993
  }
2428
2994
 
2429
- // Block dangerous properties - but respect proxy invariants
2995
+ // Block dangerous properties. The ONLY [[Get]] invariant that forces a specific return
2996
+ // value is for a non-writable + non-configurable DATA property \u2014 already handled above.
2997
+ // Anything reaching here is configurable, a non-configurable WRITABLE data property (such
2998
+ // as a function own prototype), or a non-configurable accessor; the invariant constrains
2999
+ // none of these, so the trap must never hand back the raw value. GHSA-3279: the old
3000
+ // "isNonConfigurable and not host -> return Reflect.get(...)" branch leaked the raw
3001
+ // writable prototype, exposing a parent-realm Object and defeating the membrane.
2430
3002
  if (blockedPropertiesSet.has(propName)) {
2431
- // For non-configurable properties, we MUST return the actual value
2432
- // (JavaScript proxy invariant - can't hide non-configurable properties).
2433
- // Host-owned values instead deny the read: every descriptor shape that could force
2434
- // the trap's result was handled above, so returning undefined is invariant-safe.
2435
- if (isNonConfigurable && !host) {
2436
- return Reflect.get(target, property, receiver);
2437
- }
2438
3003
  if (throwOnBlocked) {
2439
3004
  throw createSafeError(
2440
3005
  "Security violation: Access to '" + propName + "' is blocked. " +
@@ -2444,12 +3009,15 @@ ${stackTraceHardeningCode}
2444
3009
  return undefined;
2445
3010
  }
2446
3011
 
2447
- var value = Reflect.get(target, property, receiver);
3012
+ var value = __ag_ReflectGet(target, property, receiver);
2448
3013
 
2449
3014
  // For function values, bind to target first (preserves internal slot access for Promises, etc.)
2450
3015
  // Then recursively proxy the bound function to block constructor access
2451
3016
  if (typeof value === 'function') {
2452
- var boundMethod = value.bind(target);
3017
+ var boundMethod = __ag_functionBind.call(value, target);
3018
+ if (host && hostIsBuiltinMethod(value)) {
3019
+ ungatedHostFunctions.add(boundMethod);
3020
+ }
2453
3021
  return createSecureProxy(boundMethod, depth + 1, host);
2454
3022
  }
2455
3023
 
@@ -2472,7 +3040,7 @@ ${stackTraceHardeningCode}
2472
3040
  }
2473
3041
  return false;
2474
3042
  }
2475
- return Reflect.set(target, property, value, receiver);
3043
+ return __ag_ReflectSet(target, property, value, receiver);
2476
3044
  },
2477
3045
  defineProperty: function(target, property, descriptor) {
2478
3046
  var propName = String(property);
@@ -2485,11 +3053,11 @@ ${stackTraceHardeningCode}
2485
3053
  }
2486
3054
  return false;
2487
3055
  }
2488
- return Reflect.defineProperty(target, property, descriptor);
3056
+ return __ag_ReflectDefineProperty(target, property, descriptor);
2489
3057
  },
2490
3058
  getOwnPropertyDescriptor: function(target, property) {
2491
3059
  var propName = String(property);
2492
- var descriptor = Reflect.getOwnPropertyDescriptor(target, property);
3060
+ var descriptor = __ag_ReflectGetOwnPropertyDescriptor(target, property);
2493
3061
 
2494
3062
  // Mirror the get trap's host-owned pinned-value refusal: a non-configurable, non-writable
2495
3063
  // data property must be reported with its exact value (proxy invariant), so on a HOST-owned
@@ -2538,7 +3106,7 @@ ${stackTraceHardeningCode}
2538
3106
  // hands back a raw function that leads to the host Function constructor.
2539
3107
  if (descriptor && (typeof descriptor.get === 'function' || typeof descriptor.set === 'function')) {
2540
3108
  var accessorWrapped = {};
2541
- for (var ak in descriptor) { if (Object.prototype.hasOwnProperty.call(descriptor, ak)) accessorWrapped[ak] = descriptor[ak]; }
3109
+ for (var ak in descriptor) { if (__ag_hasOwnProperty.call(descriptor, ak)) accessorWrapped[ak] = descriptor[ak]; }
2542
3110
  if (typeof descriptor.get === 'function') accessorWrapped.get = createSecureProxy(descriptor.get, depth + 1, host);
2543
3111
  if (typeof descriptor.set === 'function') accessorWrapped.set = createSecureProxy(descriptor.set, depth + 1, host);
2544
3112
  return accessorWrapped;
@@ -2550,7 +3118,7 @@ ${stackTraceHardeningCode}
2550
3118
  var value = descriptor.value;
2551
3119
  if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
2552
3120
  var wrapped = {};
2553
- for (var dk in descriptor) { if (Object.prototype.hasOwnProperty.call(descriptor, dk)) wrapped[dk] = descriptor[dk]; }
3121
+ for (var dk in descriptor) { if (__ag_hasOwnProperty.call(descriptor, dk)) wrapped[dk] = descriptor[dk]; }
2554
3122
  wrapped.value = createSecureProxy(value, depth + 1, host);
2555
3123
  return wrapped;
2556
3124
  }
@@ -2558,7 +3126,7 @@ ${stackTraceHardeningCode}
2558
3126
  return descriptor;
2559
3127
  },
2560
3128
  ownKeys: function(target) {
2561
- var keys = Reflect.ownKeys(target);
3129
+ var keys = __ag_ReflectOwnKeys(target);
2562
3130
  return keys.filter(function(key) {
2563
3131
  var keyStr = String(key);
2564
3132
  // Keep non-blocked properties
@@ -2566,7 +3134,7 @@ ${stackTraceHardeningCode}
2566
3134
  return true;
2567
3135
  }
2568
3136
  // Must keep non-configurable properties (proxy invariant)
2569
- var descriptor = Object.getOwnPropertyDescriptor(target, key);
3137
+ var descriptor = __ag_getOwnPropertyDescriptor(target, key);
2570
3138
  if (descriptor && !descriptor.configurable) {
2571
3139
  return true;
2572
3140
  }
@@ -2586,18 +3154,29 @@ ${stackTraceHardeningCode}
2586
3154
  // (Promise.prototype up to Function) to reach the host Function constructor for RCE.
2587
3155
  // Results are re-wrapped at a FRESH depth (0) so a chain of calls such as
2588
3156
  // then().then() cannot inflate depth past the recursion cap and leak an unwrapped value.
3157
+ //
3158
+ // SECURITY: a call into a HOST function (a custom global, a method read off one, or
3159
+ // call/apply/bind on one) goes through the global-function gate instead: abort check,
3160
+ // maxGlobalFunctionCalls, the shared operation rate limit, and a sanitized, parent-realm
3161
+ // copy of the result. Without it those calls skipped every limit that guards callTool, and
3162
+ // their results arrived unsanitized. Only built-in methods of host data are exempt.
2589
3163
  apply: function(target, thisArg, args) {
2590
- return createSecureProxy(Reflect.apply(target, thisArg, args), 0, host);
2591
- }
2592
- // NOTE: intentionally NO construct trap here (unlike the standalone secure-proxy used
2593
- // for single-VM mode). Every constructor reachable from sandbox code resolves to an
3164
+ if (host && !ungatedHostFunctions.has(target)) {
3165
+ return callHostFunction(target, thisArg, args);
3166
+ }
3167
+ return createSecureProxy(__ag_ReflectApply(target, thisArg, args), 0, host);
3168
+ },
3169
+ // Constructing a HOST function would hand back a raw host instance without passing the
3170
+ // gate, so it is refused. Realm-owned values keep NO construct trap (undefined here means
3171
+ // the default behavior): every constructor reachable from sandbox code resolves to an
2594
3172
  // inner-VM or parent-VM intrinsic, and BOTH of those realms run with code generation
2595
3173
  // from strings disabled, so a 'new X()' result cannot reach a usable Function
2596
- // constructor. The only code-generation-enabled realm (the host) is reached solely via
2597
- // host return values (callTool), which is an apply-path and is covered above. Wrapping
2598
- // construct results would additionally break the proxy invariant for the frozen (non-
2599
- // extensible) Error objects the harness throws (getPrototypeOf must not report null for
2600
- // a non-extensible target), masking legitimate errors.
3174
+ // constructor. Wrapping construct results would additionally break the proxy invariant
3175
+ // for the frozen (non-extensible) Error objects the harness throws (getPrototypeOf must
3176
+ // not report null for a non-extensible target), masking legitimate errors.
3177
+ construct: host ? function() {
3178
+ throw createSafeError('Host functions cannot be called with new', 'TypeError');
3179
+ } : undefined
2601
3180
  });
2602
3181
 
2603
3182
  cache.set(obj, proxy);
@@ -2609,19 +3188,91 @@ ${stackTraceHardeningCode}
2609
3188
  }
2610
3189
 
2611
3190
  /**
2612
- * Validate an operation before forwarding to host
3191
+ * Operation rate limit, shared by tool calls and calls into host functions.
3192
+ * Sliding one-second window; entries older than two seconds are dropped.
2613
3193
  */
2614
- function validateOperation(operationName, args) {
2615
- // Rate limiting check with sliding window cleanup
2616
- const now = Date.now();
2617
- // Clean up old entries to prevent unbounded growth (keep only last 2 seconds)
3194
+ function enforceRateLimit(now) {
2618
3195
  while (operationHistory.length > 0 && now - operationHistory[0].timestamp > 2000) {
2619
3196
  operationHistory.shift();
2620
3197
  }
2621
- const recentOperations = operationHistory.filter(function(h) { return now - h.timestamp < 1000; });
2622
- if (recentOperations.length >= validationConfig.maxOperationsPerSecond) {
3198
+ while (globalFunctionCallTimes.length > 0 && now - globalFunctionCallTimes[0] > 2000) {
3199
+ globalFunctionCallTimes.shift();
3200
+ }
3201
+ var recent = 0;
3202
+ for (var r = 0; r < operationHistory.length; r++) {
3203
+ if (now - operationHistory[r].timestamp < 1000) recent++;
3204
+ }
3205
+ for (var g = 0; g < globalFunctionCallTimes.length; g++) {
3206
+ if (now - globalFunctionCallTimes[g] < 1000) recent++;
3207
+ }
3208
+ if (recent >= validationConfig.maxOperationsPerSecond) {
2623
3209
  throw createSafeError('Operation rate limit exceeded (' + validationConfig.maxOperationsPerSecond + ' operations/second)');
2624
3210
  }
3211
+ }
3212
+
3213
+ /**
3214
+ * Parse the host invoker's JSON envelope into a parent-realm value, or throw its error.
3215
+ */
3216
+ function decodeGlobalFunctionResult(envelopeJson) {
3217
+ if (typeof envelopeJson !== 'string') {
3218
+ throw createSafeError('Global function bridge returned an invalid response');
3219
+ }
3220
+ var envelope;
3221
+ try {
3222
+ envelope = JSON.parse(envelopeJson);
3223
+ } catch (e) {
3224
+ throw createSafeError('Global function bridge returned invalid JSON');
3225
+ }
3226
+ if (!envelope || typeof envelope !== 'object' || envelope.v !== 1) {
3227
+ throw createSafeError('Global function bridge returned an invalid response');
3228
+ }
3229
+ if (envelope.ok === true) {
3230
+ return __ag_hasOwnProperty.call(envelope, 'value') ? envelope.value : undefined;
3231
+ }
3232
+ var failure = envelope.error;
3233
+ var message = (failure && typeof failure.message === 'string') ? failure.message : 'Global function call failed';
3234
+ var name = (failure && typeof failure.name === 'string') ? failure.name : 'Error';
3235
+ throw createSafeError(message, name);
3236
+ }
3237
+
3238
+ /**
3239
+ * The global-function gate: every call from the sandbox into a host function passed in
3240
+ * globals (including functions nested in objects) comes through here.
3241
+ */
3242
+ function callHostFunction(target, thisArg, args) {
3243
+ if (hostAbortCheck()) {
3244
+ throw createSafeError('Execution aborted');
3245
+ }
3246
+ if (typeof hostInvokeGlobal !== 'function') {
3247
+ throw createSafeError('Global function bridge is not available');
3248
+ }
3249
+
3250
+ globalFunctionCallCount++;
3251
+ if (globalFunctionCallCount > ${maxGlobalFunctionCalls}) {
3252
+ throw createSafeError(${JSON.stringify(globalFunctionLimitMessage(maxGlobalFunctionCalls))});
3253
+ }
3254
+
3255
+ var now = Date.now();
3256
+ enforceRateLimit(now);
3257
+ globalFunctionCallTimes.push(now);
3258
+
3259
+ var outcome = hostInvokeGlobal(target, thisArg, args);
3260
+ if (typeof outcome === 'string') {
3261
+ return createSecureProxy(decodeGlobalFunctionResult(outcome));
3262
+ }
3263
+
3264
+ // A host function that returned a thenable: settle to a sanitized parent-realm value.
3265
+ return createSecureProxy(outcome.then(decodeGlobalFunctionResult).then(function(value) {
3266
+ return createSecureProxy(value);
3267
+ }));
3268
+ }
3269
+
3270
+ /**
3271
+ * Validate an operation before forwarding to host
3272
+ */
3273
+ function validateOperation(operationName, args) {
3274
+ // Rate limiting check with sliding window cleanup
3275
+ enforceRateLimit(Date.now());
2625
3276
 
2626
3277
  // Operation name format validation
2627
3278
  if (typeof operationName !== 'string' || !operationName) {
@@ -2663,11 +3314,64 @@ ${stackTraceHardeningCode}
2663
3314
  }
2664
3315
  }
2665
3316
 
3317
+ /**
3318
+ * Read a script's callTool options. Only { throwOnError: false } changes behavior.
3319
+ */
3320
+ function readThrowOnError(options) {
3321
+ if (options === undefined || options === null) return true;
3322
+ if (typeof options !== 'object') {
3323
+ throw createSafeError('callTool options must be an object', 'TypeError');
3324
+ }
3325
+ return options.throwOnError !== false;
3326
+ }
3327
+
3328
+ /**
3329
+ * Remember that a safe error reports a failure of the tool itself (see toolFailures).
3330
+ */
3331
+ function markToolFailure(error, toolName, name, message, code) {
3332
+ var info = { name: name, message: message, toolName: toolName };
3333
+ if (typeof code === 'string') info.code = code;
3334
+ toolFailures.set(error, info);
3335
+ return error;
3336
+ }
3337
+
3338
+ /**
3339
+ * Whether a tool bridge payload is larger than the limit in UTF-8 bytes, as the host counts it.
3340
+ * A code unit is 1 to 3 bytes (a surrogate pair is 4), so only lengths in between are counted.
3341
+ */
3342
+ function exceedsPayloadLimit(str, maxBytes) {
3343
+ if (str.length > maxBytes) return true;
3344
+ if (str.length * 3 <= maxBytes) return false;
3345
+ var bytes = 0;
3346
+ for (var i = 0; i < str.length; i++) {
3347
+ var c = str.charCodeAt(i);
3348
+ if (c < 0x80) bytes += 1;
3349
+ else if (c < 0x800) bytes += 2;
3350
+ else if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
3351
+ var d = str.charCodeAt(i + 1);
3352
+ if (d >= 0xdc00 && d <= 0xdfff) {
3353
+ bytes += 4;
3354
+ i++;
3355
+ } else {
3356
+ bytes += 3;
3357
+ }
3358
+ } else bytes += 3;
3359
+ if (bytes > maxBytes) return true;
3360
+ }
3361
+ return false;
3362
+ }
3363
+
2666
3364
  /**
2667
3365
  * Inner VM's callTool function
2668
3366
  * Proxies through parent VM with validation
3367
+ *
3368
+ * options.throwOnError === false: a failing tool resolves to { success: false, error } and a
3369
+ * working one to { success: true, data }. Refusals by the enclave (abort, tool-call cap, rate
3370
+ * limit, operation-name and suspicious-sequence checks, invalid arguments) still throw.
2669
3371
  */
2670
- function innerCallTool(toolName, args) {
3372
+ function innerCallTool(toolName, args, options) {
3373
+ var throwOnError = readThrowOnError(options);
3374
+
2671
3375
  // Check if aborted
2672
3376
  if (hostAbortCheck()) {
2673
3377
  throw createSafeError('Execution aborted');
@@ -2716,8 +3420,8 @@ ${stackTraceHardeningCode}
2716
3420
  throw createSafeError('Tool request must be JSON-serializable');
2717
3421
  }
2718
3422
 
2719
- // Conservative byte estimate: UTF-8 is at most 4 bytes per code unit.
2720
- if (requestJson && (requestJson.length * 4) > toolBridgeMaxPayloadBytes) {
3423
+ // Counted in UTF-8 bytes, as the host counts it, so both sides agree on the limit.
3424
+ if (requestJson && exceedsPayloadLimit(requestJson, toolBridgeMaxPayloadBytes)) {
2721
3425
  throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
2722
3426
  }
2723
3427
 
@@ -2726,8 +3430,17 @@ ${stackTraceHardeningCode}
2726
3430
  throw createSafeError('Tool bridge returned non-string response');
2727
3431
  }
2728
3432
 
2729
- if ((responseJson.length * 4) > toolBridgeMaxPayloadBytes) {
2730
- throw createSafeError('Tool response exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
3433
+ // The host refuses an oversized response as a tool failure; this check only backs it up,
3434
+ // and reports the same way so { throwOnError: false } resolves it to a result.
3435
+ if (exceedsPayloadLimit(responseJson, toolBridgeMaxPayloadBytes)) {
3436
+ var tooLarge = 'Tool response exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)';
3437
+ throw markToolFailure(
3438
+ createSafeError(tooLarge, 'RangeError'),
3439
+ toolName,
3440
+ 'RangeError',
3441
+ tooLarge,
3442
+ 'TOOL_BRIDGE_RESPONSE_TOO_LARGE'
3443
+ );
2731
3444
  }
2732
3445
 
2733
3446
  var response;
@@ -2746,7 +3459,7 @@ ${stackTraceHardeningCode}
2746
3459
  }
2747
3460
 
2748
3461
  if (response.ok === true) {
2749
- if (Object.prototype.hasOwnProperty.call(response, 'value')) {
3462
+ if (__ag_hasOwnProperty.call(response, 'value')) {
2750
3463
  return response.value;
2751
3464
  }
2752
3465
  return undefined;
@@ -2756,13 +3469,36 @@ ${stackTraceHardeningCode}
2756
3469
  var err = response.error;
2757
3470
  var msg = (err && typeof err.message === 'string') ? err.message : 'Tool call failed';
2758
3471
  var name = (err && typeof err.name === 'string') ? err.name : 'Error';
2759
- throw createSafeError(msg, name);
3472
+ var failure = createSafeError(msg, name);
3473
+ if (err && err.toolError === true) {
3474
+ markToolFailure(failure, toolName, name, msg, err.code);
3475
+ }
3476
+ throw failure;
2760
3477
  }
2761
3478
 
2762
3479
  throw createSafeError('Tool bridge returned invalid response');
2763
3480
  });
2764
3481
  } else {
2765
- promise = hostCallTool(toolName, sanitizedArgs);
3482
+ promise = hostCallTool(toolName, sanitizedArgs).then(undefined, function(error) {
3483
+ // Direct mode: the host marks failures of the tool itself with this code.
3484
+ if (error && error.code === 'TOOL_CALL_FAILED') {
3485
+ var message = typeof error.message === 'string' ? error.message : 'Tool call failed';
3486
+ throw markToolFailure(createSafeError(message), toolName, 'Error', message, 'TOOL_CALL_FAILED');
3487
+ }
3488
+ throw error;
3489
+ });
3490
+ }
3491
+
3492
+ if (!throwOnError) {
3493
+ promise = promise.then(function(result) {
3494
+ return { success: true, data: result };
3495
+ }, function(error) {
3496
+ var info = toolFailures.get(error);
3497
+ if (info) {
3498
+ return { success: false, error: info };
3499
+ }
3500
+ throw error;
3501
+ });
2766
3502
  }
2767
3503
 
2768
3504
  // Create a secure promise that wraps both the promise object and its result
@@ -3415,6 +4151,36 @@ ${stackTraceHardeningCode}
3415
4151
  innerRuntimeScript.runInContext(innerContext);
3416
4152
  } catch (e) { /* ignore */ }
3417
4153
 
4154
+ // Tool namespaces (mail.list(args)): built INSIDE the inner realm by a factory evaluated there
4155
+ // (before Object/JSON are replaced by the safe globals below), so each namespace is a frozen,
4156
+ // null-prototype inner-realm object whose methods call the gated callTool. A namespace call is
4157
+ // therefore an ordinary tool call: counted, rate-limited, pattern-checked and sanitized.
4158
+ var toolNamespaceNames = ${JSON.stringify(toolNamespaces.map((ns) => ns.name))};
4159
+ if (toolNamespaceNames.length > 0) {
4160
+ var installToolNamespaces = new vm.Script(${JSON.stringify(TOOL_NAMESPACE_FACTORY_SOURCE)}, {
4161
+ filename: 'inner-tool-namespaces.js'
4162
+ }).runInContext(innerContext);
4163
+ var builtToolNamespaces = installToolNamespaces(safeRuntime.__safe_callTool, ${JSON.stringify(
4164
+ JSON.stringify(toolNamespaces)
4165
+ )});
4166
+ for (var tn = 0; tn < toolNamespaceNames.length; tn++) {
4167
+ var toolNamespaceName = toolNamespaceNames[tn];
4168
+ var toolNamespace = builtToolNamespaces[toolNamespaceName];
4169
+ __ag_defineProperty(innerContext, toolNamespaceName, {
4170
+ value: toolNamespace,
4171
+ writable: false,
4172
+ configurable: false,
4173
+ enumerable: false
4174
+ });
4175
+ __ag_defineProperty(innerContext, '__safe_' + toolNamespaceName, {
4176
+ value: toolNamespace,
4177
+ writable: false,
4178
+ configurable: false,
4179
+ enumerable: false
4180
+ });
4181
+ }
4182
+ }
4183
+
3418
4184
  // Defense-in-depth: Remove host callback from inner sandbox after all scripts have captured it
3419
4185
  try { delete innerContext['__host_memory_track__']; } catch (e) { /* ignore */ }
3420
4186
 
@@ -3658,6 +4424,8 @@ var MEMBRANE_MAX_RECURSION_DEPTH, NODEJS_24_DANGEROUS_GLOBALS;
3658
4424
  var init_parent_vm_bootstrap = __esm({
3659
4425
  "libs/core/src/double-vm/parent-vm-bootstrap.ts"() {
3660
4426
  "use strict";
4427
+ init_global_function_gate();
4428
+ init_tool_namespaces();
3661
4429
  MEMBRANE_MAX_RECURSION_DEPTH = 256;
3662
4430
  NODEJS_24_DANGEROUS_GLOBALS = {
3663
4431
  STRICT: [
@@ -3870,36 +4638,7 @@ var init_suspicious_patterns = __esm({
3870
4638
 
3871
4639
  // libs/core/src/double-vm/double-vm-wrapper.ts
3872
4640
  import * as vm2 from "vm";
3873
- function sanitizeStackTrace(stack, sanitize = true) {
3874
- if (!stack || !sanitize) return stack;
3875
- let sanitized = stack;
3876
- for (const pattern of SENSITIVE_STACK_PATTERNS) {
3877
- pattern.lastIndex = 0;
3878
- sanitized = sanitized.replace(pattern, "[REDACTED]");
3879
- }
3880
- const lines = sanitized.split("\n");
3881
- for (let i = 0; i < lines.length; i++) {
3882
- const line = lines[i];
3883
- if (line.length > 1e3) continue;
3884
- if (/:\d+:\d+\)/.test(line)) {
3885
- const atIdx = line.indexOf("at ");
3886
- if (atIdx !== -1) {
3887
- const afterAt = line.substring(atIdx + 3).trimStart();
3888
- const spaceIdx = afterAt.indexOf(" ");
3889
- if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === "(") {
3890
- const funcName = afterAt.substring(0, spaceIdx);
3891
- lines[i] = line.substring(0, atIdx) + "at " + funcName + " ([REDACTED])";
3892
- continue;
3893
- }
3894
- }
3895
- }
3896
- if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
3897
- lines[i] = line.replace(/:\d+:\d+$/, "") + "[REDACTED]";
3898
- }
3899
- }
3900
- return lines.join("\n");
3901
- }
3902
- var SENSITIVE_STACK_PATTERNS, DoubleVmWrapper;
4641
+ var DoubleVmWrapper;
3903
4642
  var init_double_vm_wrapper = __esm({
3904
4643
  "libs/core/src/double-vm/double-vm-wrapper.ts"() {
3905
4644
  "use strict";
@@ -3909,14 +4648,10 @@ var init_double_vm_wrapper = __esm({
3909
4648
  init_reference_resolver();
3910
4649
  init_memory_tracker();
3911
4650
  init_tool_bridge();
4651
+ init_stack_trace();
4652
+ init_global_function_gate();
3912
4653
  init_parent_vm_bootstrap();
3913
4654
  init_suspicious_patterns();
3914
- SENSITIVE_STACK_PATTERNS = [
3915
- /\/Users\/[^/]+\/[^\s):]*/gi,
3916
- /\/home\/[^/]+\/[^\s):]*/gi,
3917
- /\/var\/[^\s):]*/gi,
3918
- /node_modules\/[^\s):]+/gi
3919
- ];
3920
4655
  DoubleVmWrapper = class {
3921
4656
  constructor(config, securityLevel) {
3922
4657
  this.config = config;
@@ -4080,6 +4815,18 @@ var init_double_vm_wrapper = __esm({
4080
4815
  configurable: true
4081
4816
  // Allow deletion after capture for defense-in-depth
4082
4817
  });
4818
+ Object.defineProperty(parentContext, "__host_invokeGlobal__", {
4819
+ value: createHostGlobalFunctionInvoker(executionContext),
4820
+ writable: false,
4821
+ configurable: true
4822
+ // Allow deletion after capture for defense-in-depth
4823
+ });
4824
+ Object.defineProperty(parentContext, "__host_isBuiltinMethod__", {
4825
+ value: (fn) => isBuiltinMethod(fn),
4826
+ writable: false,
4827
+ configurable: true
4828
+ // Allow deletion after capture for defense-in-depth
4829
+ });
4083
4830
  Object.defineProperty(parentContext, "__host_stats__", {
4084
4831
  value: stats,
4085
4832
  writable: false,
@@ -4215,7 +4962,11 @@ var init_double_vm_wrapper = __esm({
4215
4962
  return sanitized;
4216
4963
  } catch (error) {
4217
4964
  const err = error;
4218
- throw createSafeError(`Tool call failed: ${toolName} - ${err.message || "Unknown error"}`);
4965
+ throw createSafeError(
4966
+ `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`,
4967
+ "Error",
4968
+ "TOOL_CALL_FAILED"
4969
+ );
4219
4970
  }
4220
4971
  };
4221
4972
  }
@@ -4260,7 +5011,9 @@ var init_double_vm_wrapper = __esm({
4260
5011
  memoryLimit: config.memoryLimit,
4261
5012
  throwOnBlocked,
4262
5013
  toolBridgeMode,
4263
- toolBridgeMaxPayloadBytes
5014
+ toolBridgeMaxPayloadBytes,
5015
+ maxGlobalFunctionCalls: resolveMaxGlobalFunctionCalls(config),
5016
+ toolNamespaces: executionContext.toolNamespaces ?? []
4264
5017
  });
4265
5018
  }
4266
5019
  /**
@@ -4441,6 +5194,16 @@ var init_memory_proxy = __esm({
4441
5194
  });
4442
5195
 
4443
5196
  // libs/core/src/safe-runtime.ts
5197
+ function readThrowOnError(options) {
5198
+ if (options === void 0 || options === null) return true;
5199
+ if (typeof options !== "object") {
5200
+ throw createSafeTypeError("callTool options must be an object");
5201
+ }
5202
+ return options.throwOnError !== false;
5203
+ }
5204
+ function plainResult(fields) {
5205
+ return Object.assign(/* @__PURE__ */ Object.create(null), fields);
5206
+ }
4444
5207
  function createSafeRuntime(context, options) {
4445
5208
  const { config, stats } = context;
4446
5209
  const sidecar = options?.sidecar;
@@ -4449,7 +5212,8 @@ function createSafeRuntime(context, options) {
4449
5212
  const memoryTracker = options?.memoryTracker;
4450
5213
  const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
4451
5214
  const proxyOptions = secureProxyConfig ? { levelConfig: secureProxyConfig } : {};
4452
- async function __safe_callTool(toolName, args) {
5215
+ async function __safe_callTool(toolName, args, options2) {
5216
+ const throwOnError = readThrowOnError(options2);
4453
5217
  if (context.aborted) {
4454
5218
  throw createSafeError("Execution aborted");
4455
5219
  }
@@ -4493,21 +5257,34 @@ function createSafeRuntime(context, options) {
4493
5257
  allowDates: true,
4494
5258
  allowErrors: true
4495
5259
  });
5260
+ let value = sanitized;
4496
5261
  if (sidecar && referenceConfig && typeof sanitized === "string") {
4497
5262
  const size = Buffer.byteLength(sanitized, "utf-8");
4498
5263
  if (size >= referenceConfig.extractionThreshold) {
4499
5264
  try {
4500
- const refId = sidecar.store(sanitized, "tool-result", { origin: toolName });
4501
- return refId;
5265
+ value = sidecar.store(sanitized, "tool-result", { origin: toolName });
4502
5266
  } catch {
4503
- return sanitized;
5267
+ value = sanitized;
4504
5268
  }
4505
5269
  }
4506
5270
  }
4507
- return sanitized;
5271
+ return throwOnError ? value : plainResult({ success: true, data: value });
4508
5272
  } catch (error) {
4509
5273
  const err = error;
4510
- throw createSafeError(`Tool call failed: ${toolName} - ${err.message || "Unknown error"}`);
5274
+ const message = `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`;
5275
+ if (!throwOnError) {
5276
+ const code = error?.code;
5277
+ return plainResult({
5278
+ success: false,
5279
+ error: plainResult({
5280
+ name: "Error",
5281
+ message,
5282
+ ...typeof code === "string" ? { code } : {},
5283
+ toolName
5284
+ })
5285
+ });
5286
+ }
5287
+ throw createSafeError(message);
4511
5288
  }
4512
5289
  }
4513
5290
  function* __safe_forOf(iterable) {
@@ -4704,7 +5481,8 @@ ${errorMessages}`);
4704
5481
  }
4705
5482
  const customGlobalsWithPrefix = {};
4706
5483
  if (config.globals) {
4707
- const wrappedCustomGlobals = wrapGlobalsWithSecureProxy(config.globals, proxyOptions);
5484
+ const customGlobalProxyOptions = options?.globalFunctionGate ? { ...proxyOptions, callGate: options.globalFunctionGate } : proxyOptions;
5485
+ const wrappedCustomGlobals = wrapGlobalsWithSecureProxy(config.globals, customGlobalProxyOptions);
4708
5486
  for (const [key, value] of Object.entries(wrappedCustomGlobals)) {
4709
5487
  customGlobalsWithPrefix[`__safe_${key}`] = value;
4710
5488
  }
@@ -4759,18 +5537,22 @@ ${errorMessages}`);
4759
5537
  }
4760
5538
  function serializeSafeRuntime() {
4761
5539
  return `
4762
- // Safe callTool implementation
4763
- async function __safe_callTool(toolName, args) {
5540
+ // Safe callTool implementation. The options ({ throwOnError: false }) are passed on:
5541
+ // only the adapter's __internal_callTool can tell a failure of the tool from a refusal.
5542
+ async function __safe_callTool(toolName, args, options) {
4764
5543
  if (typeof toolName !== 'string' || !toolName) {
4765
5544
  throw new TypeError('Tool name must be a non-empty string');
4766
5545
  }
4767
5546
  if (typeof args !== 'object' || args === null || Array.isArray(args)) {
4768
5547
  throw new TypeError('Tool arguments must be an object');
4769
5548
  }
5549
+ if (options !== undefined && options !== null && typeof options !== 'object') {
5550
+ throw new TypeError('callTool options must be an object');
5551
+ }
4770
5552
 
4771
5553
  // This will be replaced by the sandbox adapter with actual implementation
4772
5554
  if (typeof __internal_callTool === 'function') {
4773
- return await __internal_callTool(toolName, args);
5555
+ return await __internal_callTool(toolName, args, options);
4774
5556
  }
4775
5557
  throw new Error('Tool handler not available');
4776
5558
  }
@@ -4940,36 +5722,6 @@ __export(vm_adapter_exports, {
4940
5722
  VmAdapter: () => VmAdapter
4941
5723
  });
4942
5724
  import * as vm3 from "vm";
4943
- function sanitizeStackTrace2(stack, sanitize = true) {
4944
- if (!stack) return stack;
4945
- if (!sanitize) return stack;
4946
- let sanitized = stack;
4947
- for (const pattern of SENSITIVE_STACK_PATTERNS2) {
4948
- pattern.lastIndex = 0;
4949
- sanitized = sanitized.replace(pattern, "[REDACTED]");
4950
- }
4951
- const lines = sanitized.split("\n");
4952
- for (let i = 0; i < lines.length; i++) {
4953
- const line = lines[i];
4954
- if (line.length > 1e3) continue;
4955
- if (/:\d+:\d+\)/.test(line)) {
4956
- const atIdx = line.indexOf("at ");
4957
- if (atIdx !== -1) {
4958
- const afterAt = line.substring(atIdx + 3).trimStart();
4959
- const spaceIdx = afterAt.indexOf(" ");
4960
- if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === "(") {
4961
- const funcName = afterAt.substring(0, spaceIdx);
4962
- lines[i] = line.substring(0, atIdx) + "at " + funcName + " ([REDACTED])";
4963
- continue;
4964
- }
4965
- }
4966
- }
4967
- if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
4968
- lines[i] = line.replace(/:\d+:\d+$/, "") + "[REDACTED]";
4969
- }
4970
- }
4971
- return lines.join("\n");
4972
- }
4973
5725
  function createSafeConsole(config, stats) {
4974
5726
  const wrap = (method) => (...args) => {
4975
5727
  stats.callCount++;
@@ -5133,7 +5885,7 @@ function sanitizeVmContext(context, securityLevel) {
5133
5885
  enumerable: true
5134
5886
  });
5135
5887
  }
5136
- var SENSITIVE_STACK_PATTERNS2, STACK_TRACE_HARDENING_CODE, STACK_TRACE_HARDENING_SCRIPT, CODE_GENERATION_VIOLATION_DETECTOR_CODE, CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT, INTRINSIC_OBJECT_NEUTRALIZATION_CODE, INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT, PROTECTED_PREFIXES, DANGEROUS_OBJECT_STATIC_METHODS, NODEJS_24_DANGEROUS_GLOBALS2, VmAdapter;
5888
+ var 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;
5137
5889
  var init_vm_adapter = __esm({
5138
5890
  "libs/core/src/adapters/vm-adapter.ts"() {
5139
5891
  "use strict";
@@ -5143,130 +5895,9 @@ var init_vm_adapter = __esm({
5143
5895
  init_memory_tracker();
5144
5896
  init_tool_bridge();
5145
5897
  init_value_sanitizer();
5146
- SENSITIVE_STACK_PATTERNS2 = [
5147
- // Unix file system paths
5148
- /\/Users\/[^/]+\/[^\s):]*/gi,
5149
- // macOS home directories
5150
- /\/home\/[^/]+\/[^\s):]*/gi,
5151
- // Linux home directories
5152
- /\/var\/[^\s):]*/gi,
5153
- // System var directories
5154
- /\/opt\/[^\s):]*/gi,
5155
- // Optional software
5156
- /\/tmp\/[^\s):]*/gi,
5157
- // Temporary files
5158
- /\/etc\/[^\s):]*/gi,
5159
- // System configuration
5160
- /\/root\/[^\s):]*/gi,
5161
- // Root home directory
5162
- /\/mnt\/[^\s):]*/gi,
5163
- // Mount points
5164
- /\/srv\/[^\s):]*/gi,
5165
- // Service data
5166
- /\/data\/[^\s):]*/gi,
5167
- // Data directories
5168
- /\/app\/[^\s):]*/gi,
5169
- // Application directories
5170
- /\/proc\/[^\s):]*/gi,
5171
- // Process information
5172
- /\/sys\/[^\s):]*/gi,
5173
- // System files
5174
- // Windows paths
5175
- /\\\\[^\s):]*/g,
5176
- // UNC paths
5177
- /[A-Z]:\\[^\s):]+/gi,
5178
- // Windows drive paths
5179
- // URL-based paths
5180
- /file:\/\/[^\s):]+/gi,
5181
- // File URLs
5182
- /webpack:\/\/[^\s):]+/gi,
5183
- // Webpack paths
5184
- /%2F[^\s):]+/gi,
5185
- // URL-encoded paths
5186
- // Package managers and node
5187
- /node_modules\/[^\s):]+/gi,
5188
- // Node modules paths
5189
- /\/nix\/store\/[^\s):]*/gi,
5190
- // Nix store paths
5191
- /\.npm\/[^\s):]*/gi,
5192
- // NPM cache
5193
- /\.yarn\/[^\s):]*/gi,
5194
- // Yarn cache
5195
- /\.pnpm\/[^\s):]*/gi,
5196
- // PNPM cache
5197
- // Container and orchestration
5198
- /\/run\/secrets\/[^\s):]*/gi,
5199
- // Docker/K8s secrets
5200
- /\/var\/run\/[^\s):]*/gi,
5201
- // Runtime directories
5202
- /\/docker\/[^\s):]*/gi,
5203
- // Docker paths
5204
- /\/containers\/[^\s):]*/gi,
5205
- // Container paths
5206
- /\/kubelet\/[^\s):]*/gi,
5207
- // Kubernetes kubelet
5208
- // CI/CD systems
5209
- /\/github\/workspace\/[^\s):]*/gi,
5210
- // GitHub Actions
5211
- /\/runner\/[^\s):]*/gi,
5212
- // GitHub/GitLab runner
5213
- /\/builds\/[^\s):]*/gi,
5214
- // CI builds
5215
- /\/workspace\/[^\s):]*/gi,
5216
- // Generic workspace
5217
- /\/pipeline\/[^\s):]*/gi,
5218
- // CI pipelines
5219
- /\/jenkins\/[^\s):]*/gi,
5220
- // Jenkins
5221
- /\/bamboo\/[^\s):]*/gi,
5222
- // Bamboo
5223
- /\/teamcity\/[^\s):]*/gi,
5224
- // TeamCity
5225
- /\/circleci\/[^\s):]*/gi,
5226
- // CircleCI
5227
- // Cloud providers
5228
- /\/aws\/[^\s):]*/gi,
5229
- // AWS paths
5230
- /\/gcloud\/[^\s):]*/gi,
5231
- // Google Cloud
5232
- /\/azure\/[^\s):]*/gi,
5233
- // Azure paths
5234
- /s3:\/\/[^\s):]+/gi,
5235
- // S3 URIs
5236
- /gs:\/\/[^\s):]+/gi,
5237
- // GCS URIs
5238
- // Secrets and credentials (patterns that might appear in paths or errors)
5239
- /[A-Z0-9]{20,}/g,
5240
- // AWS-style access keys (20+ uppercase chars)
5241
- /sk-[a-zA-Z0-9]{32,}/g,
5242
- // OpenAI/Stripe-style secret keys
5243
- /ghp_[a-zA-Z0-9]{36,}/g,
5244
- // GitHub personal access tokens
5245
- /gho_[a-zA-Z0-9]{36,}/g,
5246
- // GitHub OAuth tokens
5247
- /github_pat_[a-zA-Z0-9_]{22,}/g,
5248
- // GitHub fine-grained tokens
5249
- /xox[baprs]-[a-zA-Z0-9-]+/g,
5250
- // Slack tokens
5251
- /Bearer\s+[a-zA-Z0-9._-]+/gi,
5252
- // Bearer tokens
5253
- /Basic\s+[a-zA-Z0-9+/=]+/gi,
5254
- // Basic auth
5255
- // Internal network info
5256
- /(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
5257
- // Private IPs
5258
- /[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
5259
- // Internal hostnames
5260
- /localhost:\d+/gi,
5261
- // Localhost with port
5262
- /127\.0\.0\.1:\d+/gi,
5263
- // Loopback with port
5264
- // User information
5265
- /\/u\/[^/]+\//gi,
5266
- // User subdirectories
5267
- /~[a-z_][a-z0-9_-]*/gi
5268
- // Unix user home shorthand
5269
- ];
5898
+ init_stack_trace();
5899
+ init_global_function_gate();
5900
+ init_tool_namespaces();
5270
5901
  STACK_TRACE_HARDENING_CODE = `
5271
5902
  (function() {
5272
5903
  function __ag_redactStackString(stackStr) {
@@ -5432,6 +6063,20 @@ var init_vm_adapter = __esm({
5432
6063
  })();
5433
6064
  `;
5434
6065
  INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new vm3.Script(INTRINSIC_OBJECT_NEUTRALIZATION_CODE);
6066
+ SANDBOX_REALM_BRIDGE_SCRIPT = new vm3.Script(`
6067
+ (function () {
6068
+ 'use strict';
6069
+ var parse = JSON.parse;
6070
+ var SandboxPromise = Promise;
6071
+ return Object.freeze({
6072
+ parseJson: function (json) { return parse(json); },
6073
+ adoptPromise: function (hostPromise) {
6074
+ return new SandboxPromise(function (resolve, reject) { hostPromise.then(resolve, reject); });
6075
+ }
6076
+ });
6077
+ })()
6078
+ `);
6079
+ TOOL_NAMESPACE_FACTORY_SCRIPT = new vm3.Script(TOOL_NAMESPACE_FACTORY_SOURCE, { filename: "tool-namespaces.js" });
5435
6080
  PROTECTED_PREFIXES = ["__safe_", "__ag_"];
5436
6081
  DANGEROUS_OBJECT_STATIC_METHODS = [
5437
6082
  "defineProperty",
@@ -5547,19 +6192,23 @@ var init_vm_adapter = __esm({
5547
6192
  }) : void 0;
5548
6193
  memoryTracker?.start();
5549
6194
  try {
5550
- const safeRuntime = createSafeRuntime(executionContext, {
5551
- sidecar: executionContext.sidecar,
5552
- referenceConfig: executionContext.referenceConfig,
5553
- secureProxyConfig: executionContext.secureProxyConfig,
5554
- memoryTracker
5555
- // Pass tracker for allocation monitoring
5556
- });
5557
6195
  const baseSandbox = vm3.createContext(
5558
6196
  {},
5559
6197
  {
5560
6198
  codeGeneration: { strings: false, wasm: false }
5561
6199
  }
5562
6200
  );
6201
+ const realmBridge = SANDBOX_REALM_BRIDGE_SCRIPT.runInContext(baseSandbox);
6202
+ const installToolNamespaces = executionContext.toolNamespaces?.length ? TOOL_NAMESPACE_FACTORY_SCRIPT.runInContext(baseSandbox) : void 0;
6203
+ const globalFunctionGate = createGlobalFunctionGate(executionContext, realmBridge);
6204
+ const safeRuntime = createSafeRuntime(executionContext, {
6205
+ sidecar: executionContext.sidecar,
6206
+ referenceConfig: executionContext.referenceConfig,
6207
+ secureProxyConfig: executionContext.secureProxyConfig,
6208
+ memoryTracker,
6209
+ // Pass tracker for allocation monitoring
6210
+ globalFunctionGate
6211
+ });
5563
6212
  if (memoryTracker && config.memoryLimit && config.memoryLimit > 0) {
5564
6213
  Object.defineProperty(baseSandbox, "__host_memory_track__", {
5565
6214
  value: (bytes) => {
@@ -5723,9 +6372,28 @@ var init_vm_adapter = __esm({
5723
6372
  // Remove global handle after capture (defense-in-depth)
5724
6373
  try { delete globalThis.__host_callToolBridge__; } catch (e) { /* ignore */ }
5725
6374
 
5726
- function estimateBytes(str) {
5727
- // Conservative: UTF-8 can be up to 4 bytes per code unit.
5728
- return str.length * 4;
6375
+ // Whether a payload is larger than the limit in UTF-8 bytes, as the host counts it. A code
6376
+ // unit is 1 to 3 bytes (a surrogate pair is 4), so only lengths in between are counted.
6377
+ function exceedsPayloadLimit(str) {
6378
+ if (str.length > maxBytes) return true;
6379
+ if (str.length * 3 <= maxBytes) return false;
6380
+ var bytes = 0;
6381
+ for (var i = 0; i < str.length; i++) {
6382
+ var c = str.charCodeAt(i);
6383
+ if (c < 0x80) bytes += 1;
6384
+ else if (c < 0x800) bytes += 2;
6385
+ else if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
6386
+ var d = str.charCodeAt(i + 1);
6387
+ if (d >= 0xdc00 && d <= 0xdfff) {
6388
+ bytes += 4;
6389
+ i++;
6390
+ } else {
6391
+ bytes += 3;
6392
+ }
6393
+ } else bytes += 3;
6394
+ if (bytes > maxBytes) return true;
6395
+ }
6396
+ return false;
5729
6397
  }
5730
6398
 
5731
6399
  function makeError(message, name) {
@@ -5734,7 +6402,16 @@ var init_vm_adapter = __esm({
5734
6402
  return err;
5735
6403
  }
5736
6404
 
5737
- return async function __safe_callTool(toolName, args) {
6405
+ return async function __safe_callTool(toolName, args, options) {
6406
+ // callTool options: only { throwOnError: false } changes behavior. Tool failures
6407
+ // then resolve to { success: false, error }; the enclave's own refusals still throw.
6408
+ var throwOnError = true;
6409
+ if (options !== undefined && options !== null) {
6410
+ if (typeof options !== 'object') {
6411
+ throw makeError('callTool options must be an object', 'TypeError');
6412
+ }
6413
+ throwOnError = options.throwOnError !== false;
6414
+ }
5738
6415
  if (typeof toolName !== 'string' || !toolName) {
5739
6416
  throw makeError('Tool name must be a non-empty string', 'TypeError');
5740
6417
  }
@@ -5760,7 +6437,7 @@ var init_vm_adapter = __esm({
5760
6437
  throw makeError('Tool request must be JSON-serializable', 'TypeError');
5761
6438
  }
5762
6439
 
5763
- if (estimateBytes(requestJson) > maxBytes) {
6440
+ if (exceedsPayloadLimit(requestJson)) {
5764
6441
  throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
5765
6442
  }
5766
6443
 
@@ -5768,8 +6445,24 @@ var init_vm_adapter = __esm({
5768
6445
  if (typeof responseJson !== 'string') {
5769
6446
  throw makeError('Tool bridge returned invalid response', 'Error');
5770
6447
  }
5771
- if (estimateBytes(responseJson) > maxBytes) {
5772
- throw makeError('Tool response exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
6448
+ // The host refuses an oversized response as a tool failure; this check only backs it
6449
+ // up, and reports the same way so { throwOnError: false } resolves it to a result.
6450
+ if (exceedsPayloadLimit(responseJson)) {
6451
+ var tooLarge = 'Tool response exceeds maximum size (' + maxBytes + ' bytes)';
6452
+ if (!throwOnError) {
6453
+ return {
6454
+ __proto__: null,
6455
+ success: false,
6456
+ error: {
6457
+ __proto__: null,
6458
+ name: 'RangeError',
6459
+ message: tooLarge,
6460
+ toolName: toolName,
6461
+ code: 'TOOL_BRIDGE_RESPONSE_TOO_LARGE',
6462
+ },
6463
+ };
6464
+ }
6465
+ throw makeError(tooLarge, 'RangeError');
5773
6466
  }
5774
6467
 
5775
6468
  var response;
@@ -5784,13 +6477,18 @@ var init_vm_adapter = __esm({
5784
6477
  }
5785
6478
 
5786
6479
  if (response.ok === true) {
5787
- if (hasOwn.call(response, 'value')) return response.value;
5788
- return undefined;
6480
+ var value = hasOwn.call(response, 'value') ? response.value : undefined;
6481
+ return throwOnError ? value : { __proto__: null, success: true, data: value };
5789
6482
  }
5790
6483
 
5791
6484
  if (response.ok === false && response.error) {
5792
6485
  var msg = (typeof response.error.message === 'string') ? response.error.message : 'Tool call failed';
5793
6486
  var name = (typeof response.error.name === 'string') ? response.error.name : 'Error';
6487
+ if (!throwOnError && response.error.toolError === true) {
6488
+ var info = { __proto__: null, name: name, message: msg, toolName: toolName };
6489
+ if (typeof response.error.code === 'string') info.code = response.error.code;
6490
+ return { __proto__: null, success: false, error: info };
6491
+ }
5794
6492
  throw makeError(msg, name);
5795
6493
  }
5796
6494
 
@@ -5824,8 +6522,9 @@ var init_vm_adapter = __esm({
5824
6522
  }
5825
6523
  if (config.globals) {
5826
6524
  for (const [key, value2] of Object.entries(config.globals)) {
5827
- const wrappedValue = value2 !== null && typeof value2 === "object" ? createSecureProxy(value2, {
5828
- levelConfig: executionContext.secureProxyConfig
6525
+ const wrappedValue = value2 !== null && (typeof value2 === "object" || typeof value2 === "function") ? createSecureProxy(value2, {
6526
+ levelConfig: executionContext.secureProxyConfig,
6527
+ callGate: globalFunctionGate
5829
6528
  }) : value2;
5830
6529
  Object.defineProperty(baseSandbox, key, {
5831
6530
  value: wrappedValue,
@@ -5835,6 +6534,23 @@ var init_vm_adapter = __esm({
5835
6534
  });
5836
6535
  }
5837
6536
  }
6537
+ if (executionContext.toolNamespaces?.length) {
6538
+ const callTool = baseSandbox["__safe_callTool"];
6539
+ for (const binding of buildToolNamespaceBindings(
6540
+ installToolNamespaces,
6541
+ callTool,
6542
+ executionContext.toolNamespaces
6543
+ )) {
6544
+ for (const name of [binding.name, `__safe_${binding.name}`]) {
6545
+ Object.defineProperty(baseSandbox, name, {
6546
+ value: binding.value,
6547
+ writable: false,
6548
+ configurable: false,
6549
+ enumerable: false
6550
+ });
6551
+ }
6552
+ }
6553
+ }
5838
6554
  if (!("__safe_console" in safeRuntime)) {
5839
6555
  const consoleStats = { totalBytes: 0, callCount: 0 };
5840
6556
  Object.defineProperty(baseSandbox, "__safe_console", {
@@ -5942,7 +6658,7 @@ var init_vm_adapter = __esm({
5942
6658
  error: {
5943
6659
  name: err.name || "VMExecutionError",
5944
6660
  message: err.message || "Unknown VM execution error",
5945
- stack: sanitizeStackTrace2(err.stack, shouldSanitize),
6661
+ stack: sanitizeStackTrace(err.stack, shouldSanitize),
5946
6662
  code: "VM_EXECUTION_ERROR"
5947
6663
  },
5948
6664
  stats
@@ -6086,6 +6802,7 @@ var init_config = __esm({
6086
6802
 
6087
6803
  // libs/core/src/adapters/worker-pool/protocol.ts
6088
6804
  import { z } from "zod";
6805
+ import { TOOL_NAMESPACE_TOOL_NAME_PATTERN } from "@enclave-vm/ast";
6089
6806
  function isToolCallMessage(msg) {
6090
6807
  return msg.type === "tool-call";
6091
6808
  }
@@ -6099,7 +6816,7 @@ var TOOL_NAME_PATTERN, ID_PATTERN, toolCallMessageSchema, executionResultMessage
6099
6816
  var init_protocol = __esm({
6100
6817
  "libs/core/src/adapters/worker-pool/protocol.ts"() {
6101
6818
  "use strict";
6102
- TOOL_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9:_-]*$/;
6819
+ TOOL_NAME_PATTERN = TOOL_NAMESPACE_TOOL_NAME_PATTERN;
6103
6820
  ID_PATTERN = /^[a-zA-Z0-9-]+$/;
6104
6821
  toolCallMessageSchema = z.object({
6105
6822
  type: z.literal("tool-call"),
@@ -6287,7 +7004,7 @@ var init_errors = __esm({
6287
7004
 
6288
7005
  // libs/core/src/adapters/worker-pool/safe-deserialize.ts
6289
7006
  function mapArraySafely(value, sanitizeItem) {
6290
- const rawLen = ReflectGet3(value, "length");
7007
+ const rawLen = ReflectGet4(value, "length");
6291
7008
  const len = typeof rawLen === "number" && NumberIsFinite3(rawLen) && rawLen >= 0 ? MathFloor3(rawLen) : 0;
6292
7009
  if (len > MAX_ARRAY_LENGTH) {
6293
7010
  throw new MessageValidationError(`Array exceeds maximum length of ${MAX_ARRAY_LENGTH}`);
@@ -6296,7 +7013,7 @@ function mapArraySafely(value, sanitizeItem) {
6296
7013
  for (let i = 0; i < len; i++) {
6297
7014
  let item;
6298
7015
  try {
6299
- item = ReflectGet3(value, i);
7016
+ item = ReflectGet4(value, i);
6300
7017
  } catch {
6301
7018
  item = void 0;
6302
7019
  }
@@ -6331,7 +7048,7 @@ function sanitizeObjectWithDepthCheck(value, depth) {
6331
7048
  if (typeof value !== "object") {
6332
7049
  return value;
6333
7050
  }
6334
- if (ArrayIsArray2(value)) {
7051
+ if (ArrayIsArray3(value)) {
6335
7052
  return mapArraySafely(value, (item) => sanitizeObjectWithDepthCheck(item, depth + 1));
6336
7053
  }
6337
7054
  const result = /* @__PURE__ */ Object.create(null);
@@ -6360,7 +7077,7 @@ function sanitizeObject(value, depth = 0) {
6360
7077
  if (typeof value !== "object") {
6361
7078
  return value;
6362
7079
  }
6363
- if (ArrayIsArray2(value)) {
7080
+ if (ArrayIsArray3(value)) {
6364
7081
  return mapArraySafely(value, (item) => sanitizeObject(item, depth + 1));
6365
7082
  }
6366
7083
  const result = /* @__PURE__ */ Object.create(null);
@@ -6371,13 +7088,13 @@ function sanitizeObject(value, depth = 0) {
6371
7088
  }
6372
7089
  return result;
6373
7090
  }
6374
- var ReflectGet3, ArrayIsArray2, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
7091
+ var ReflectGet4, ArrayIsArray3, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
6375
7092
  var init_safe_deserialize = __esm({
6376
7093
  "libs/core/src/adapters/worker-pool/safe-deserialize.ts"() {
6377
7094
  "use strict";
6378
7095
  init_errors();
6379
- ReflectGet3 = Reflect.get;
6380
- ArrayIsArray2 = Array.isArray;
7096
+ ReflectGet4 = Reflect.get;
7097
+ ArrayIsArray3 = Array.isArray;
6381
7098
  NumberIsFinite3 = Number.isFinite;
6382
7099
  MathFloor3 = Math.floor;
6383
7100
  MAX_ARRAY_LENGTH = 1e6;
@@ -7090,6 +7807,7 @@ var init_worker_pool_adapter = __esm({
7090
7807
  init_rate_limiter();
7091
7808
  init_safe_deserialize();
7092
7809
  init_errors();
7810
+ init_stack_trace();
7093
7811
  WorkerPoolAdapter = class {
7094
7812
  config;
7095
7813
  securityLevel;
@@ -7328,7 +8046,8 @@ var init_worker_pool_adapter = __esm({
7328
8046
  globals: context.config.globals,
7329
8047
  // Security level determines which globals are available in sandbox
7330
8048
  // This mirrors AST guard's allowed globals for defense-in-depth
7331
- securityLevel: this.securityLevel
8049
+ securityLevel: this.securityLevel,
8050
+ toolNamespaces: context.toolNamespaces ? [...context.toolNamespaces] : void 0
7332
8051
  };
7333
8052
  return new Promise((resolve, reject) => {
7334
8053
  const pendingToolCalls = /* @__PURE__ */ new Map();
@@ -7345,7 +8064,7 @@ var init_worker_pool_adapter = __esm({
7345
8064
  } else if (isExecutionResultMessage(msg) && msg.requestId === requestId) {
7346
8065
  cleanup();
7347
8066
  const duration = Date.now() - startTime;
7348
- const result = this.buildResult(msg, duration);
8067
+ const result = this.buildResult(msg, duration, context.config.sanitizeStackTraces);
7349
8068
  resolve(result);
7350
8069
  } else if (isConsoleMessage(msg) && msg.requestId === requestId) {
7351
8070
  this.handleConsoleMessage(msg);
@@ -7386,17 +8105,30 @@ var init_worker_pool_adapter = __esm({
7386
8105
  pendingToolCalls.set(msg.callId, true);
7387
8106
  let result;
7388
8107
  let error;
8108
+ let toolError = false;
7389
8109
  try {
7390
8110
  if (!context.toolHandler) {
7391
8111
  throw new Error("No tool handler configured");
7392
8112
  }
7393
8113
  const sanitizedArgs = sanitizeObject(msg.args);
7394
- result = await context.toolHandler(msg.toolName, sanitizedArgs);
8114
+ toolError = true;
8115
+ const handlerResult = await context.toolHandler(msg.toolName, sanitizedArgs);
8116
+ try {
8117
+ result = sanitizeObject(handlerResult);
8118
+ } catch {
8119
+ throw Object.assign(new Error("Tool returned an unsupported value"), {
8120
+ name: "ToolBridgeError",
8121
+ code: "TOOL_RESULT_NOT_SAFE"
8122
+ });
8123
+ }
8124
+ toolError = false;
7395
8125
  } catch (e) {
7396
8126
  const err = e;
8127
+ const code = e?.code;
7397
8128
  error = {
7398
8129
  name: err.name || "Error",
7399
- message: err.message || "Unknown error"
8130
+ message: err.message || "Unknown error",
8131
+ ...toolError && typeof code === "string" ? { code } : {}
7400
8132
  };
7401
8133
  } finally {
7402
8134
  pendingToolCalls.delete(msg.callId);
@@ -7405,8 +8137,9 @@ var init_worker_pool_adapter = __esm({
7405
8137
  type: "tool-response",
7406
8138
  requestId: msg.requestId,
7407
8139
  callId: msg.callId,
7408
- result: sanitizeObject(result),
7409
- error
8140
+ result,
8141
+ error,
8142
+ ...error && toolError ? { toolError: true } : {}
7410
8143
  });
7411
8144
  }
7412
8145
  handleConsoleMessage(msg) {
@@ -7423,7 +8156,7 @@ var init_worker_pool_adapter = __esm({
7423
8156
  * before sending, but full runtime type validation would require schema
7424
8157
  * definitions which are not available at this layer.
7425
8158
  */
7426
- buildResult(msg, duration) {
8159
+ buildResult(msg, duration, sanitizeStacks) {
7427
8160
  if (msg.success) {
7428
8161
  return {
7429
8162
  success: true,
@@ -7444,7 +8177,8 @@ var init_worker_pool_adapter = __esm({
7444
8177
  name: error.name,
7445
8178
  message: error.message,
7446
8179
  code: error.code,
7447
- stack: error.stack
8180
+ // The worker trims its stack; sanitize it here too so the result obeys the option.
8181
+ stack: sanitizeStackTrace(error.stack, sanitizeStacks)
7448
8182
  },
7449
8183
  stats: {
7450
8184
  duration,
@@ -8077,7 +8811,8 @@ import {
8077
8811
  extractLargeStrings,
8078
8812
  transformConcatenation,
8079
8813
  transformTemplateLiterals,
8080
- guardComputedMemberKeys
8814
+ guardComputedMemberKeys,
8815
+ normalizeToolNamespaces
8081
8816
  } from "@enclave-vm/ast";
8082
8817
  import * as acorn2 from "acorn";
8083
8818
  import { generate } from "astring";
@@ -8260,6 +8995,7 @@ var DEFAULT_DOUBLE_VM_CONFIG = {
8260
8995
  };
8261
8996
 
8262
8997
  // libs/core/src/globals-validator.ts
8998
+ import { types } from "util";
8263
8999
  var DANGEROUS_FUNCTION_PATTERNS = [
8264
9000
  /\beval\b/,
8265
9001
  // eval() calls
@@ -8287,7 +9023,55 @@ var DANGEROUS_FUNCTION_PATTERNS = [
8287
9023
  // Synchronous spawn
8288
9024
  ];
8289
9025
  var DANGEROUS_GLOBAL_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
8290
- function validateGlobalValue(key, value, options = {}, path2 = [], visited = /* @__PURE__ */ new WeakSet()) {
9026
+ var MapEntries = Map.prototype.entries;
9027
+ var SetValues = Set.prototype.values;
9028
+ var ReflectApply = Reflect.apply;
9029
+ var ReflectOwnKeys = Reflect.ownKeys;
9030
+ var ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
9031
+ var ObjectGetPrototypeOf = Object.getPrototypeOf;
9032
+ var ArrayPrototype = Array.prototype;
9033
+ var MapPrototype = Map.prototype;
9034
+ var SetPrototype = Set.prototype;
9035
+ var IteratorPrototype = ObjectGetPrototypeOf(ObjectGetPrototypeOf([][Symbol.iterator]()));
9036
+ var AsyncIteratorPrototype = ObjectGetPrototypeOf(
9037
+ ObjectGetPrototypeOf(
9038
+ async function* () {
9039
+ }.prototype
9040
+ )
9041
+ );
9042
+ function describeOpaqueContainer(obj) {
9043
+ if (types.isPromise(obj)) return "a Promise";
9044
+ if (types.isWeakMap(obj)) return "a WeakMap";
9045
+ if (types.isGeneratorObject(obj)) return "a generator";
9046
+ if (types.isMapIterator(obj) || types.isSetIterator(obj) || Object.prototype.isPrototypeOf.call(IteratorPrototype, obj) || Object.prototype.isPrototypeOf.call(AsyncIteratorPrototype, obj)) {
9047
+ return "an iterator";
9048
+ }
9049
+ return void 0;
9050
+ }
9051
+ function isPlainDataObject(obj) {
9052
+ const proto = ObjectGetPrototypeOf(obj);
9053
+ return proto === null || proto === Object.prototype || types.isDate(obj) || types.isRegExp(obj) || types.isArrayBufferView(obj) || types.isAnyArrayBuffer(obj);
9054
+ }
9055
+ function describeInstance(obj) {
9056
+ try {
9057
+ const name = ObjectGetPrototypeOf(obj)?.constructor?.name;
9058
+ if (typeof name === "string" && name) return `a ${name} instance`;
9059
+ } catch {
9060
+ }
9061
+ return "a non-plain object";
9062
+ }
9063
+ function collectionError(key, what, path2) {
9064
+ return new Error(
9065
+ `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.`
9066
+ );
9067
+ }
9068
+ function mapValueSegment(mapKey, index) {
9069
+ if (typeof mapKey === "string" || typeof mapKey === "number" || typeof mapKey === "boolean") {
9070
+ return `get(${JSON.stringify(mapKey)})`;
9071
+ }
9072
+ return `values()[${index}]`;
9073
+ }
9074
+ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /* @__PURE__ */ new WeakSet(), collectionVisited = /* @__PURE__ */ new WeakSet(), inCollection = false) {
8291
9075
  const maxDepth = options.maxDepth ?? 10;
8292
9076
  const allowFunctions = options.allowFunctions ?? false;
8293
9077
  const allowGettersSetters = options.allowGettersSetters ?? false;
@@ -8311,6 +9095,9 @@ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /*
8311
9095
  }
8312
9096
  if (type === "function") {
8313
9097
  const funcName = value.name || "anonymous";
9098
+ if (inCollection && (allowFunctions || allowedFunctionNames.includes(funcName))) {
9099
+ throw collectionError(key, "a function", path2);
9100
+ }
8314
9101
  if (allowedFunctionNames.includes(funcName)) {
8315
9102
  return;
8316
9103
  }
@@ -8337,35 +9124,89 @@ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /*
8337
9124
  }
8338
9125
  if (type === "object") {
8339
9126
  const obj = value;
8340
- if (visited.has(obj)) {
9127
+ const seen = inCollection ? collectionVisited : visited;
9128
+ if (seen.has(obj)) {
8341
9129
  return;
8342
9130
  }
8343
- visited.add(obj);
9131
+ seen.add(obj);
9132
+ const opaque = describeOpaqueContainer(obj);
9133
+ if (opaque) {
9134
+ throw new Error(
9135
+ `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.`
9136
+ );
9137
+ }
9138
+ const isArray = Array.isArray(obj);
9139
+ const isMap = types.isMap(obj);
9140
+ const isSet = types.isSet(obj);
9141
+ if (isArray) {
9142
+ const hidden = types.isProxy(obj) ? "a Proxy array" : ObjectGetPrototypeOf(obj) !== ArrayPrototype ? "an array with a custom prototype" : void 0;
9143
+ if (hidden) {
9144
+ throw new Error(
9145
+ `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.`
9146
+ );
9147
+ }
9148
+ }
9149
+ if (inCollection) {
9150
+ if (types.isProxy(obj)) {
9151
+ throw collectionError(key, "a Proxy", path2);
9152
+ }
9153
+ if (!isArray && !isMap && !isSet && !isPlainDataObject(obj)) {
9154
+ throw collectionError(key, describeInstance(obj), path2);
9155
+ }
9156
+ if ((isMap || isSet) && ObjectGetPrototypeOf(obj) !== (isMap ? MapPrototype : SetPrototype)) {
9157
+ throw collectionError(key, describeInstance(obj), path2);
9158
+ }
9159
+ }
8344
9160
  if (!allowGettersSetters) {
8345
- const descriptors = Object.getOwnPropertyDescriptors(obj);
8346
- for (const [prop, desc] of Object.entries(descriptors)) {
8347
- if (desc.get || desc.set) {
9161
+ for (const prop of ReflectOwnKeys(obj)) {
9162
+ const desc = ReflectGetOwnPropertyDescriptor(obj, prop);
9163
+ if (desc && (desc.get || desc.set)) {
9164
+ const at = [...path2, typeof prop === "string" ? prop : `[${String(prop)}]`].join(".");
8348
9165
  throw new Error(
8349
- `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.`
9166
+ `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.`
8350
9167
  );
8351
9168
  }
8352
9169
  }
8353
9170
  }
8354
- if (Array.isArray(obj)) {
8355
- for (let i = 0; i < obj.length; i++) {
8356
- validateGlobalValue(key, obj[i], options, [...path2, String(i)], visited);
9171
+ if (isMap) {
9172
+ let index = 0;
9173
+ for (const [mapKey, mapValue] of ReflectApply(MapEntries, obj, [])) {
9174
+ validateGlobalValue(key, mapKey, options, [...path2, `keys()[${index}]`], visited, collectionVisited, true);
9175
+ validateGlobalValue(
9176
+ key,
9177
+ mapValue,
9178
+ options,
9179
+ [...path2, mapValueSegment(mapKey, index)],
9180
+ visited,
9181
+ collectionVisited,
9182
+ true
9183
+ );
9184
+ index++;
9185
+ }
9186
+ } else if (isSet) {
9187
+ let index = 0;
9188
+ for (const element of ReflectApply(SetValues, obj, [])) {
9189
+ validateGlobalValue(key, element, options, [...path2, `values()[${index}]`], visited, collectionVisited, true);
9190
+ index++;
8357
9191
  }
8358
- return;
8359
9192
  }
8360
- const keys = Object.keys(obj);
9193
+ const keys = isArray || inCollection ? ReflectOwnKeys(obj) : Object.keys(obj);
8361
9194
  for (const prop of keys) {
8362
- if (DANGEROUS_GLOBAL_KEYS.has(prop)) {
9195
+ if (typeof prop === "string" && DANGEROUS_GLOBAL_KEYS.has(prop)) {
8363
9196
  throw new Error(
8364
9197
  `Custom global "${key}" contains dangerous key "${prop}" at ${path2.join(".") || "root"}. Keys like "__proto__", "constructor", and "prototype" are not allowed.`
8365
9198
  );
8366
9199
  }
8367
9200
  const propValue = obj[prop];
8368
- validateGlobalValue(key, propValue, options, [...path2, prop], visited);
9201
+ validateGlobalValue(
9202
+ key,
9203
+ propValue,
9204
+ options,
9205
+ [...path2, typeof prop === "string" ? prop : `[${String(prop)}]`],
9206
+ visited,
9207
+ collectionVisited,
9208
+ inCollection || isArray
9209
+ );
8369
9210
  }
8370
9211
  return;
8371
9212
  }
@@ -10259,6 +11100,8 @@ function createScoringGate(config) {
10259
11100
  }
10260
11101
 
10261
11102
  // libs/core/src/enclave.ts
11103
+ init_global_function_gate();
11104
+ init_stack_trace();
10262
11105
  var DEFAULT_SECURITY_LEVEL = "STANDARD";
10263
11106
  var DEFAULT_TOOL_BRIDGE_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
10264
11107
  function getConfigFromSecurityLevel(securityLevel, options) {
@@ -10313,6 +11156,7 @@ var Enclave = class {
10313
11156
  scoringGate;
10314
11157
  doubleVmConfig;
10315
11158
  customGlobalNames;
11159
+ toolNamespaces;
10316
11160
  adapter;
10317
11161
  constructor(options = {}) {
10318
11162
  this.securityLevel = options.securityLevel ?? DEFAULT_SECURITY_LEVEL;
@@ -10368,6 +11212,12 @@ var Enclave = class {
10368
11212
  }
10369
11213
  };
10370
11214
  }
11215
+ this.toolNamespaces = normalizeToolNamespaces(options.toolNamespaces, {
11216
+ reservedNames: Object.keys(initialGlobals)
11217
+ });
11218
+ if (options.maxGlobalFunctionCalls !== void 0 && !(Number.isInteger(options.maxGlobalFunctionCalls) && options.maxGlobalFunctionCalls >= 0)) {
11219
+ throw new TypeError("maxGlobalFunctionCalls must be a non-negative integer");
11220
+ }
10371
11221
  this.config = {
10372
11222
  ...BASE_CONFIG,
10373
11223
  timeout: securityConfig.timeout,
@@ -10382,9 +11232,13 @@ var Enclave = class {
10382
11232
  toolBridge: normalizedToolBridge,
10383
11233
  // secureProxyConfig must come AFTER options spread to use the merged config
10384
11234
  secureProxyConfig: securityConfig.secureProxyConfig,
10385
- globals: initialGlobals
11235
+ globals: initialGlobals,
11236
+ maxGlobalFunctionCalls: resolveMaxGlobalFunctionCalls({
11237
+ maxToolCalls: securityConfig.maxToolCalls,
11238
+ maxGlobalFunctionCalls: options.maxGlobalFunctionCalls
11239
+ })
10386
11240
  };
10387
- this.customGlobalNames = Object.keys(initialGlobals);
11241
+ this.customGlobalNames = [...Object.keys(initialGlobals), ...this.toolNamespaces.map((ns) => ns.name)];
10388
11242
  const customAllowedGlobals = this.customGlobalNames.flatMap((name) => [name, `__safe_${name}`]);
10389
11243
  this.validator = this.createValidator(presetName, customAllowedGlobals);
10390
11244
  this.validateCode = options.validate !== false;
@@ -10428,11 +11282,31 @@ var Enclave = class {
10428
11282
  /**
10429
11283
  * Execute AgentScript code
10430
11284
  *
11285
+ * Every error returned obeys `sanitizeStackTraces`, whichever stage raised it.
11286
+ *
10431
11287
  * @param code AgentScript code to execute
10432
11288
  * @param toolHandler Optional tool handler (overrides constructor config)
10433
11289
  * @returns Execution result
10434
11290
  */
10435
11291
  async run(code, toolHandler) {
11292
+ const result = await this.execute(code, toolHandler);
11293
+ return this.applyStackTracePolicy(result);
11294
+ }
11295
+ /**
11296
+ * Single exit for returned errors: with `sanitizeStackTraces` on, strip host paths, file
11297
+ * locations and frames from the stack, whichever stage (validation, transform, compile,
11298
+ * execution, tool call) and adapter produced the error.
11299
+ */
11300
+ applyStackTracePolicy(result) {
11301
+ if (result.success || !result.error?.stack || !this.config.sanitizeStackTraces) {
11302
+ return result;
11303
+ }
11304
+ return { ...result, error: { ...result.error, stack: sanitizeStackTrace(result.error.stack, true) } };
11305
+ }
11306
+ /**
11307
+ * Transform, validate and execute. `run` applies the stack-trace policy to what this returns.
11308
+ */
11309
+ async execute(code, toolHandler) {
10436
11310
  const startTime = Date.now();
10437
11311
  const stats = {
10438
11312
  duration: 0,
@@ -10517,7 +11391,8 @@ ${errorMessages}`,
10517
11391
  toolHandler: toolHandler || this.config.toolHandler,
10518
11392
  sidecar,
10519
11393
  referenceConfig: this.referenceConfig,
10520
- secureProxyConfig: this.config.secureProxyConfig
11394
+ secureProxyConfig: this.config.secureProxyConfig,
11395
+ toolNamespaces: this.toolNamespaces
10521
11396
  };
10522
11397
  const timeoutId = setTimeout(() => {
10523
11398
  context.aborted = true;
@@ -11328,7 +12203,11 @@ var Interpreter = class {
11328
12203
  const obj = value ?? {};
11329
12204
  for (const prop of pattern.properties) {
11330
12205
  if (prop.type === "RestElement") continue;
11331
- const key = prop.key.name;
12206
+ if (prop.computed) throw new InterpreterError("Computed destructuring keys are not allowed");
12207
+ let key;
12208
+ if (prop.key.type === "Identifier") key = prop.key.name;
12209
+ else if (prop.key.type === "Literal") key = String(prop.key.value);
12210
+ else throw new InterpreterError("Unsupported destructuring key");
11332
12211
  if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden destructured key: ${key}`);
11333
12212
  this.bindPattern(prop.value, obj[key], scope, mutable);
11334
12213
  }
@@ -11391,6 +12270,7 @@ function applyBinary(op, l, r) {
11391
12270
  }
11392
12271
 
11393
12272
  // libs/core/src/adapters/interpreter-adapter.ts
12273
+ init_stack_trace();
11394
12274
  var SAFE_GLOBALS = Object.freeze({ Math, JSON });
11395
12275
  var DEFAULT_MAX_STEPS = 5e6;
11396
12276
  var DEFAULT_MAX_CALL_DEPTH = 256;
@@ -11401,6 +12281,7 @@ var InterpreterAdapter = class {
11401
12281
  async execute(code, context) {
11402
12282
  const startTime = Date.now();
11403
12283
  let toolCallCount = 0;
12284
+ const sanitizeStacks = context.config.sanitizeStackTraces === true;
11404
12285
  const maxToolCalls = context.config.maxToolCalls ?? Number.POSITIVE_INFINITY;
11405
12286
  const toolHandler = context.toolHandler ?? context.config.toolHandler;
11406
12287
  const __safe_callTool = async (name, args) => {
@@ -11417,7 +12298,7 @@ var InterpreterAdapter = class {
11417
12298
  try {
11418
12299
  program = acorn3.parse(code, { ecmaVersion: "latest", sourceType: "script" });
11419
12300
  } catch (error) {
11420
- return this.fail(error, startTime, toolCallCount, 0, "SyntaxError");
12301
+ return this.fail(error, startTime, toolCallCount, 0, sanitizeStacks, "SyntaxError");
11421
12302
  }
11422
12303
  const timeout = context.config.timeout;
11423
12304
  const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
@@ -11442,6 +12323,7 @@ var InterpreterAdapter = class {
11442
12323
  startTime,
11443
12324
  toolCallCount,
11444
12325
  interpreter.stepCount,
12326
+ sanitizeStacks,
11445
12327
  "TimeoutError",
11446
12328
  "EXECUTION_TIMEOUT"
11447
12329
  );
@@ -11453,7 +12335,7 @@ var InterpreterAdapter = class {
11453
12335
  };
11454
12336
  } catch (error) {
11455
12337
  const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
11456
- return this.fail(error, startTime, toolCallCount, interpreter.stepCount, void 0, code2);
12338
+ return this.fail(error, startTime, toolCallCount, interpreter.stepCount, sanitizeStacks, void 0, code2);
11457
12339
  } finally {
11458
12340
  if (timer) clearTimeout(timer);
11459
12341
  if (timeoutHandle) clearTimeout(timeoutHandle);
@@ -11465,12 +12347,13 @@ var InterpreterAdapter = class {
11465
12347
  const endTime = Date.now();
11466
12348
  return { duration: endTime - startTime, toolCallCount, iterationCount, startTime, endTime };
11467
12349
  }
11468
- fail(error, startTime, toolCallCount, iterationCount, name, code) {
12350
+ fail(error, startTime, toolCallCount, iterationCount, sanitizeStacks, name, code) {
11469
12351
  const err = error instanceof Error ? error : new Error(String(error));
12352
+ const stack = sanitizeStackTrace(err.stack, sanitizeStacks);
11470
12353
  const execError = {
11471
12354
  message: err.message,
11472
12355
  name: name ?? err.name,
11473
- ...err.stack ? { stack: err.stack } : {},
12356
+ ...stack ? { stack } : {},
11474
12357
  ...code ? { code } : {}
11475
12358
  };
11476
12359
  return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };