@enclave-vm/core 2.15.2 → 2.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -31,9 +31,17 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
33
  // libs/core/src/safe-error.ts
34
- function createSafeError(message, name = "Error") {
34
+ function createSafeError(message, name = "Error", code) {
35
35
  const error = new Error(message);
36
36
  error.name = name;
37
+ if (typeof code === "string") {
38
+ Object.defineProperty(error, "code", {
39
+ value: code,
40
+ writable: false,
41
+ enumerable: false,
42
+ configurable: false
43
+ });
44
+ }
37
45
  const SafeConstructor = /* @__PURE__ */ Object.create(null);
38
46
  Object.defineProperties(SafeConstructor, {
39
47
  constructor: {
@@ -176,6 +184,14 @@ function createSafeReflect(securityLevel) {
176
184
  }
177
185
  });
178
186
  }
187
+ function gatedProxyCache(gate) {
188
+ let cache = gatedProxyCaches.get(gate);
189
+ if (!cache) {
190
+ cache = /* @__PURE__ */ new WeakMap();
191
+ gatedProxyCaches.set(gate, cache);
192
+ }
193
+ return cache;
194
+ }
179
195
  function getFullCacheKey(options) {
180
196
  const parts = [];
181
197
  if (options.levelConfig) {
@@ -201,7 +217,7 @@ function getFullCacheKey(options) {
201
217
  function isProxyable(value) {
202
218
  if (value === null) return false;
203
219
  if (typeof value !== "object" && typeof value !== "function") return false;
204
- const tag = ReflectApply(ObjectToString, value, []);
220
+ const tag = ReflectApply2(ObjectToString, value, []);
205
221
  if (NON_PROXYABLE_TYPES.has(tag)) {
206
222
  return false;
207
223
  }
@@ -212,12 +228,11 @@ function createSecureProxy(target, options = {}) {
212
228
  return target;
213
229
  }
214
230
  const cacheKey = getFullCacheKey(options);
215
- const targetCache = proxyCache.get(target);
216
- if (targetCache) {
217
- const cached = targetCache.get(cacheKey);
218
- if (cached) {
219
- return cached;
220
- }
231
+ const gateCache = options.callGate ? gatedProxyCache(options.callGate) : void 0;
232
+ const lookupCached = (obj) => gateCache ? gateCache.get(obj) : proxyCache.get(obj)?.get(cacheKey);
233
+ const cached = lookupCached(target);
234
+ if (cached) {
235
+ return cached;
221
236
  }
222
237
  const baseBlocked = options.levelConfig ? buildBlockedPropertiesFromConfig(options.levelConfig) : new Set(BLOCKED_PROPERTIES);
223
238
  const blockedSet = /* @__PURE__ */ new Set([...baseBlocked, ...options.additionalBlocked || []]);
@@ -228,12 +243,9 @@ function createSecureProxy(target, options = {}) {
228
243
  if (!isProxyable(obj)) {
229
244
  return obj;
230
245
  }
231
- const objCache = proxyCache.get(obj);
232
- if (objCache) {
233
- const cachedProxy = objCache.get(cacheKey);
234
- if (cachedProxy) {
235
- return cachedProxy;
236
- }
246
+ const cachedProxy = lookupCached(obj);
247
+ if (cachedProxy) {
248
+ return cachedProxy;
237
249
  }
238
250
  if (depth > maxDepth) {
239
251
  throw createSafeError(
@@ -281,9 +293,9 @@ function createSecureProxy(target, options = {}) {
281
293
  }
282
294
  const value = ReflectGet(target2, property, receiver);
283
295
  if (typeof value === "function") {
284
- const tag = ReflectApply(ObjectToString, target2, []);
296
+ const tag = ReflectApply2(ObjectToString, target2, []);
285
297
  if (INTERNAL_SLOT_TYPES.has(tag)) {
286
- const boundMethod = ReflectApply(FunctionBind, value, [target2]);
298
+ const boundMethod = ReflectApply2(FunctionBind, value, [target2]);
287
299
  return proxyWithDepth(boundMethod, depth + 1);
288
300
  }
289
301
  }
@@ -329,7 +341,7 @@ function createSecureProxy(target, options = {}) {
329
341
  // Filter blocked property names from enumeration (Object.keys, Object.entries, etc.)
330
342
  // Must respect proxy invariants: non-configurable own properties cannot be hidden
331
343
  ownKeys(target2) {
332
- const keys = ReflectOwnKeys(target2);
344
+ const keys = ReflectOwnKeys2(target2);
333
345
  return keys.filter((key) => {
334
346
  const keyStr = typeof key === "symbol" ? key.toString() : key;
335
347
  if (typeof keyStr !== "string" || !blockedSet.has(keyStr)) {
@@ -346,7 +358,7 @@ function createSecureProxy(target, options = {}) {
346
358
  // Must respect proxy invariants: non-configurable properties must return actual descriptor
347
359
  getOwnPropertyDescriptor(target2, property) {
348
360
  const propName = typeof property === "symbol" ? property.toString() : property;
349
- const descriptor = ReflectGetOwnPropertyDescriptor(target2, property);
361
+ const descriptor = ReflectGetOwnPropertyDescriptor2(target2, property);
350
362
  if (descriptor && !descriptor.configurable && descriptor.writable === false && "value" in descriptor) {
351
363
  const exactValue = descriptor.value;
352
364
  if (exactValue !== null && (typeof exactValue === "object" || typeof exactValue === "function")) {
@@ -405,7 +417,10 @@ function createSecureProxy(target, options = {}) {
405
417
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
406
418
  apply(target2, thisArg, argArray) {
407
419
  const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
408
- const result = ReflectApply(target2, unwrappedThis, argArray);
420
+ if (options.callGate && options.callGate.gates(target2)) {
421
+ return options.callGate.call(target2, unwrappedThis, argArray);
422
+ }
423
+ const result = ReflectApply2(target2, unwrappedThis, argArray);
409
424
  if (isProxyable(result)) {
410
425
  return proxyWithDepth(result, depth + 1);
411
426
  }
@@ -416,6 +431,9 @@ function createSecureProxy(target, options = {}) {
416
431
  // host Function constructor — the same escape class the apply trap closes for calls.
417
432
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
418
433
  construct(target2, argArray, newTarget) {
434
+ if (options.callGate && options.callGate.gates(target2)) {
435
+ throw createSafeError("Host functions cannot be called with new", "TypeError");
436
+ }
419
437
  const instance = ReflectConstruct(target2, argArray, newTarget === proxy ? target2 : newTarget);
420
438
  if (isProxyable(instance)) {
421
439
  return proxyWithDepth(instance, depth + 1);
@@ -423,12 +441,16 @@ function createSecureProxy(target, options = {}) {
423
441
  return instance;
424
442
  }
425
443
  });
426
- let objCacheMap = proxyCache.get(obj);
427
- if (!objCacheMap) {
428
- objCacheMap = /* @__PURE__ */ new Map();
429
- proxyCache.set(obj, objCacheMap);
444
+ if (gateCache) {
445
+ gateCache.set(obj, proxy);
446
+ } else {
447
+ let objCacheMap = proxyCache.get(obj);
448
+ if (!objCacheMap) {
449
+ objCacheMap = /* @__PURE__ */ new Map();
450
+ proxyCache.set(obj, objCacheMap);
451
+ }
452
+ objCacheMap.set(cacheKey, proxy);
430
453
  }
431
- objCacheMap.set(cacheKey, proxy);
432
454
  proxySet.add(proxy);
433
455
  proxyToTarget.set(proxy, obj);
434
456
  return proxy;
@@ -470,7 +492,16 @@ function isSecureProxy(obj) {
470
492
  }
471
493
  return proxySet.has(obj);
472
494
  }
473
- var ObjectGetOwnPropertyDescriptor, ObjectToString, FunctionBind, ReflectGet, ReflectSet, ReflectDefineProperty, ReflectGetOwnPropertyDescriptor, ReflectOwnKeys, ReflectApply, 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, proxyCache, proxySet, proxyToTarget, NON_PROXYABLE_TYPES, INTERNAL_SLOT_TYPES;
495
+ function unwrapSecureProxy(value) {
496
+ let current = value;
497
+ while (current !== null && (typeof current === "object" || typeof current === "function")) {
498
+ const target = proxyToTarget.get(current);
499
+ if (target === void 0) break;
500
+ current = target;
501
+ }
502
+ return current;
503
+ }
504
+ 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;
474
505
  var init_secure_proxy = __esm({
475
506
  "libs/core/src/secure-proxy.ts"() {
476
507
  "use strict";
@@ -481,13 +512,13 @@ var init_secure_proxy = __esm({
481
512
  ReflectGet = Reflect.get;
482
513
  ReflectSet = Reflect.set;
483
514
  ReflectDefineProperty = Reflect.defineProperty;
484
- ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
485
- ReflectOwnKeys = Reflect.ownKeys;
486
- ReflectApply = Reflect.apply;
515
+ ReflectGetOwnPropertyDescriptor2 = Reflect.getOwnPropertyDescriptor;
516
+ ReflectOwnKeys2 = Reflect.ownKeys;
517
+ ReflectApply2 = Reflect.apply;
487
518
  ReflectConstruct = Reflect.construct;
488
519
  ReflectObject = Reflect;
489
520
  PINNED_REFLECT_VALUES = /* @__PURE__ */ new Map();
490
- for (const key of ReflectOwnKeys(ReflectObject)) {
521
+ for (const key of ReflectOwnKeys2(ReflectObject)) {
491
522
  PINNED_REFLECT_VALUES.set(key, ReflectGet(ReflectObject, key));
492
523
  }
493
524
  FunctionCtor = Function;
@@ -596,6 +627,7 @@ var init_secure_proxy = __esm({
596
627
  // 'call',
597
628
  // 'apply',
598
629
  ]);
630
+ gatedProxyCaches = /* @__PURE__ */ new WeakMap();
599
631
  proxyCache = /* @__PURE__ */ new WeakMap();
600
632
  proxySet = /* @__PURE__ */ new WeakSet();
601
633
  proxyToTarget = /* @__PURE__ */ new WeakMap();
@@ -1012,6 +1044,26 @@ var init_reference_resolver = __esm({
1012
1044
  });
1013
1045
 
1014
1046
  // libs/core/src/value-sanitizer.ts
1047
+ function hasBrand(builtin, value) {
1048
+ if (!builtin) return false;
1049
+ try {
1050
+ ReflectApply3(builtin, value, []);
1051
+ return true;
1052
+ } catch {
1053
+ return false;
1054
+ }
1055
+ }
1056
+ function regExpToString(value) {
1057
+ let flags = "";
1058
+ for (const [flag, getter] of RegExpFlagGetters) {
1059
+ if (getter && ReflectApply3(getter, value, [])) flags += flag;
1060
+ }
1061
+ return `/${ReflectApply3(RegExpProtoSourceGetter, value, [])}/${flags}`;
1062
+ }
1063
+ function isPlainObject(value) {
1064
+ const prototype = ObjectGetPrototypeOf2(value);
1065
+ return prototype === null || ObjectGetPrototypeOf2(prototype) === null;
1066
+ }
1015
1067
  function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
1016
1068
  const maxDepth = options.maxDepth ?? 20;
1017
1069
  const maxProperties = options.maxProperties ?? 1e4;
@@ -1072,12 +1124,14 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1072
1124
  }
1073
1125
  return result;
1074
1126
  }
1075
- if (value instanceof Date) {
1076
- const time = ReflectApply2(DateProtoGetTime, value, []);
1127
+ const inspected = options.unwrap ? options.unwrap(value) : value;
1128
+ const isPlain = isPlainObject(inspected);
1129
+ if (!isPlain && hasBrand(DateProtoGetTime, inspected)) {
1130
+ const time = ReflectApply3(DateProtoGetTime, inspected, []);
1077
1131
  if (allowDates) {
1078
1132
  return new Date(time);
1079
1133
  }
1080
- return ReflectApply2(DateProtoToISOString, value, []);
1134
+ return ReflectApply3(DateProtoToISOString, inspected, []);
1081
1135
  }
1082
1136
  if (value instanceof Error) {
1083
1137
  const rawName = ReflectGet3(value, "name");
@@ -1093,12 +1147,12 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1093
1147
  }
1094
1148
  return { error: message };
1095
1149
  }
1096
- if (value instanceof RegExp) {
1097
- return ReflectApply2(RegExpProtoToString, value, []);
1150
+ if (!isPlain && hasBrand(RegExpProtoSourceGetter, inspected)) {
1151
+ return regExpToString(inspected);
1098
1152
  }
1099
- if (value instanceof Map) {
1153
+ if (!isPlain && hasBrand(MapProtoSizeGetter, inspected)) {
1100
1154
  const sanitizedMap = ObjectCreate(null);
1101
- const entries = ReflectApply2(MapProtoEntries, value, []);
1155
+ const entries = ReflectApply3(MapProtoEntries, inspected, []);
1102
1156
  for (const [key, val] of entries) {
1103
1157
  if (typeof key !== "string") continue;
1104
1158
  if (DANGEROUS_KEYS.has(key)) continue;
@@ -1107,8 +1161,8 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1107
1161
  }
1108
1162
  return sanitizedMap;
1109
1163
  }
1110
- if (value instanceof Set) {
1111
- const iter = ReflectApply2(SetProtoValues, value, []);
1164
+ if (!isPlain && hasBrand(SetProtoSizeGetter, inspected)) {
1165
+ const iter = ReflectApply3(SetProtoValues, inspected, []);
1112
1166
  const result = [];
1113
1167
  for (const item of iter) {
1114
1168
  context.propCount.count++;
@@ -1267,23 +1321,420 @@ function checkSerializedSize(value, maxBytes) {
1267
1321
  return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
1268
1322
  }
1269
1323
  }
1270
- var DANGEROUS_KEYS, ReflectApply2, ReflectGet3, ArrayIsArray, ObjectKeys, ObjectCreate, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoToString;
1324
+ var DANGEROUS_KEYS, ReflectApply3, ReflectGet3, ArrayIsArray, ObjectKeys, ObjectCreate, ObjectGetPrototypeOf2, NumberIsFinite2, MathFloor2, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoSourceGetter, RegExpFlagGetters, MapProtoSizeGetter, SetProtoSizeGetter;
1271
1325
  var init_value_sanitizer = __esm({
1272
1326
  "libs/core/src/value-sanitizer.ts"() {
1273
1327
  "use strict";
1274
1328
  DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
1275
- ReflectApply2 = Reflect.apply;
1329
+ ReflectApply3 = Reflect.apply;
1276
1330
  ReflectGet3 = Reflect.get;
1277
1331
  ArrayIsArray = Array.isArray;
1278
1332
  ObjectKeys = Object.keys;
1279
1333
  ObjectCreate = Object.create;
1334
+ ObjectGetPrototypeOf2 = Object.getPrototypeOf;
1280
1335
  NumberIsFinite2 = Number.isFinite;
1281
1336
  MathFloor2 = Math.floor;
1282
1337
  MapProtoEntries = Map.prototype.entries;
1283
1338
  SetProtoValues = Set.prototype.values;
1284
1339
  DateProtoGetTime = Date.prototype.getTime;
1285
1340
  DateProtoToISOString = Date.prototype.toISOString;
1286
- RegExpProtoToString = RegExp.prototype.toString;
1341
+ RegExpProtoSourceGetter = Object.getOwnPropertyDescriptor(RegExp.prototype, "source")?.get;
1342
+ RegExpFlagGetters = [
1343
+ ["d", "hasIndices"],
1344
+ ["g", "global"],
1345
+ ["i", "ignoreCase"],
1346
+ ["m", "multiline"],
1347
+ ["s", "dotAll"],
1348
+ ["u", "unicode"],
1349
+ ["v", "unicodeSets"],
1350
+ ["y", "sticky"]
1351
+ ].map(([flag, property]) => [flag, Object.getOwnPropertyDescriptor(RegExp.prototype, property)?.get]);
1352
+ MapProtoSizeGetter = Object.getOwnPropertyDescriptor(Map.prototype, "size")?.get;
1353
+ SetProtoSizeGetter = Object.getOwnPropertyDescriptor(Set.prototype, "size")?.get;
1354
+ }
1355
+ });
1356
+
1357
+ // libs/core/src/global-function-gate.ts
1358
+ function isBuiltinMethod(fn) {
1359
+ return (typeof fn === "function" || typeof fn === "object" && fn !== null) && BUILTIN_METHODS.has(fn);
1360
+ }
1361
+ function resolveMaxGlobalFunctionCalls(config) {
1362
+ const explicit = config.maxGlobalFunctionCalls;
1363
+ if (typeof explicit === "number" && Number.isFinite(explicit) && explicit >= 0) {
1364
+ return Math.floor(explicit);
1365
+ }
1366
+ const maxToolCalls = typeof config.maxToolCalls === "number" && Number.isFinite(config.maxToolCalls) ? config.maxToolCalls : 100;
1367
+ return Math.max(0, Math.floor(maxToolCalls)) * DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL;
1368
+ }
1369
+ function globalFunctionLimitMessage(max) {
1370
+ return `Maximum global function call limit exceeded (${max}). This limit prevents runaway calls into host functions.`;
1371
+ }
1372
+ function resultLimits(context) {
1373
+ const { config } = context;
1374
+ return {
1375
+ maxDepth: config.maxSanitizeDepth,
1376
+ maxProperties: config.maxSanitizeProperties,
1377
+ maxPayloadBytes: config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_PAYLOAD_BYTES
1378
+ };
1379
+ }
1380
+ function truncate(value, max) {
1381
+ return value.length <= max ? value : `${value.slice(0, max)}\u2026`;
1382
+ }
1383
+ function failure(error) {
1384
+ let name = "Error";
1385
+ let message = "Global function call failed";
1386
+ try {
1387
+ if (error && typeof error === "object") {
1388
+ const rawName = error.name;
1389
+ const rawMessage = error.message;
1390
+ if (typeof rawName === "string" && rawName) name = rawName;
1391
+ if (typeof rawMessage === "string" && rawMessage) message = rawMessage;
1392
+ } else if (typeof error === "string" && error) {
1393
+ message = error;
1394
+ }
1395
+ } catch {
1396
+ }
1397
+ return {
1398
+ ok: false,
1399
+ name: truncate(name, MAX_ERROR_NAME_LENGTH),
1400
+ message: truncate(message, MAX_ERROR_MESSAGE_LENGTH)
1401
+ };
1402
+ }
1403
+ function jsonReplacer(_key, value) {
1404
+ if (typeof value === "bigint") return value.toString();
1405
+ if (typeof value === "number" && !Number.isFinite(value)) return null;
1406
+ return value;
1407
+ }
1408
+ function utf8ByteLength(value) {
1409
+ return Buffer.byteLength(value, "utf8");
1410
+ }
1411
+ function encodeResult(value, limits) {
1412
+ if (value === void 0) return { ok: true };
1413
+ let json;
1414
+ try {
1415
+ const sanitized = sanitizeValue(value, {
1416
+ maxDepth: limits.maxDepth,
1417
+ maxProperties: limits.maxProperties,
1418
+ allowDates: false,
1419
+ allowErrors: true
1420
+ });
1421
+ json = JsonStringify(sanitized, jsonReplacer);
1422
+ } catch {
1423
+ return { ok: false, name: "GlobalFunctionError", message: UNSAFE_RESULT_MESSAGE };
1424
+ }
1425
+ if (json === void 0) return { ok: true };
1426
+ if (utf8ByteLength(json) > limits.maxPayloadBytes) {
1427
+ return {
1428
+ ok: false,
1429
+ name: "GlobalFunctionError",
1430
+ message: `Global function result exceeds maximum size (${limits.maxPayloadBytes} bytes)`
1431
+ };
1432
+ }
1433
+ return { ok: true, json };
1434
+ }
1435
+ function isThenable(value) {
1436
+ if (value === null || typeof value !== "object" && typeof value !== "function") return false;
1437
+ try {
1438
+ return typeof value.then === "function";
1439
+ } catch {
1440
+ return false;
1441
+ }
1442
+ }
1443
+ function invokeGlobalFunction(fn, thisArg, args, limits) {
1444
+ if (typeof fn !== "function") {
1445
+ return { ok: false, name: "TypeError", message: "Global is not a function" };
1446
+ }
1447
+ let result;
1448
+ try {
1449
+ result = ReflectApply4(fn, thisArg, ArrayIsArray2(args) ? args : []);
1450
+ } catch (error) {
1451
+ return failure(error);
1452
+ }
1453
+ if (isThenable(result)) {
1454
+ return Promise.resolve(result).then(
1455
+ (value) => encodeResult(value, limits),
1456
+ (error) => failure(error)
1457
+ );
1458
+ }
1459
+ return encodeResult(result, limits);
1460
+ }
1461
+ function toEnvelope(outcome) {
1462
+ if (outcome.ok) {
1463
+ return outcome.json === void 0 ? '{"v":1,"ok":true}' : `{"v":1,"ok":true,"value":${outcome.json}}`;
1464
+ }
1465
+ return JsonStringify({ v: 1, ok: false, error: { name: outcome.name, message: outcome.message } });
1466
+ }
1467
+ function createHostGlobalFunctionInvoker(context) {
1468
+ const limits = resultLimits(context);
1469
+ return (fn, thisArg, args) => {
1470
+ const outcome = invokeGlobalFunction(fn, thisArg, args, limits);
1471
+ return outcome instanceof Promise ? outcome.then(toEnvelope) : toEnvelope(outcome);
1472
+ };
1473
+ }
1474
+ function createGlobalFunctionGate(context, realm) {
1475
+ const limits = resultLimits(context);
1476
+ const max = resolveMaxGlobalFunctionCalls(context.config);
1477
+ let calls = 0;
1478
+ const settle = (outcome) => {
1479
+ if (!outcome.ok) {
1480
+ throw createSafeError(outcome.message, outcome.name);
1481
+ }
1482
+ return outcome.json === void 0 ? void 0 : realm.parseJson(outcome.json);
1483
+ };
1484
+ return {
1485
+ gates: (target) => !isBuiltinMethod(target),
1486
+ call: (target, thisArg, args) => {
1487
+ if (context.aborted) {
1488
+ throw createSafeError("Execution aborted");
1489
+ }
1490
+ calls++;
1491
+ if (calls > max) {
1492
+ throw createSafeError(globalFunctionLimitMessage(max));
1493
+ }
1494
+ const outcome = invokeGlobalFunction(target, thisArg, args, limits);
1495
+ if (outcome instanceof Promise) {
1496
+ return realm.adoptPromise(outcome.then(settle));
1497
+ }
1498
+ return settle(outcome);
1499
+ }
1500
+ };
1501
+ }
1502
+ var ReflectApply4, ReflectOwnKeys3, ObjectGetOwnPropertyDescriptor2, ObjectGetPrototypeOf3, 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;
1503
+ var init_global_function_gate = __esm({
1504
+ "libs/core/src/global-function-gate.ts"() {
1505
+ "use strict";
1506
+ init_value_sanitizer();
1507
+ init_safe_error();
1508
+ ReflectApply4 = Reflect.apply;
1509
+ ReflectOwnKeys3 = Reflect.ownKeys;
1510
+ ObjectGetOwnPropertyDescriptor2 = Object.getOwnPropertyDescriptor;
1511
+ ObjectGetPrototypeOf3 = Object.getPrototypeOf;
1512
+ ArrayIsArray2 = Array.isArray;
1513
+ JsonStringify = JSON.stringify;
1514
+ BUILTIN_METHODS = (() => {
1515
+ const methods = /* @__PURE__ */ new WeakSet();
1516
+ const typedArrays = [
1517
+ Int8Array,
1518
+ Uint8Array,
1519
+ Uint8ClampedArray,
1520
+ Int16Array,
1521
+ Uint16Array,
1522
+ Int32Array,
1523
+ Uint32Array,
1524
+ Float32Array,
1525
+ Float64Array,
1526
+ BigInt64Array,
1527
+ BigUint64Array
1528
+ ];
1529
+ const arrayIteratorPrototype = ObjectGetPrototypeOf3([][Symbol.iterator]());
1530
+ const prototypes = [
1531
+ Object.prototype,
1532
+ Array.prototype,
1533
+ String.prototype,
1534
+ Number.prototype,
1535
+ Boolean.prototype,
1536
+ Symbol.prototype,
1537
+ BigInt.prototype,
1538
+ Date.prototype,
1539
+ RegExp.prototype,
1540
+ Error.prototype,
1541
+ EvalError.prototype,
1542
+ RangeError.prototype,
1543
+ ReferenceError.prototype,
1544
+ SyntaxError.prototype,
1545
+ TypeError.prototype,
1546
+ URIError.prototype,
1547
+ Map.prototype,
1548
+ Set.prototype,
1549
+ WeakMap.prototype,
1550
+ WeakSet.prototype,
1551
+ Promise.prototype,
1552
+ ArrayBuffer.prototype,
1553
+ DataView.prototype,
1554
+ ObjectGetPrototypeOf3(Uint8Array.prototype),
1555
+ // %TypedArray%.prototype
1556
+ ...typedArrays.map((TypedArray) => TypedArray.prototype),
1557
+ arrayIteratorPrototype,
1558
+ ObjectGetPrototypeOf3(arrayIteratorPrototype),
1559
+ // %IteratorPrototype%
1560
+ ObjectGetPrototypeOf3((/* @__PURE__ */ new Map())[Symbol.iterator]()),
1561
+ ObjectGetPrototypeOf3((/* @__PURE__ */ new Set())[Symbol.iterator]()),
1562
+ ObjectGetPrototypeOf3(""[Symbol.iterator]())
1563
+ ];
1564
+ for (const prototype of prototypes) {
1565
+ if (prototype === null || typeof prototype !== "object") continue;
1566
+ for (const key of ReflectOwnKeys3(prototype)) {
1567
+ if (key === "constructor") continue;
1568
+ const descriptor = ObjectGetOwnPropertyDescriptor2(prototype, key);
1569
+ if (descriptor && typeof descriptor.value === "function") {
1570
+ methods.add(descriptor.value);
1571
+ }
1572
+ }
1573
+ }
1574
+ return methods;
1575
+ })();
1576
+ DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL = 10;
1577
+ DEFAULT_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
1578
+ MAX_ERROR_MESSAGE_LENGTH = 4096;
1579
+ MAX_ERROR_NAME_LENGTH = 128;
1580
+ 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)";
1581
+ }
1582
+ });
1583
+
1584
+ // libs/core/src/stack-trace.ts
1585
+ function redactLine(line) {
1586
+ let out = line.length > MAX_LINE_LENGTH ? `${line.slice(0, MAX_LINE_LENGTH)}\u2026` : line;
1587
+ for (const pattern of SENSITIVE_STACK_PATTERNS) {
1588
+ pattern.lastIndex = 0;
1589
+ out = out.replace(pattern, "[REDACTED]");
1590
+ }
1591
+ return out;
1592
+ }
1593
+ function sanitizeStackTrace(stack, sanitize = true) {
1594
+ if (typeof stack !== "string" || !stack || !sanitize) return stack;
1595
+ const bounded = stack.length > MAX_STACK_LENGTH ? stack.slice(0, MAX_STACK_LENGTH) : stack;
1596
+ return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
1597
+ }
1598
+ var SENSITIVE_STACK_PATTERNS, FRAME_LINE, MAX_STACK_LENGTH, MAX_LINE_LENGTH, REDACTED_FRAME;
1599
+ var init_stack_trace = __esm({
1600
+ "libs/core/src/stack-trace.ts"() {
1601
+ "use strict";
1602
+ SENSITIVE_STACK_PATTERNS = [
1603
+ // Unix file system paths
1604
+ /\/Users\/[^/]+\/[^\s):]*/gi,
1605
+ // macOS home directories
1606
+ /\/home\/[^/]+\/[^\s):]*/gi,
1607
+ // Linux home directories
1608
+ /\/var\/[^\s):]*/gi,
1609
+ // System var directories
1610
+ /\/opt\/[^\s):]*/gi,
1611
+ // Optional software
1612
+ /\/tmp\/[^\s):]*/gi,
1613
+ // Temporary files
1614
+ /\/etc\/[^\s):]*/gi,
1615
+ // System configuration
1616
+ /\/root\/[^\s):]*/gi,
1617
+ // Root home directory
1618
+ /\/mnt\/[^\s):]*/gi,
1619
+ // Mount points
1620
+ /\/srv\/[^\s):]*/gi,
1621
+ // Service data
1622
+ /\/data\/[^\s):]*/gi,
1623
+ // Data directories
1624
+ /\/app\/[^\s):]*/gi,
1625
+ // Application directories
1626
+ /\/proc\/[^\s):]*/gi,
1627
+ // Process information
1628
+ /\/sys\/[^\s):]*/gi,
1629
+ // System files
1630
+ // Windows paths
1631
+ /\\\\[^\s):]*/g,
1632
+ // UNC paths
1633
+ /[A-Z]:\\[^\s):]+/gi,
1634
+ // Windows drive paths
1635
+ // URL-based paths
1636
+ /file:\/\/[^\s):]+/gi,
1637
+ // File URLs
1638
+ /webpack:\/\/[^\s):]+/gi,
1639
+ // Webpack paths
1640
+ /%2F[^\s):]+/gi,
1641
+ // URL-encoded paths
1642
+ // Package managers and node
1643
+ /node_modules\/[^\s):]+/gi,
1644
+ // Node modules paths
1645
+ /\/nix\/store\/[^\s):]*/gi,
1646
+ // Nix store paths
1647
+ /\.npm\/[^\s):]*/gi,
1648
+ // NPM cache
1649
+ /\.yarn\/[^\s):]*/gi,
1650
+ // Yarn cache
1651
+ /\.pnpm\/[^\s):]*/gi,
1652
+ // PNPM cache
1653
+ // Container and orchestration
1654
+ /\/run\/secrets\/[^\s):]*/gi,
1655
+ // Docker/K8s secrets
1656
+ /\/var\/run\/[^\s):]*/gi,
1657
+ // Runtime directories
1658
+ /\/docker\/[^\s):]*/gi,
1659
+ // Docker paths
1660
+ /\/containers\/[^\s):]*/gi,
1661
+ // Container paths
1662
+ /\/kubelet\/[^\s):]*/gi,
1663
+ // Kubernetes kubelet
1664
+ // CI/CD systems
1665
+ /\/github\/workspace\/[^\s):]*/gi,
1666
+ // GitHub Actions
1667
+ /\/runner\/[^\s):]*/gi,
1668
+ // GitHub/GitLab runner
1669
+ /\/builds\/[^\s):]*/gi,
1670
+ // CI builds
1671
+ /\/workspace\/[^\s):]*/gi,
1672
+ // Generic workspace
1673
+ /\/pipeline\/[^\s):]*/gi,
1674
+ // CI pipelines
1675
+ /\/jenkins\/[^\s):]*/gi,
1676
+ // Jenkins
1677
+ /\/bamboo\/[^\s):]*/gi,
1678
+ // Bamboo
1679
+ /\/teamcity\/[^\s):]*/gi,
1680
+ // TeamCity
1681
+ /\/circleci\/[^\s):]*/gi,
1682
+ // CircleCI
1683
+ // Cloud providers
1684
+ /\/aws\/[^\s):]*/gi,
1685
+ // AWS paths
1686
+ /\/gcloud\/[^\s):]*/gi,
1687
+ // Google Cloud
1688
+ /\/azure\/[^\s):]*/gi,
1689
+ // Azure paths
1690
+ /s3:\/\/[^\s):]+/gi,
1691
+ // S3 URIs
1692
+ /gs:\/\/[^\s):]+/gi,
1693
+ // GCS URIs
1694
+ // Secrets and credentials (patterns that might appear in paths or errors)
1695
+ /[A-Z0-9]{20,}/g,
1696
+ // AWS-style access keys (20+ uppercase chars)
1697
+ /sk-[a-zA-Z0-9]{32,}/g,
1698
+ // OpenAI/Stripe-style secret keys
1699
+ /ghp_[a-zA-Z0-9]{36,}/g,
1700
+ // GitHub personal access tokens
1701
+ /gho_[a-zA-Z0-9]{36,}/g,
1702
+ // GitHub OAuth tokens
1703
+ /github_pat_[a-zA-Z0-9_]{22,}/g,
1704
+ // GitHub fine-grained tokens
1705
+ /xox[baprs]-[a-zA-Z0-9-]+/g,
1706
+ // Slack tokens
1707
+ /Bearer\s+[a-zA-Z0-9._-]+/gi,
1708
+ // Bearer tokens
1709
+ /Basic\s+[a-zA-Z0-9+/=]+/gi,
1710
+ // Basic auth
1711
+ // Internal network info
1712
+ /(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
1713
+ // Private IPs
1714
+ /[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
1715
+ // Internal hostnames
1716
+ /localhost:\d+/gi,
1717
+ // Localhost with port
1718
+ /127\.0\.0\.1:\d+/gi,
1719
+ // Loopback with port
1720
+ // User information
1721
+ /\/u\/[^/]+\//gi,
1722
+ // User subdirectories
1723
+ /~[a-z_][a-z0-9_-]*/gi,
1724
+ // Unix user home shorthand
1725
+ // Anything else that is still shaped like a location: an absolute path of two or more
1726
+ // segments, a URL, or a script location such as `agentscript.js:3` / `index.mjs:10:5`.
1727
+ /[a-z][a-z0-9+.-]*:\/\/[^\s)]+/gi,
1728
+ // Other URLs (http://host/bundle.js:1:2)
1729
+ /(?:\/[\w.@%+-]+){2,}\/?/g,
1730
+ // Remaining absolute paths
1731
+ /[\w.@-]+\.(?:[cm]?[jt]sx?|json|node|wasm)(?::\d+){1,2}/gi
1732
+ // file.ext:line[:column]
1733
+ ];
1734
+ FRAME_LINE = /^\s*at\s/;
1735
+ MAX_STACK_LENGTH = 16 * 1024;
1736
+ MAX_LINE_LENGTH = 1e3;
1737
+ REDACTED_FRAME = " at [REDACTED]";
1287
1738
  }
1288
1739
  });
1289
1740
 
@@ -1442,16 +1893,16 @@ var init_memory_tracker = __esm({
1442
1893
  });
1443
1894
 
1444
1895
  // libs/core/src/tool-bridge.ts
1445
- function utf8ByteLength(value) {
1896
+ function utf8ByteLength2(value) {
1446
1897
  return Buffer.byteLength(value, "utf8");
1447
1898
  }
1448
- function jsonReplacer(_key, value) {
1899
+ function jsonReplacer2(_key, value) {
1449
1900
  if (typeof value === "bigint") return value.toString();
1450
1901
  if (typeof value === "number" && !Number.isFinite(value)) return null;
1451
1902
  return value;
1452
1903
  }
1453
1904
  function safeJsonStringify(value) {
1454
- return JSON.stringify(value, jsonReplacer);
1905
+ return JSON.stringify(value, jsonReplacer2);
1455
1906
  }
1456
1907
  function truncateForErrorMessage(value, maxChars) {
1457
1908
  if (value.length <= maxChars) return value;
@@ -1492,7 +1943,7 @@ function serializeResponse(response, maxPayloadBytes) {
1492
1943
  }
1493
1944
  });
1494
1945
  }
1495
- if (utf8ByteLength(json) <= maxPayloadBytes) return json;
1946
+ if (utf8ByteLength2(json) <= maxPayloadBytes) return json;
1496
1947
  const minimal = {
1497
1948
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
1498
1949
  ok: false,
@@ -1548,7 +1999,7 @@ function createHostToolBridge(executionContext, options) {
1548
1999
  maxPayloadBytes
1549
2000
  );
1550
2001
  }
1551
- if (utf8ByteLength(requestJson) > maxPayloadBytes) {
2002
+ if (utf8ByteLength2(requestJson) > maxPayloadBytes) {
1552
2003
  return serializeResponse(
1553
2004
  {
1554
2005
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -1689,7 +2140,7 @@ function createHostToolBridge(executionContext, options) {
1689
2140
  {
1690
2141
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
1691
2142
  ok: false,
1692
- error: safeError
2143
+ error: { ...safeError, toolError: true }
1693
2144
  },
1694
2145
  maxPayloadBytes
1695
2146
  );
@@ -1713,13 +2164,13 @@ function createHostToolBridge(executionContext, options) {
1713
2164
  {
1714
2165
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
1715
2166
  ok: false,
1716
- error: safeError
2167
+ error: { ...safeError, toolError: true }
1717
2168
  },
1718
2169
  maxPayloadBytes
1719
2170
  );
1720
2171
  }
1721
2172
  if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
1722
- const size = utf8ByteLength(sanitizedResult);
2173
+ const size = utf8ByteLength2(sanitizedResult);
1723
2174
  if (size >= referenceConfig.extractionThreshold) {
1724
2175
  try {
1725
2176
  const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
@@ -1743,12 +2194,12 @@ function createHostToolBridge(executionContext, options) {
1743
2194
  {
1744
2195
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
1745
2196
  ok: false,
1746
- error: safeError
2197
+ error: { ...safeError, toolError: true }
1747
2198
  },
1748
2199
  maxPayloadBytes
1749
2200
  );
1750
2201
  }
1751
- if (utf8ByteLength(okJson) > maxPayloadBytes) {
2202
+ if (utf8ByteLength2(okJson) > maxPayloadBytes) {
1752
2203
  return serializeResponse(
1753
2204
  {
1754
2205
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -1756,7 +2207,8 @@ function createHostToolBridge(executionContext, options) {
1756
2207
  error: {
1757
2208
  name: "ToolBridgeError",
1758
2209
  message: `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
1759
- code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
2210
+ code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE",
2211
+ toolError: true
1760
2212
  }
1761
2213
  },
1762
2214
  maxPayloadBytes
@@ -1786,6 +2238,64 @@ var init_tool_bridge = __esm({
1786
2238
  }
1787
2239
  });
1788
2240
 
2241
+ // libs/core/src/tool-namespaces.ts
2242
+ function buildToolNamespaceBindings(install, callTool, namespaces) {
2243
+ if (namespaces.length === 0) return [];
2244
+ if (typeof install !== "function") {
2245
+ throw new Error("Tool namespace factory is not available in the sandbox");
2246
+ }
2247
+ const built = install(
2248
+ callTool,
2249
+ JSON.stringify(namespaces)
2250
+ );
2251
+ return namespaces.map((ns) => ({ name: ns.name, value: built[ns.name] }));
2252
+ }
2253
+ var TOOL_NAMESPACE_FACTORY_SOURCE;
2254
+ var init_tool_namespaces = __esm({
2255
+ "libs/core/src/tool-namespaces.ts"() {
2256
+ "use strict";
2257
+ TOOL_NAMESPACE_FACTORY_SOURCE = `
2258
+ (function () {
2259
+ 'use strict';
2260
+ var parse = JSON.parse;
2261
+ var freeze = Object.freeze;
2262
+ var isArray = Array.isArray;
2263
+
2264
+ function isSafeKey(key) {
2265
+ return typeof key === 'string' && key.length > 0 &&
2266
+ !(key.charAt(0) === '_' && key.charAt(1) === '_') &&
2267
+ key !== 'constructor' && key !== 'prototype';
2268
+ }
2269
+
2270
+ function bind(callTool, toolName) {
2271
+ return (args, options) => callTool(toolName, args === undefined ? {} : args, options);
2272
+ }
2273
+
2274
+ return function install(callTool, namespacesJson) {
2275
+ var spec = parse(namespacesJson);
2276
+ var namespaces = { __proto__: null };
2277
+ if (isArray(spec)) {
2278
+ for (var i = 0; i < spec.length; i++) {
2279
+ var ns = spec[i];
2280
+ if (!ns || !isSafeKey(ns.name) || !isArray(ns.methods)) continue;
2281
+ var target = { __proto__: null };
2282
+ for (var j = 0; j < ns.methods.length; j++) {
2283
+ var method = ns.methods[j];
2284
+ if (!method || !isSafeKey(method.name) || typeof method.toolName !== 'string') continue;
2285
+ target[method.name] = bind(callTool, method.toolName);
2286
+ }
2287
+ freeze(target);
2288
+ namespaces[ns.name] = target;
2289
+ }
2290
+ }
2291
+ freeze(namespaces);
2292
+ return namespaces;
2293
+ };
2294
+ })()
2295
+ `.trim();
2296
+ }
2297
+ });
2298
+
1789
2299
  // libs/core/src/double-vm/parent-vm-bootstrap.ts
1790
2300
  function generateSanitizeContextCode(securityLevel) {
1791
2301
  const globalsToRemove = NODEJS_24_DANGEROUS_GLOBALS[securityLevel];
@@ -1827,7 +2337,9 @@ function generateParentVmBootstrap(options) {
1827
2337
  blockedProperties,
1828
2338
  allowComposites = false,
1829
2339
  memoryLimit = 0,
1830
- throwOnBlocked = true
2340
+ throwOnBlocked = true,
2341
+ maxGlobalFunctionCalls = 1e3,
2342
+ toolNamespaces = []
1831
2343
  } = options;
1832
2344
  const sanitizeContextCode = generateSanitizeContextCode(securityLevel);
1833
2345
  const patternDetectorsCode = generatePatternDetectorsCode(suspiciousPatterns);
@@ -2263,6 +2775,8 @@ ${stackTraceHardeningCode}
2263
2775
  const hostReportViolation = __host_reportViolation__;
2264
2776
  const hostConfig = __host_config__;
2265
2777
  const hostMemoryTrack = typeof __host_memory_track__ === 'function' ? __host_memory_track__ : function(){};
2778
+ const hostInvokeGlobal = typeof __host_invokeGlobal__ === 'function' ? __host_invokeGlobal__ : null;
2779
+ const hostIsBuiltinMethod = typeof __host_isBuiltinMethod__ === 'function' ? __host_isBuiltinMethod__ : function() { return false; };
2266
2780
  const toolBridgeMode = ${JSON.stringify(toolBridgeMode)};
2267
2781
  const toolBridgeMaxPayloadBytes = ${toolBridgeMaxPayloadBytes};
2268
2782
 
@@ -2275,6 +2789,8 @@ ${stackTraceHardeningCode}
2275
2789
  try { delete globalThis.__host_reportViolation__; } catch (e) { /* ignore */ }
2276
2790
  try { delete globalThis.__host_config__; } catch (e) { /* ignore */ }
2277
2791
  try { delete globalThis.__host_memory_track__; } catch (e) { /* ignore */ }
2792
+ try { delete globalThis.__host_invokeGlobal__; } catch (e) { /* ignore */ }
2793
+ try { delete globalThis.__host_isBuiltinMethod__; } catch (e) { /* ignore */ }
2278
2794
 
2279
2795
  // Policy violation reporter (best-effort; host decides how to handle based on security level)
2280
2796
  function __ag_reportViolation(kind) {
@@ -2444,6 +2960,22 @@ ${stackTraceHardeningCode}
2444
2960
  // Tool call stats for rate limiting
2445
2961
  let toolCallCount = 0;
2446
2962
 
2963
+ // Calls into host functions passed in globals: counted against their own cap, and their
2964
+ // timestamps share the operation rate limit with tool calls. They are not recorded in
2965
+ // operationHistory, so the tool-call suspicious-sequence detectors only see tool calls.
2966
+ let globalFunctionCallCount = 0;
2967
+ const globalFunctionCallTimes = [];
2968
+
2969
+ // Fail-closed: every call into a host function goes through the gate, except the built-in
2970
+ // prototype methods of host data (Array.prototype.map, iterators, Date methods, ...), which
2971
+ // the get trap binds and records here so data globals keep working as before.
2972
+ const ungatedHostFunctions = new WeakSet();
2973
+
2974
+ // Errors that report a failure of the tool itself (the handler threw, or its result could not
2975
+ // be delivered), as opposed to a refusal by the enclave. callTool(..., { throwOnError: false })
2976
+ // turns only these into { success: false, error } results. Keyed by the safe error thrown.
2977
+ const toolFailures = new WeakMap();
2978
+
2447
2979
  // Blocked properties for secure proxy (from security level)
2448
2980
  const blockedPropertiesSet = new Set(${JSON.stringify(blockedProperties)});
2449
2981
 
@@ -2549,6 +3081,9 @@ ${stackTraceHardeningCode}
2549
3081
  // Then recursively proxy the bound function to block constructor access
2550
3082
  if (typeof value === 'function') {
2551
3083
  var boundMethod = __ag_functionBind.call(value, target);
3084
+ if (host && hostIsBuiltinMethod(value)) {
3085
+ ungatedHostFunctions.add(boundMethod);
3086
+ }
2552
3087
  return createSecureProxy(boundMethod, depth + 1, host);
2553
3088
  }
2554
3089
 
@@ -2685,18 +3220,29 @@ ${stackTraceHardeningCode}
2685
3220
  // (Promise.prototype up to Function) to reach the host Function constructor for RCE.
2686
3221
  // Results are re-wrapped at a FRESH depth (0) so a chain of calls such as
2687
3222
  // then().then() cannot inflate depth past the recursion cap and leak an unwrapped value.
3223
+ //
3224
+ // SECURITY: a call into a HOST function (a custom global, a method read off one, or
3225
+ // call/apply/bind on one) goes through the global-function gate instead: abort check,
3226
+ // maxGlobalFunctionCalls, the shared operation rate limit, and a sanitized, parent-realm
3227
+ // copy of the result. Without it those calls skipped every limit that guards callTool, and
3228
+ // their results arrived unsanitized. Only built-in methods of host data are exempt.
2688
3229
  apply: function(target, thisArg, args) {
3230
+ if (host && !ungatedHostFunctions.has(target)) {
3231
+ return callHostFunction(target, thisArg, args);
3232
+ }
2689
3233
  return createSecureProxy(__ag_ReflectApply(target, thisArg, args), 0, host);
2690
- }
2691
- // NOTE: intentionally NO construct trap here (unlike the standalone secure-proxy used
2692
- // for single-VM mode). Every constructor reachable from sandbox code resolves to an
3234
+ },
3235
+ // Constructing a HOST function would hand back a raw host instance without passing the
3236
+ // gate, so it is refused. Realm-owned values keep NO construct trap (undefined here means
3237
+ // the default behavior): every constructor reachable from sandbox code resolves to an
2693
3238
  // inner-VM or parent-VM intrinsic, and BOTH of those realms run with code generation
2694
3239
  // from strings disabled, so a 'new X()' result cannot reach a usable Function
2695
- // constructor. The only code-generation-enabled realm (the host) is reached solely via
2696
- // host return values (callTool), which is an apply-path and is covered above. Wrapping
2697
- // construct results would additionally break the proxy invariant for the frozen (non-
2698
- // extensible) Error objects the harness throws (getPrototypeOf must not report null for
2699
- // a non-extensible target), masking legitimate errors.
3240
+ // constructor. Wrapping construct results would additionally break the proxy invariant
3241
+ // for the frozen (non-extensible) Error objects the harness throws (getPrototypeOf must
3242
+ // not report null for a non-extensible target), masking legitimate errors.
3243
+ construct: host ? function() {
3244
+ throw createSafeError('Host functions cannot be called with new', 'TypeError');
3245
+ } : undefined
2700
3246
  });
2701
3247
 
2702
3248
  cache.set(obj, proxy);
@@ -2708,19 +3254,91 @@ ${stackTraceHardeningCode}
2708
3254
  }
2709
3255
 
2710
3256
  /**
2711
- * Validate an operation before forwarding to host
3257
+ * Operation rate limit, shared by tool calls and calls into host functions.
3258
+ * Sliding one-second window; entries older than two seconds are dropped.
2712
3259
  */
2713
- function validateOperation(operationName, args) {
2714
- // Rate limiting check with sliding window cleanup
2715
- const now = Date.now();
2716
- // Clean up old entries to prevent unbounded growth (keep only last 2 seconds)
3260
+ function enforceRateLimit(now) {
2717
3261
  while (operationHistory.length > 0 && now - operationHistory[0].timestamp > 2000) {
2718
3262
  operationHistory.shift();
2719
3263
  }
2720
- const recentOperations = operationHistory.filter(function(h) { return now - h.timestamp < 1000; });
2721
- if (recentOperations.length >= validationConfig.maxOperationsPerSecond) {
3264
+ while (globalFunctionCallTimes.length > 0 && now - globalFunctionCallTimes[0] > 2000) {
3265
+ globalFunctionCallTimes.shift();
3266
+ }
3267
+ var recent = 0;
3268
+ for (var r = 0; r < operationHistory.length; r++) {
3269
+ if (now - operationHistory[r].timestamp < 1000) recent++;
3270
+ }
3271
+ for (var g = 0; g < globalFunctionCallTimes.length; g++) {
3272
+ if (now - globalFunctionCallTimes[g] < 1000) recent++;
3273
+ }
3274
+ if (recent >= validationConfig.maxOperationsPerSecond) {
2722
3275
  throw createSafeError('Operation rate limit exceeded (' + validationConfig.maxOperationsPerSecond + ' operations/second)');
2723
3276
  }
3277
+ }
3278
+
3279
+ /**
3280
+ * Parse the host invoker's JSON envelope into a parent-realm value, or throw its error.
3281
+ */
3282
+ function decodeGlobalFunctionResult(envelopeJson) {
3283
+ if (typeof envelopeJson !== 'string') {
3284
+ throw createSafeError('Global function bridge returned an invalid response');
3285
+ }
3286
+ var envelope;
3287
+ try {
3288
+ envelope = JSON.parse(envelopeJson);
3289
+ } catch (e) {
3290
+ throw createSafeError('Global function bridge returned invalid JSON');
3291
+ }
3292
+ if (!envelope || typeof envelope !== 'object' || envelope.v !== 1) {
3293
+ throw createSafeError('Global function bridge returned an invalid response');
3294
+ }
3295
+ if (envelope.ok === true) {
3296
+ return __ag_hasOwnProperty.call(envelope, 'value') ? envelope.value : undefined;
3297
+ }
3298
+ var failure = envelope.error;
3299
+ var message = (failure && typeof failure.message === 'string') ? failure.message : 'Global function call failed';
3300
+ var name = (failure && typeof failure.name === 'string') ? failure.name : 'Error';
3301
+ throw createSafeError(message, name);
3302
+ }
3303
+
3304
+ /**
3305
+ * The global-function gate: every call from the sandbox into a host function passed in
3306
+ * globals (including functions nested in objects) comes through here.
3307
+ */
3308
+ function callHostFunction(target, thisArg, args) {
3309
+ if (hostAbortCheck()) {
3310
+ throw createSafeError('Execution aborted');
3311
+ }
3312
+ if (typeof hostInvokeGlobal !== 'function') {
3313
+ throw createSafeError('Global function bridge is not available');
3314
+ }
3315
+
3316
+ globalFunctionCallCount++;
3317
+ if (globalFunctionCallCount > ${maxGlobalFunctionCalls}) {
3318
+ throw createSafeError(${JSON.stringify(globalFunctionLimitMessage(maxGlobalFunctionCalls))});
3319
+ }
3320
+
3321
+ var now = Date.now();
3322
+ enforceRateLimit(now);
3323
+ globalFunctionCallTimes.push(now);
3324
+
3325
+ var outcome = hostInvokeGlobal(target, thisArg, args);
3326
+ if (typeof outcome === 'string') {
3327
+ return createSecureProxy(decodeGlobalFunctionResult(outcome));
3328
+ }
3329
+
3330
+ // A host function that returned a thenable: settle to a sanitized parent-realm value.
3331
+ return createSecureProxy(outcome.then(decodeGlobalFunctionResult).then(function(value) {
3332
+ return createSecureProxy(value);
3333
+ }));
3334
+ }
3335
+
3336
+ /**
3337
+ * Validate an operation before forwarding to host
3338
+ */
3339
+ function validateOperation(operationName, args) {
3340
+ // Rate limiting check with sliding window cleanup
3341
+ enforceRateLimit(Date.now());
2724
3342
 
2725
3343
  // Operation name format validation
2726
3344
  if (typeof operationName !== 'string' || !operationName) {
@@ -2762,11 +3380,64 @@ ${stackTraceHardeningCode}
2762
3380
  }
2763
3381
  }
2764
3382
 
3383
+ /**
3384
+ * Read a script's callTool options. Only { throwOnError: false } changes behavior.
3385
+ */
3386
+ function readThrowOnError(options) {
3387
+ if (options === undefined || options === null) return true;
3388
+ if (typeof options !== 'object') {
3389
+ throw createSafeError('callTool options must be an object', 'TypeError');
3390
+ }
3391
+ return options.throwOnError !== false;
3392
+ }
3393
+
3394
+ /**
3395
+ * Remember that a safe error reports a failure of the tool itself (see toolFailures).
3396
+ */
3397
+ function markToolFailure(error, toolName, name, message, code) {
3398
+ var info = { name: name, message: message, toolName: toolName };
3399
+ if (typeof code === 'string') info.code = code;
3400
+ toolFailures.set(error, info);
3401
+ return error;
3402
+ }
3403
+
3404
+ /**
3405
+ * Whether a tool bridge payload is larger than the limit in UTF-8 bytes, as the host counts it.
3406
+ * A code unit is 1 to 3 bytes (a surrogate pair is 4), so only lengths in between are counted.
3407
+ */
3408
+ function exceedsPayloadLimit(str, maxBytes) {
3409
+ if (str.length > maxBytes) return true;
3410
+ if (str.length * 3 <= maxBytes) return false;
3411
+ var bytes = 0;
3412
+ for (var i = 0; i < str.length; i++) {
3413
+ var c = str.charCodeAt(i);
3414
+ if (c < 0x80) bytes += 1;
3415
+ else if (c < 0x800) bytes += 2;
3416
+ else if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
3417
+ var d = str.charCodeAt(i + 1);
3418
+ if (d >= 0xdc00 && d <= 0xdfff) {
3419
+ bytes += 4;
3420
+ i++;
3421
+ } else {
3422
+ bytes += 3;
3423
+ }
3424
+ } else bytes += 3;
3425
+ if (bytes > maxBytes) return true;
3426
+ }
3427
+ return false;
3428
+ }
3429
+
2765
3430
  /**
2766
3431
  * Inner VM's callTool function
2767
3432
  * Proxies through parent VM with validation
3433
+ *
3434
+ * options.throwOnError === false: a failing tool resolves to { success: false, error } and a
3435
+ * working one to { success: true, data }. Refusals by the enclave (abort, tool-call cap, rate
3436
+ * limit, operation-name and suspicious-sequence checks, invalid arguments) still throw.
2768
3437
  */
2769
- function innerCallTool(toolName, args) {
3438
+ function innerCallTool(toolName, args, options) {
3439
+ var throwOnError = readThrowOnError(options);
3440
+
2770
3441
  // Check if aborted
2771
3442
  if (hostAbortCheck()) {
2772
3443
  throw createSafeError('Execution aborted');
@@ -2815,8 +3486,8 @@ ${stackTraceHardeningCode}
2815
3486
  throw createSafeError('Tool request must be JSON-serializable');
2816
3487
  }
2817
3488
 
2818
- // Conservative byte estimate: UTF-8 is at most 4 bytes per code unit.
2819
- if (requestJson && (requestJson.length * 4) > toolBridgeMaxPayloadBytes) {
3489
+ // Counted in UTF-8 bytes, as the host counts it, so both sides agree on the limit.
3490
+ if (requestJson && exceedsPayloadLimit(requestJson, toolBridgeMaxPayloadBytes)) {
2820
3491
  throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
2821
3492
  }
2822
3493
 
@@ -2825,8 +3496,17 @@ ${stackTraceHardeningCode}
2825
3496
  throw createSafeError('Tool bridge returned non-string response');
2826
3497
  }
2827
3498
 
2828
- if ((responseJson.length * 4) > toolBridgeMaxPayloadBytes) {
2829
- throw createSafeError('Tool response exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
3499
+ // The host refuses an oversized response as a tool failure; this check only backs it up,
3500
+ // and reports the same way so { throwOnError: false } resolves it to a result.
3501
+ if (exceedsPayloadLimit(responseJson, toolBridgeMaxPayloadBytes)) {
3502
+ var tooLarge = 'Tool response exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)';
3503
+ throw markToolFailure(
3504
+ createSafeError(tooLarge, 'RangeError'),
3505
+ toolName,
3506
+ 'RangeError',
3507
+ tooLarge,
3508
+ 'TOOL_BRIDGE_RESPONSE_TOO_LARGE'
3509
+ );
2830
3510
  }
2831
3511
 
2832
3512
  var response;
@@ -2855,13 +3535,36 @@ ${stackTraceHardeningCode}
2855
3535
  var err = response.error;
2856
3536
  var msg = (err && typeof err.message === 'string') ? err.message : 'Tool call failed';
2857
3537
  var name = (err && typeof err.name === 'string') ? err.name : 'Error';
2858
- throw createSafeError(msg, name);
3538
+ var failure = createSafeError(msg, name);
3539
+ if (err && err.toolError === true) {
3540
+ markToolFailure(failure, toolName, name, msg, err.code);
3541
+ }
3542
+ throw failure;
2859
3543
  }
2860
3544
 
2861
3545
  throw createSafeError('Tool bridge returned invalid response');
2862
3546
  });
2863
3547
  } else {
2864
- promise = hostCallTool(toolName, sanitizedArgs);
3548
+ promise = hostCallTool(toolName, sanitizedArgs).then(undefined, function(error) {
3549
+ // Direct mode: the host marks failures of the tool itself with this code.
3550
+ if (error && error.code === 'TOOL_CALL_FAILED') {
3551
+ var message = typeof error.message === 'string' ? error.message : 'Tool call failed';
3552
+ throw markToolFailure(createSafeError(message), toolName, 'Error', message, 'TOOL_CALL_FAILED');
3553
+ }
3554
+ throw error;
3555
+ });
3556
+ }
3557
+
3558
+ if (!throwOnError) {
3559
+ promise = promise.then(function(result) {
3560
+ return { success: true, data: result };
3561
+ }, function(error) {
3562
+ var info = toolFailures.get(error);
3563
+ if (info) {
3564
+ return { success: false, error: info };
3565
+ }
3566
+ throw error;
3567
+ });
2865
3568
  }
2866
3569
 
2867
3570
  // Create a secure promise that wraps both the promise object and its result
@@ -3514,6 +4217,36 @@ ${stackTraceHardeningCode}
3514
4217
  innerRuntimeScript.runInContext(innerContext);
3515
4218
  } catch (e) { /* ignore */ }
3516
4219
 
4220
+ // Tool namespaces (mail.list(args)): built INSIDE the inner realm by a factory evaluated there
4221
+ // (before Object/JSON are replaced by the safe globals below), so each namespace is a frozen,
4222
+ // null-prototype inner-realm object whose methods call the gated callTool. A namespace call is
4223
+ // therefore an ordinary tool call: counted, rate-limited, pattern-checked and sanitized.
4224
+ var toolNamespaceNames = ${JSON.stringify(toolNamespaces.map((ns) => ns.name))};
4225
+ if (toolNamespaceNames.length > 0) {
4226
+ var installToolNamespaces = new vm.Script(${JSON.stringify(TOOL_NAMESPACE_FACTORY_SOURCE)}, {
4227
+ filename: 'inner-tool-namespaces.js'
4228
+ }).runInContext(innerContext);
4229
+ var builtToolNamespaces = installToolNamespaces(safeRuntime.__safe_callTool, ${JSON.stringify(
4230
+ JSON.stringify(toolNamespaces)
4231
+ )});
4232
+ for (var tn = 0; tn < toolNamespaceNames.length; tn++) {
4233
+ var toolNamespaceName = toolNamespaceNames[tn];
4234
+ var toolNamespace = builtToolNamespaces[toolNamespaceName];
4235
+ __ag_defineProperty(innerContext, toolNamespaceName, {
4236
+ value: toolNamespace,
4237
+ writable: false,
4238
+ configurable: false,
4239
+ enumerable: false
4240
+ });
4241
+ __ag_defineProperty(innerContext, '__safe_' + toolNamespaceName, {
4242
+ value: toolNamespace,
4243
+ writable: false,
4244
+ configurable: false,
4245
+ enumerable: false
4246
+ });
4247
+ }
4248
+ }
4249
+
3517
4250
  // Defense-in-depth: Remove host callback from inner sandbox after all scripts have captured it
3518
4251
  try { delete innerContext['__host_memory_track__']; } catch (e) { /* ignore */ }
3519
4252
 
@@ -3757,6 +4490,8 @@ var MEMBRANE_MAX_RECURSION_DEPTH, NODEJS_24_DANGEROUS_GLOBALS;
3757
4490
  var init_parent_vm_bootstrap = __esm({
3758
4491
  "libs/core/src/double-vm/parent-vm-bootstrap.ts"() {
3759
4492
  "use strict";
4493
+ init_global_function_gate();
4494
+ init_tool_namespaces();
3760
4495
  MEMBRANE_MAX_RECURSION_DEPTH = 256;
3761
4496
  NODEJS_24_DANGEROUS_GLOBALS = {
3762
4497
  STRICT: [
@@ -3968,54 +4703,21 @@ var init_suspicious_patterns = __esm({
3968
4703
  });
3969
4704
 
3970
4705
  // libs/core/src/double-vm/double-vm-wrapper.ts
3971
- function sanitizeStackTrace(stack, sanitize = true) {
3972
- if (!stack || !sanitize) return stack;
3973
- let sanitized = stack;
3974
- for (const pattern of SENSITIVE_STACK_PATTERNS) {
3975
- pattern.lastIndex = 0;
3976
- sanitized = sanitized.replace(pattern, "[REDACTED]");
3977
- }
3978
- const lines = sanitized.split("\n");
3979
- for (let i = 0; i < lines.length; i++) {
3980
- const line = lines[i];
3981
- if (line.length > 1e3) continue;
3982
- if (/:\d+:\d+\)/.test(line)) {
3983
- const atIdx = line.indexOf("at ");
3984
- if (atIdx !== -1) {
3985
- const afterAt = line.substring(atIdx + 3).trimStart();
3986
- const spaceIdx = afterAt.indexOf(" ");
3987
- if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === "(") {
3988
- const funcName = afterAt.substring(0, spaceIdx);
3989
- lines[i] = line.substring(0, atIdx) + "at " + funcName + " ([REDACTED])";
3990
- continue;
3991
- }
3992
- }
3993
- }
3994
- if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
3995
- lines[i] = line.replace(/:\d+:\d+$/, "") + "[REDACTED]";
3996
- }
3997
- }
3998
- return lines.join("\n");
3999
- }
4000
- var vm2, SENSITIVE_STACK_PATTERNS, DoubleVmWrapper;
4706
+ var vm3, DoubleVmWrapper;
4001
4707
  var init_double_vm_wrapper = __esm({
4002
4708
  "libs/core/src/double-vm/double-vm-wrapper.ts"() {
4003
4709
  "use strict";
4004
- vm2 = __toESM(require("vm"));
4710
+ vm3 = __toESM(require("vm"));
4005
4711
  init_value_sanitizer();
4006
4712
  init_secure_proxy();
4007
4713
  init_safe_error();
4008
4714
  init_reference_resolver();
4009
4715
  init_memory_tracker();
4010
4716
  init_tool_bridge();
4717
+ init_stack_trace();
4718
+ init_global_function_gate();
4011
4719
  init_parent_vm_bootstrap();
4012
4720
  init_suspicious_patterns();
4013
- SENSITIVE_STACK_PATTERNS = [
4014
- /\/Users\/[^/]+\/[^\s):]*/gi,
4015
- /\/home\/[^/]+\/[^\s):]*/gi,
4016
- /\/var\/[^\s):]*/gi,
4017
- /node_modules\/[^\s):]+/gi
4018
- ];
4019
4721
  DoubleVmWrapper = class {
4020
4722
  constructor(config, securityLevel) {
4021
4723
  this.config = config;
@@ -4043,7 +4745,7 @@ var init_double_vm_wrapper = __esm({
4043
4745
  });
4044
4746
  this.parentContext = parentContext;
4045
4747
  const parentScript = this.buildParentScript(code, executionContext);
4046
- const script = new vm2.Script(parentScript, {
4748
+ const script = new vm3.Script(parentScript, {
4047
4749
  filename: "parent-vm.js"
4048
4750
  });
4049
4751
  const parentTimeout = config.timeout + this.config.parentTimeoutBuffer;
@@ -4155,15 +4857,15 @@ var init_double_vm_wrapper = __esm({
4155
4857
  */
4156
4858
  createParentContext(executionContext, memoryTracker, reportViolation) {
4157
4859
  const { stats, config } = executionContext;
4158
- const parentContext = vm2.createContext(
4860
+ const parentContext = vm3.createContext(
4159
4861
  {},
4160
4862
  {
4161
4863
  codeGeneration: { strings: false, wasm: false }
4162
4864
  }
4163
4865
  );
4164
4866
  const safeVm = {
4165
- createContext: vm2.createContext.bind(vm2),
4166
- Script: vm2.Script
4867
+ createContext: vm3.createContext.bind(vm3),
4868
+ Script: vm3.Script
4167
4869
  };
4168
4870
  Object.defineProperty(parentContext, "__host_vm_module__", {
4169
4871
  value: safeVm,
@@ -4179,6 +4881,18 @@ var init_double_vm_wrapper = __esm({
4179
4881
  configurable: true
4180
4882
  // Allow deletion after capture for defense-in-depth
4181
4883
  });
4884
+ Object.defineProperty(parentContext, "__host_invokeGlobal__", {
4885
+ value: createHostGlobalFunctionInvoker(executionContext),
4886
+ writable: false,
4887
+ configurable: true
4888
+ // Allow deletion after capture for defense-in-depth
4889
+ });
4890
+ Object.defineProperty(parentContext, "__host_isBuiltinMethod__", {
4891
+ value: (fn) => isBuiltinMethod(fn),
4892
+ writable: false,
4893
+ configurable: true
4894
+ // Allow deletion after capture for defense-in-depth
4895
+ });
4182
4896
  Object.defineProperty(parentContext, "__host_stats__", {
4183
4897
  value: stats,
4184
4898
  writable: false,
@@ -4314,7 +5028,11 @@ var init_double_vm_wrapper = __esm({
4314
5028
  return sanitized;
4315
5029
  } catch (error) {
4316
5030
  const err = error;
4317
- throw createSafeError(`Tool call failed: ${toolName} - ${err.message || "Unknown error"}`);
5031
+ throw createSafeError(
5032
+ `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`,
5033
+ "Error",
5034
+ "TOOL_CALL_FAILED"
5035
+ );
4318
5036
  }
4319
5037
  };
4320
5038
  }
@@ -4359,7 +5077,9 @@ var init_double_vm_wrapper = __esm({
4359
5077
  memoryLimit: config.memoryLimit,
4360
5078
  throwOnBlocked,
4361
5079
  toolBridgeMode,
4362
- toolBridgeMaxPayloadBytes
5080
+ toolBridgeMaxPayloadBytes,
5081
+ maxGlobalFunctionCalls: resolveMaxGlobalFunctionCalls(config),
5082
+ toolNamespaces: executionContext.toolNamespaces ?? []
4363
5083
  });
4364
5084
  }
4365
5085
  /**
@@ -4540,6 +5260,16 @@ var init_memory_proxy = __esm({
4540
5260
  });
4541
5261
 
4542
5262
  // libs/core/src/safe-runtime.ts
5263
+ function readThrowOnError(options) {
5264
+ if (options === void 0 || options === null) return true;
5265
+ if (typeof options !== "object") {
5266
+ throw createSafeTypeError("callTool options must be an object");
5267
+ }
5268
+ return options.throwOnError !== false;
5269
+ }
5270
+ function plainResult(fields) {
5271
+ return Object.assign(/* @__PURE__ */ Object.create(null), fields);
5272
+ }
4543
5273
  function createSafeRuntime(context, options) {
4544
5274
  const { config, stats } = context;
4545
5275
  const sidecar = options?.sidecar;
@@ -4548,7 +5278,8 @@ function createSafeRuntime(context, options) {
4548
5278
  const memoryTracker = options?.memoryTracker;
4549
5279
  const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
4550
5280
  const proxyOptions = secureProxyConfig ? { levelConfig: secureProxyConfig } : {};
4551
- async function __safe_callTool(toolName, args) {
5281
+ async function __safe_callTool(toolName, args, options2) {
5282
+ const throwOnError = readThrowOnError(options2);
4552
5283
  if (context.aborted) {
4553
5284
  throw createSafeError("Execution aborted");
4554
5285
  }
@@ -4592,21 +5323,34 @@ function createSafeRuntime(context, options) {
4592
5323
  allowDates: true,
4593
5324
  allowErrors: true
4594
5325
  });
5326
+ let value = sanitized;
4595
5327
  if (sidecar && referenceConfig && typeof sanitized === "string") {
4596
5328
  const size = Buffer.byteLength(sanitized, "utf-8");
4597
5329
  if (size >= referenceConfig.extractionThreshold) {
4598
5330
  try {
4599
- const refId = sidecar.store(sanitized, "tool-result", { origin: toolName });
4600
- return refId;
5331
+ value = sidecar.store(sanitized, "tool-result", { origin: toolName });
4601
5332
  } catch {
4602
- return sanitized;
5333
+ value = sanitized;
4603
5334
  }
4604
5335
  }
4605
5336
  }
4606
- return sanitized;
5337
+ return throwOnError ? value : plainResult({ success: true, data: value });
4607
5338
  } catch (error) {
4608
5339
  const err = error;
4609
- throw createSafeError(`Tool call failed: ${toolName} - ${err.message || "Unknown error"}`);
5340
+ const message = `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`;
5341
+ if (!throwOnError) {
5342
+ const code = error?.code;
5343
+ return plainResult({
5344
+ success: false,
5345
+ error: plainResult({
5346
+ name: "Error",
5347
+ message,
5348
+ ...typeof code === "string" ? { code } : {},
5349
+ toolName
5350
+ })
5351
+ });
5352
+ }
5353
+ throw createSafeError(message);
4610
5354
  }
4611
5355
  }
4612
5356
  function* __safe_forOf(iterable) {
@@ -4803,7 +5547,8 @@ ${errorMessages}`);
4803
5547
  }
4804
5548
  const customGlobalsWithPrefix = {};
4805
5549
  if (config.globals) {
4806
- const wrappedCustomGlobals = wrapGlobalsWithSecureProxy(config.globals, proxyOptions);
5550
+ const customGlobalProxyOptions = options?.globalFunctionGate ? { ...proxyOptions, callGate: options.globalFunctionGate } : proxyOptions;
5551
+ const wrappedCustomGlobals = wrapGlobalsWithSecureProxy(config.globals, customGlobalProxyOptions);
4807
5552
  for (const [key, value] of Object.entries(wrappedCustomGlobals)) {
4808
5553
  customGlobalsWithPrefix[`__safe_${key}`] = value;
4809
5554
  }
@@ -4858,18 +5603,22 @@ ${errorMessages}`);
4858
5603
  }
4859
5604
  function serializeSafeRuntime() {
4860
5605
  return `
4861
- // Safe callTool implementation
4862
- async function __safe_callTool(toolName, args) {
5606
+ // Safe callTool implementation. The options ({ throwOnError: false }) are passed on:
5607
+ // only the adapter's __internal_callTool can tell a failure of the tool from a refusal.
5608
+ async function __safe_callTool(toolName, args, options) {
4863
5609
  if (typeof toolName !== 'string' || !toolName) {
4864
5610
  throw new TypeError('Tool name must be a non-empty string');
4865
5611
  }
4866
5612
  if (typeof args !== 'object' || args === null || Array.isArray(args)) {
4867
5613
  throw new TypeError('Tool arguments must be an object');
4868
5614
  }
5615
+ if (options !== undefined && options !== null && typeof options !== 'object') {
5616
+ throw new TypeError('callTool options must be an object');
5617
+ }
4869
5618
 
4870
5619
  // This will be replaced by the sandbox adapter with actual implementation
4871
5620
  if (typeof __internal_callTool === 'function') {
4872
- return await __internal_callTool(toolName, args);
5621
+ return await __internal_callTool(toolName, args, options);
4873
5622
  }
4874
5623
  throw new Error('Tool handler not available');
4875
5624
  }
@@ -5038,36 +5787,6 @@ var vm_adapter_exports = {};
5038
5787
  __export(vm_adapter_exports, {
5039
5788
  VmAdapter: () => VmAdapter
5040
5789
  });
5041
- function sanitizeStackTrace2(stack, sanitize = true) {
5042
- if (!stack) return stack;
5043
- if (!sanitize) return stack;
5044
- let sanitized = stack;
5045
- for (const pattern of SENSITIVE_STACK_PATTERNS2) {
5046
- pattern.lastIndex = 0;
5047
- sanitized = sanitized.replace(pattern, "[REDACTED]");
5048
- }
5049
- const lines = sanitized.split("\n");
5050
- for (let i = 0; i < lines.length; i++) {
5051
- const line = lines[i];
5052
- if (line.length > 1e3) continue;
5053
- if (/:\d+:\d+\)/.test(line)) {
5054
- const atIdx = line.indexOf("at ");
5055
- if (atIdx !== -1) {
5056
- const afterAt = line.substring(atIdx + 3).trimStart();
5057
- const spaceIdx = afterAt.indexOf(" ");
5058
- if (spaceIdx !== -1 && afterAt.charAt(spaceIdx + 1) === "(") {
5059
- const funcName = afterAt.substring(0, spaceIdx);
5060
- lines[i] = line.substring(0, atIdx) + "at " + funcName + " ([REDACTED])";
5061
- continue;
5062
- }
5063
- }
5064
- }
5065
- if (/:\d+:\d+$/.test(line) && /^\s*at\s/.test(line)) {
5066
- lines[i] = line.replace(/:\d+:\d+$/, "") + "[REDACTED]";
5067
- }
5068
- }
5069
- return lines.join("\n");
5070
- }
5071
5790
  function createSafeConsole(config, stats) {
5072
5791
  const wrap = (method) => (...args) => {
5073
5792
  stats.callCount++;
@@ -5231,141 +5950,20 @@ function sanitizeVmContext(context, securityLevel) {
5231
5950
  enumerable: true
5232
5951
  });
5233
5952
  }
5234
- var vm3, SENSITIVE_STACK_PATTERNS2, STACK_TRACE_HARDENING_CODE, STACK_TRACE_HARDENING_SCRIPT, CODE_GENERATION_VIOLATION_DETECTOR_CODE, CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT, INTRINSIC_OBJECT_NEUTRALIZATION_CODE, INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT, PROTECTED_PREFIXES, DANGEROUS_OBJECT_STATIC_METHODS, NODEJS_24_DANGEROUS_GLOBALS2, VmAdapter;
5953
+ var vm4, 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;
5235
5954
  var init_vm_adapter = __esm({
5236
5955
  "libs/core/src/adapters/vm-adapter.ts"() {
5237
5956
  "use strict";
5238
- vm3 = __toESM(require("vm"));
5957
+ vm4 = __toESM(require("vm"));
5239
5958
  init_safe_runtime();
5240
5959
  init_secure_proxy();
5241
5960
  init_safe_error();
5242
5961
  init_memory_tracker();
5243
5962
  init_tool_bridge();
5244
5963
  init_value_sanitizer();
5245
- SENSITIVE_STACK_PATTERNS2 = [
5246
- // Unix file system paths
5247
- /\/Users\/[^/]+\/[^\s):]*/gi,
5248
- // macOS home directories
5249
- /\/home\/[^/]+\/[^\s):]*/gi,
5250
- // Linux home directories
5251
- /\/var\/[^\s):]*/gi,
5252
- // System var directories
5253
- /\/opt\/[^\s):]*/gi,
5254
- // Optional software
5255
- /\/tmp\/[^\s):]*/gi,
5256
- // Temporary files
5257
- /\/etc\/[^\s):]*/gi,
5258
- // System configuration
5259
- /\/root\/[^\s):]*/gi,
5260
- // Root home directory
5261
- /\/mnt\/[^\s):]*/gi,
5262
- // Mount points
5263
- /\/srv\/[^\s):]*/gi,
5264
- // Service data
5265
- /\/data\/[^\s):]*/gi,
5266
- // Data directories
5267
- /\/app\/[^\s):]*/gi,
5268
- // Application directories
5269
- /\/proc\/[^\s):]*/gi,
5270
- // Process information
5271
- /\/sys\/[^\s):]*/gi,
5272
- // System files
5273
- // Windows paths
5274
- /\\\\[^\s):]*/g,
5275
- // UNC paths
5276
- /[A-Z]:\\[^\s):]+/gi,
5277
- // Windows drive paths
5278
- // URL-based paths
5279
- /file:\/\/[^\s):]+/gi,
5280
- // File URLs
5281
- /webpack:\/\/[^\s):]+/gi,
5282
- // Webpack paths
5283
- /%2F[^\s):]+/gi,
5284
- // URL-encoded paths
5285
- // Package managers and node
5286
- /node_modules\/[^\s):]+/gi,
5287
- // Node modules paths
5288
- /\/nix\/store\/[^\s):]*/gi,
5289
- // Nix store paths
5290
- /\.npm\/[^\s):]*/gi,
5291
- // NPM cache
5292
- /\.yarn\/[^\s):]*/gi,
5293
- // Yarn cache
5294
- /\.pnpm\/[^\s):]*/gi,
5295
- // PNPM cache
5296
- // Container and orchestration
5297
- /\/run\/secrets\/[^\s):]*/gi,
5298
- // Docker/K8s secrets
5299
- /\/var\/run\/[^\s):]*/gi,
5300
- // Runtime directories
5301
- /\/docker\/[^\s):]*/gi,
5302
- // Docker paths
5303
- /\/containers\/[^\s):]*/gi,
5304
- // Container paths
5305
- /\/kubelet\/[^\s):]*/gi,
5306
- // Kubernetes kubelet
5307
- // CI/CD systems
5308
- /\/github\/workspace\/[^\s):]*/gi,
5309
- // GitHub Actions
5310
- /\/runner\/[^\s):]*/gi,
5311
- // GitHub/GitLab runner
5312
- /\/builds\/[^\s):]*/gi,
5313
- // CI builds
5314
- /\/workspace\/[^\s):]*/gi,
5315
- // Generic workspace
5316
- /\/pipeline\/[^\s):]*/gi,
5317
- // CI pipelines
5318
- /\/jenkins\/[^\s):]*/gi,
5319
- // Jenkins
5320
- /\/bamboo\/[^\s):]*/gi,
5321
- // Bamboo
5322
- /\/teamcity\/[^\s):]*/gi,
5323
- // TeamCity
5324
- /\/circleci\/[^\s):]*/gi,
5325
- // CircleCI
5326
- // Cloud providers
5327
- /\/aws\/[^\s):]*/gi,
5328
- // AWS paths
5329
- /\/gcloud\/[^\s):]*/gi,
5330
- // Google Cloud
5331
- /\/azure\/[^\s):]*/gi,
5332
- // Azure paths
5333
- /s3:\/\/[^\s):]+/gi,
5334
- // S3 URIs
5335
- /gs:\/\/[^\s):]+/gi,
5336
- // GCS URIs
5337
- // Secrets and credentials (patterns that might appear in paths or errors)
5338
- /[A-Z0-9]{20,}/g,
5339
- // AWS-style access keys (20+ uppercase chars)
5340
- /sk-[a-zA-Z0-9]{32,}/g,
5341
- // OpenAI/Stripe-style secret keys
5342
- /ghp_[a-zA-Z0-9]{36,}/g,
5343
- // GitHub personal access tokens
5344
- /gho_[a-zA-Z0-9]{36,}/g,
5345
- // GitHub OAuth tokens
5346
- /github_pat_[a-zA-Z0-9_]{22,}/g,
5347
- // GitHub fine-grained tokens
5348
- /xox[baprs]-[a-zA-Z0-9-]+/g,
5349
- // Slack tokens
5350
- /Bearer\s+[a-zA-Z0-9._-]+/gi,
5351
- // Bearer tokens
5352
- /Basic\s+[a-zA-Z0-9+/=]+/gi,
5353
- // Basic auth
5354
- // Internal network info
5355
- /(?:10|172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d+\.\d+/g,
5356
- // Private IPs
5357
- /[a-z0-9-]+\.internal(?:\.[a-z]+)?/gi,
5358
- // Internal hostnames
5359
- /localhost:\d+/gi,
5360
- // Localhost with port
5361
- /127\.0\.0\.1:\d+/gi,
5362
- // Loopback with port
5363
- // User information
5364
- /\/u\/[^/]+\//gi,
5365
- // User subdirectories
5366
- /~[a-z_][a-z0-9_-]*/gi
5367
- // Unix user home shorthand
5368
- ];
5964
+ init_stack_trace();
5965
+ init_global_function_gate();
5966
+ init_tool_namespaces();
5369
5967
  STACK_TRACE_HARDENING_CODE = `
5370
5968
  (function() {
5371
5969
  function __ag_redactStackString(stackStr) {
@@ -5465,7 +6063,7 @@ var init_vm_adapter = __esm({
5465
6063
  } catch (e) {}
5466
6064
  })();
5467
6065
  `.trim();
5468
- STACK_TRACE_HARDENING_SCRIPT = new vm3.Script(STACK_TRACE_HARDENING_CODE);
6066
+ STACK_TRACE_HARDENING_SCRIPT = new vm4.Script(STACK_TRACE_HARDENING_CODE);
5469
6067
  CODE_GENERATION_VIOLATION_DETECTOR_CODE = `
5470
6068
  (function() {
5471
6069
  var __ag_report = (typeof __ag_reportViolation__ === 'function') ? __ag_reportViolation__ : null;
@@ -5514,7 +6112,7 @@ var init_vm_adapter = __esm({
5514
6112
  try { __ag_wrapCtor((async function*(){}).constructor, 'CODE_GENERATION'); } catch (e) {}
5515
6113
  })();
5516
6114
  `.trim();
5517
- CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT = new vm3.Script(CODE_GENERATION_VIOLATION_DETECTOR_CODE);
6115
+ CODE_GENERATION_VIOLATION_DETECTOR_SCRIPT = new vm4.Script(CODE_GENERATION_VIOLATION_DETECTOR_CODE);
5518
6116
  INTRINSIC_OBJECT_NEUTRALIZATION_CODE = `
5519
6117
  (function() {
5520
6118
  var RealObject = Object.getPrototypeOf({}).constructor;
@@ -5530,7 +6128,21 @@ var init_vm_adapter = __esm({
5530
6128
  }
5531
6129
  })();
5532
6130
  `;
5533
- INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new vm3.Script(INTRINSIC_OBJECT_NEUTRALIZATION_CODE);
6131
+ INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new vm4.Script(INTRINSIC_OBJECT_NEUTRALIZATION_CODE);
6132
+ SANDBOX_REALM_BRIDGE_SCRIPT = new vm4.Script(`
6133
+ (function () {
6134
+ 'use strict';
6135
+ var parse = JSON.parse;
6136
+ var SandboxPromise = Promise;
6137
+ return Object.freeze({
6138
+ parseJson: function (json) { return parse(json); },
6139
+ adoptPromise: function (hostPromise) {
6140
+ return new SandboxPromise(function (resolve, reject) { hostPromise.then(resolve, reject); });
6141
+ }
6142
+ });
6143
+ })()
6144
+ `);
6145
+ TOOL_NAMESPACE_FACTORY_SCRIPT = new vm4.Script(TOOL_NAMESPACE_FACTORY_SOURCE, { filename: "tool-namespaces.js" });
5534
6146
  PROTECTED_PREFIXES = ["__safe_", "__ag_"];
5535
6147
  DANGEROUS_OBJECT_STATIC_METHODS = [
5536
6148
  "defineProperty",
@@ -5646,19 +6258,23 @@ var init_vm_adapter = __esm({
5646
6258
  }) : void 0;
5647
6259
  memoryTracker?.start();
5648
6260
  try {
6261
+ const baseSandbox = vm4.createContext(
6262
+ {},
6263
+ {
6264
+ codeGeneration: { strings: false, wasm: false }
6265
+ }
6266
+ );
6267
+ const realmBridge = SANDBOX_REALM_BRIDGE_SCRIPT.runInContext(baseSandbox);
6268
+ const installToolNamespaces = executionContext.toolNamespaces?.length ? TOOL_NAMESPACE_FACTORY_SCRIPT.runInContext(baseSandbox) : void 0;
6269
+ const globalFunctionGate = createGlobalFunctionGate(executionContext, realmBridge);
5649
6270
  const safeRuntime = createSafeRuntime(executionContext, {
5650
6271
  sidecar: executionContext.sidecar,
5651
6272
  referenceConfig: executionContext.referenceConfig,
5652
6273
  secureProxyConfig: executionContext.secureProxyConfig,
5653
- memoryTracker
6274
+ memoryTracker,
5654
6275
  // Pass tracker for allocation monitoring
6276
+ globalFunctionGate
5655
6277
  });
5656
- const baseSandbox = vm3.createContext(
5657
- {},
5658
- {
5659
- codeGeneration: { strings: false, wasm: false }
5660
- }
5661
- );
5662
6278
  if (memoryTracker && config.memoryLimit && config.memoryLimit > 0) {
5663
6279
  Object.defineProperty(baseSandbox, "__host_memory_track__", {
5664
6280
  value: (bytes) => {
@@ -5668,7 +6284,7 @@ var init_vm_adapter = __esm({
5668
6284
  configurable: true,
5669
6285
  enumerable: false
5670
6286
  });
5671
- const patchScript = new vm3.Script(`
6287
+ const patchScript = new vm4.Script(`
5672
6288
  (function() {
5673
6289
  var memoryLimit = ${config.memoryLimit};
5674
6290
  var trackMemory = __host_memory_track__;
@@ -5811,7 +6427,7 @@ var init_vm_adapter = __esm({
5811
6427
  // allow deletion after capture
5812
6428
  enumerable: false
5813
6429
  });
5814
- const bridgeInitScript = new vm3.Script(`
6430
+ const bridgeInitScript = new vm4.Script(`
5815
6431
  (function() {
5816
6432
  var bridge = __host_callToolBridge__;
5817
6433
  var stringify = JSON.stringify;
@@ -5822,9 +6438,28 @@ var init_vm_adapter = __esm({
5822
6438
  // Remove global handle after capture (defense-in-depth)
5823
6439
  try { delete globalThis.__host_callToolBridge__; } catch (e) { /* ignore */ }
5824
6440
 
5825
- function estimateBytes(str) {
5826
- // Conservative: UTF-8 can be up to 4 bytes per code unit.
5827
- return str.length * 4;
6441
+ // Whether a payload is larger than the limit in UTF-8 bytes, as the host counts it. A code
6442
+ // unit is 1 to 3 bytes (a surrogate pair is 4), so only lengths in between are counted.
6443
+ function exceedsPayloadLimit(str) {
6444
+ if (str.length > maxBytes) return true;
6445
+ if (str.length * 3 <= maxBytes) return false;
6446
+ var bytes = 0;
6447
+ for (var i = 0; i < str.length; i++) {
6448
+ var c = str.charCodeAt(i);
6449
+ if (c < 0x80) bytes += 1;
6450
+ else if (c < 0x800) bytes += 2;
6451
+ else if (c >= 0xd800 && c <= 0xdbff && i + 1 < str.length) {
6452
+ var d = str.charCodeAt(i + 1);
6453
+ if (d >= 0xdc00 && d <= 0xdfff) {
6454
+ bytes += 4;
6455
+ i++;
6456
+ } else {
6457
+ bytes += 3;
6458
+ }
6459
+ } else bytes += 3;
6460
+ if (bytes > maxBytes) return true;
6461
+ }
6462
+ return false;
5828
6463
  }
5829
6464
 
5830
6465
  function makeError(message, name) {
@@ -5833,7 +6468,16 @@ var init_vm_adapter = __esm({
5833
6468
  return err;
5834
6469
  }
5835
6470
 
5836
- return async function __safe_callTool(toolName, args) {
6471
+ return async function __safe_callTool(toolName, args, options) {
6472
+ // callTool options: only { throwOnError: false } changes behavior. Tool failures
6473
+ // then resolve to { success: false, error }; the enclave's own refusals still throw.
6474
+ var throwOnError = true;
6475
+ if (options !== undefined && options !== null) {
6476
+ if (typeof options !== 'object') {
6477
+ throw makeError('callTool options must be an object', 'TypeError');
6478
+ }
6479
+ throwOnError = options.throwOnError !== false;
6480
+ }
5837
6481
  if (typeof toolName !== 'string' || !toolName) {
5838
6482
  throw makeError('Tool name must be a non-empty string', 'TypeError');
5839
6483
  }
@@ -5859,7 +6503,7 @@ var init_vm_adapter = __esm({
5859
6503
  throw makeError('Tool request must be JSON-serializable', 'TypeError');
5860
6504
  }
5861
6505
 
5862
- if (estimateBytes(requestJson) > maxBytes) {
6506
+ if (exceedsPayloadLimit(requestJson)) {
5863
6507
  throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
5864
6508
  }
5865
6509
 
@@ -5867,8 +6511,24 @@ var init_vm_adapter = __esm({
5867
6511
  if (typeof responseJson !== 'string') {
5868
6512
  throw makeError('Tool bridge returned invalid response', 'Error');
5869
6513
  }
5870
- if (estimateBytes(responseJson) > maxBytes) {
5871
- throw makeError('Tool response exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
6514
+ // The host refuses an oversized response as a tool failure; this check only backs it
6515
+ // up, and reports the same way so { throwOnError: false } resolves it to a result.
6516
+ if (exceedsPayloadLimit(responseJson)) {
6517
+ var tooLarge = 'Tool response exceeds maximum size (' + maxBytes + ' bytes)';
6518
+ if (!throwOnError) {
6519
+ return {
6520
+ __proto__: null,
6521
+ success: false,
6522
+ error: {
6523
+ __proto__: null,
6524
+ name: 'RangeError',
6525
+ message: tooLarge,
6526
+ toolName: toolName,
6527
+ code: 'TOOL_BRIDGE_RESPONSE_TOO_LARGE',
6528
+ },
6529
+ };
6530
+ }
6531
+ throw makeError(tooLarge, 'RangeError');
5872
6532
  }
5873
6533
 
5874
6534
  var response;
@@ -5883,13 +6543,18 @@ var init_vm_adapter = __esm({
5883
6543
  }
5884
6544
 
5885
6545
  if (response.ok === true) {
5886
- if (hasOwn.call(response, 'value')) return response.value;
5887
- return undefined;
6546
+ var value = hasOwn.call(response, 'value') ? response.value : undefined;
6547
+ return throwOnError ? value : { __proto__: null, success: true, data: value };
5888
6548
  }
5889
6549
 
5890
6550
  if (response.ok === false && response.error) {
5891
6551
  var msg = (typeof response.error.message === 'string') ? response.error.message : 'Tool call failed';
5892
6552
  var name = (typeof response.error.name === 'string') ? response.error.name : 'Error';
6553
+ if (!throwOnError && response.error.toolError === true) {
6554
+ var info = { __proto__: null, name: name, message: msg, toolName: toolName };
6555
+ if (typeof response.error.code === 'string') info.code = response.error.code;
6556
+ return { __proto__: null, success: false, error: info };
6557
+ }
5893
6558
  throw makeError(msg, name);
5894
6559
  }
5895
6560
 
@@ -5923,8 +6588,9 @@ var init_vm_adapter = __esm({
5923
6588
  }
5924
6589
  if (config.globals) {
5925
6590
  for (const [key, value2] of Object.entries(config.globals)) {
5926
- const wrappedValue = value2 !== null && typeof value2 === "object" ? createSecureProxy(value2, {
5927
- levelConfig: executionContext.secureProxyConfig
6591
+ const wrappedValue = value2 !== null && (typeof value2 === "object" || typeof value2 === "function") ? createSecureProxy(value2, {
6592
+ levelConfig: executionContext.secureProxyConfig,
6593
+ callGate: globalFunctionGate
5928
6594
  }) : value2;
5929
6595
  Object.defineProperty(baseSandbox, key, {
5930
6596
  value: wrappedValue,
@@ -5934,6 +6600,23 @@ var init_vm_adapter = __esm({
5934
6600
  });
5935
6601
  }
5936
6602
  }
6603
+ if (executionContext.toolNamespaces?.length) {
6604
+ const callTool = baseSandbox["__safe_callTool"];
6605
+ for (const binding of buildToolNamespaceBindings(
6606
+ installToolNamespaces,
6607
+ callTool,
6608
+ executionContext.toolNamespaces
6609
+ )) {
6610
+ for (const name of [binding.name, `__safe_${binding.name}`]) {
6611
+ Object.defineProperty(baseSandbox, name, {
6612
+ value: binding.value,
6613
+ writable: false,
6614
+ configurable: false,
6615
+ enumerable: false
6616
+ });
6617
+ }
6618
+ }
6619
+ }
5937
6620
  if (!("__safe_console" in safeRuntime)) {
5938
6621
  const consoleStats = { totalBytes: 0, callCount: 0 };
5939
6622
  Object.defineProperty(baseSandbox, "__safe_console", {
@@ -5956,7 +6639,7 @@ var init_vm_adapter = __esm({
5956
6639
  const _protectedSandbox = createProtectedSandbox(baseSandbox);
5957
6640
  this.context = baseSandbox;
5958
6641
  const wrappedCode = "(async () => {\n" + code + '\nreturn typeof __ag_main === "function" ? await __ag_main() : undefined;\n})();';
5959
- const script = new vm3.Script(wrappedCode, {
6642
+ const script = new vm4.Script(wrappedCode, {
5960
6643
  filename: "agentscript.js"
5961
6644
  });
5962
6645
  const resultPromise = script.runInContext(this.context, {
@@ -6005,7 +6688,9 @@ var init_vm_adapter = __esm({
6005
6688
  maxDepth: clampedDepth,
6006
6689
  maxProperties: clampedProperties,
6007
6690
  allowDates: true,
6008
- allowErrors: true
6691
+ allowErrors: true,
6692
+ // The membrane wraps the script's Dates; read them through their targets.
6693
+ unwrap: unwrapSecureProxy
6009
6694
  });
6010
6695
  return {
6011
6696
  success: true,
@@ -6041,7 +6726,7 @@ var init_vm_adapter = __esm({
6041
6726
  error: {
6042
6727
  name: err.name || "VMExecutionError",
6043
6728
  message: err.message || "Unknown VM execution error",
6044
- stack: sanitizeStackTrace2(err.stack, shouldSanitize),
6729
+ stack: sanitizeStackTrace(err.stack, shouldSanitize),
6045
6730
  code: "VM_EXECUTION_ERROR"
6046
6731
  },
6047
6732
  stats
@@ -6193,12 +6878,13 @@ function isExecutionResultMessage(msg) {
6193
6878
  function isConsoleMessage(msg) {
6194
6879
  return msg.type === "console";
6195
6880
  }
6196
- var import_zod, TOOL_NAME_PATTERN, ID_PATTERN, toolCallMessageSchema, executionResultMessageSchema, memoryReportResultMessageSchema, consoleMessageSchema, workerReadyMessageSchema, workerToMainMessageSchema;
6881
+ var import_zod, import_ast3, TOOL_NAME_PATTERN, ID_PATTERN, toolCallMessageSchema, executionResultMessageSchema, memoryReportResultMessageSchema, consoleMessageSchema, workerReadyMessageSchema, workerToMainMessageSchema;
6197
6882
  var init_protocol = __esm({
6198
6883
  "libs/core/src/adapters/worker-pool/protocol.ts"() {
6199
6884
  "use strict";
6200
6885
  import_zod = require("zod");
6201
- TOOL_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9:_-]*$/;
6886
+ import_ast3 = require("@enclave-vm/ast");
6887
+ TOOL_NAME_PATTERN = import_ast3.TOOL_NAMESPACE_TOOL_NAME_PATTERN;
6202
6888
  ID_PATTERN = /^[a-zA-Z0-9-]+$/;
6203
6889
  toolCallMessageSchema = import_zod.z.object({
6204
6890
  type: import_zod.z.literal("tool-call"),
@@ -6212,6 +6898,13 @@ var init_protocol = __esm({
6212
6898
  requestId: import_zod.z.string().min(1).max(100).regex(ID_PATTERN),
6213
6899
  success: import_zod.z.boolean(),
6214
6900
  value: import_zod.z.unknown().optional(),
6901
+ specialValues: import_zod.z.array(
6902
+ import_zod.z.object({
6903
+ path: import_zod.z.array(import_zod.z.union([import_zod.z.string(), import_zod.z.number().int().nonnegative()])).max(64),
6904
+ kind: import_zod.z.enum(["date", "nan", "infinity", "-infinity", "undefined"]),
6905
+ time: import_zod.z.number().nullable().optional()
6906
+ }).strict()
6907
+ ).optional(),
6215
6908
  error: import_zod.z.object({
6216
6909
  name: import_zod.z.string().max(100),
6217
6910
  message: import_zod.z.string().max(1e4),
@@ -6430,7 +7123,7 @@ function sanitizeObjectWithDepthCheck(value, depth) {
6430
7123
  if (typeof value !== "object") {
6431
7124
  return value;
6432
7125
  }
6433
- if (ArrayIsArray2(value)) {
7126
+ if (ArrayIsArray3(value)) {
6434
7127
  return mapArraySafely(value, (item) => sanitizeObjectWithDepthCheck(item, depth + 1));
6435
7128
  }
6436
7129
  const result = /* @__PURE__ */ Object.create(null);
@@ -6449,6 +7142,9 @@ function safeSerialize(value) {
6449
7142
  return val;
6450
7143
  });
6451
7144
  }
7145
+ function isDangerousKey(key) {
7146
+ return DANGEROUS_KEYS2.has(key);
7147
+ }
6452
7148
  function sanitizeObject(value, depth = 0) {
6453
7149
  if (depth > MAX_DEPTH) {
6454
7150
  return void 0;
@@ -6459,7 +7155,7 @@ function sanitizeObject(value, depth = 0) {
6459
7155
  if (typeof value !== "object") {
6460
7156
  return value;
6461
7157
  }
6462
- if (ArrayIsArray2(value)) {
7158
+ if (ArrayIsArray3(value)) {
6463
7159
  return mapArraySafely(value, (item) => sanitizeObject(item, depth + 1));
6464
7160
  }
6465
7161
  const result = /* @__PURE__ */ Object.create(null);
@@ -6470,13 +7166,13 @@ function sanitizeObject(value, depth = 0) {
6470
7166
  }
6471
7167
  return result;
6472
7168
  }
6473
- var ReflectGet4, ArrayIsArray2, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
7169
+ var ReflectGet4, ArrayIsArray3, NumberIsFinite3, MathFloor3, MAX_ARRAY_LENGTH, DANGEROUS_KEYS2, MAX_DEPTH;
6474
7170
  var init_safe_deserialize = __esm({
6475
7171
  "libs/core/src/adapters/worker-pool/safe-deserialize.ts"() {
6476
7172
  "use strict";
6477
7173
  init_errors();
6478
7174
  ReflectGet4 = Reflect.get;
6479
- ArrayIsArray2 = Array.isArray;
7175
+ ArrayIsArray3 = Array.isArray;
6480
7176
  NumberIsFinite3 = Number.isFinite;
6481
7177
  MathFloor3 = Math.floor;
6482
7178
  MAX_ARRAY_LENGTH = 1e6;
@@ -7175,6 +7871,75 @@ var init_rate_limiter = __esm({
7175
7871
  }
7176
7872
  });
7177
7873
 
7874
+ // libs/core/src/adapters/worker-pool/result-encoding.ts
7875
+ function decodeResult(value, specialValues) {
7876
+ if (specialValues === void 0) {
7877
+ return value;
7878
+ }
7879
+ if (!Array.isArray(specialValues)) {
7880
+ throw new MessageValidationError("Worker result special values must be an array");
7881
+ }
7882
+ let decoded = value;
7883
+ for (const special of specialValues) {
7884
+ assertSpecialValue(special);
7885
+ const restored = restoreSpecialValue(special);
7886
+ if (special.path.length === 0) {
7887
+ decoded = restored;
7888
+ continue;
7889
+ }
7890
+ const container = resolveContainer(decoded, special.path.slice(0, -1));
7891
+ const key = special.path[special.path.length - 1];
7892
+ if (!container || !Object.hasOwn(container, key) || container[key] !== null) {
7893
+ throw new MessageValidationError("Worker result refers to a value it does not contain");
7894
+ }
7895
+ container[key] = restored;
7896
+ }
7897
+ return decoded;
7898
+ }
7899
+ function assertSpecialValue(special) {
7900
+ const candidate = special;
7901
+ const validPath = Array.isArray(candidate?.path) && candidate.path.every((key) => typeof key === "string" || Number.isInteger(key) && key >= 0);
7902
+ if (!validPath || !SPECIAL_KINDS.has(candidate?.kind)) {
7903
+ throw new MessageValidationError("Worker result has an invalid special value");
7904
+ }
7905
+ }
7906
+ function resolveContainer(root, path2) {
7907
+ let current = root;
7908
+ for (const key of path2) {
7909
+ if (!isDataContainer(current) || isDangerousKey(String(key)) || !Object.hasOwn(current, key)) {
7910
+ return void 0;
7911
+ }
7912
+ current = current[key];
7913
+ }
7914
+ return isDataContainer(current) ? current : void 0;
7915
+ }
7916
+ function isDataContainer(value) {
7917
+ return Array.isArray(value) || typeof value === "object" && value !== null && Object.getPrototypeOf(value) === null;
7918
+ }
7919
+ function restoreSpecialValue(special) {
7920
+ switch (special.kind) {
7921
+ case "date":
7922
+ return new Date(typeof special.time === "number" ? special.time : NaN);
7923
+ case "nan":
7924
+ return NaN;
7925
+ case "infinity":
7926
+ return Infinity;
7927
+ case "-infinity":
7928
+ return -Infinity;
7929
+ case "undefined":
7930
+ return void 0;
7931
+ }
7932
+ }
7933
+ var SPECIAL_KINDS;
7934
+ var init_result_encoding = __esm({
7935
+ "libs/core/src/adapters/worker-pool/result-encoding.ts"() {
7936
+ "use strict";
7937
+ init_errors();
7938
+ init_safe_deserialize();
7939
+ SPECIAL_KINDS = /* @__PURE__ */ new Set(["date", "nan", "infinity", "-infinity", "undefined"]);
7940
+ }
7941
+ });
7942
+
7178
7943
  // libs/core/src/adapters/worker-pool/worker-pool-adapter.ts
7179
7944
  var import_crypto3, WorkerPoolAdapter;
7180
7945
  var init_worker_pool_adapter = __esm({
@@ -7188,7 +7953,9 @@ var init_worker_pool_adapter = __esm({
7188
7953
  init_memory_monitor();
7189
7954
  init_rate_limiter();
7190
7955
  init_safe_deserialize();
7956
+ init_result_encoding();
7191
7957
  init_errors();
7958
+ init_stack_trace();
7192
7959
  WorkerPoolAdapter = class {
7193
7960
  config;
7194
7961
  securityLevel;
@@ -7427,7 +8194,8 @@ var init_worker_pool_adapter = __esm({
7427
8194
  globals: context.config.globals,
7428
8195
  // Security level determines which globals are available in sandbox
7429
8196
  // This mirrors AST guard's allowed globals for defense-in-depth
7430
- securityLevel: this.securityLevel
8197
+ securityLevel: this.securityLevel,
8198
+ toolNamespaces: context.toolNamespaces ? [...context.toolNamespaces] : void 0
7431
8199
  };
7432
8200
  return new Promise((resolve, reject) => {
7433
8201
  const pendingToolCalls = /* @__PURE__ */ new Map();
@@ -7444,7 +8212,7 @@ var init_worker_pool_adapter = __esm({
7444
8212
  } else if (isExecutionResultMessage(msg) && msg.requestId === requestId) {
7445
8213
  cleanup();
7446
8214
  const duration = Date.now() - startTime;
7447
- const result = this.buildResult(msg, duration);
8215
+ const result = this.buildResult(msg, duration, context.config.sanitizeStackTraces);
7448
8216
  resolve(result);
7449
8217
  } else if (isConsoleMessage(msg) && msg.requestId === requestId) {
7450
8218
  this.handleConsoleMessage(msg);
@@ -7485,17 +8253,30 @@ var init_worker_pool_adapter = __esm({
7485
8253
  pendingToolCalls.set(msg.callId, true);
7486
8254
  let result;
7487
8255
  let error;
8256
+ let toolError = false;
7488
8257
  try {
7489
8258
  if (!context.toolHandler) {
7490
8259
  throw new Error("No tool handler configured");
7491
8260
  }
7492
8261
  const sanitizedArgs = sanitizeObject(msg.args);
7493
- result = await context.toolHandler(msg.toolName, sanitizedArgs);
8262
+ toolError = true;
8263
+ const handlerResult = await context.toolHandler(msg.toolName, sanitizedArgs);
8264
+ try {
8265
+ result = sanitizeObject(handlerResult);
8266
+ } catch {
8267
+ throw Object.assign(new Error("Tool returned an unsupported value"), {
8268
+ name: "ToolBridgeError",
8269
+ code: "TOOL_RESULT_NOT_SAFE"
8270
+ });
8271
+ }
8272
+ toolError = false;
7494
8273
  } catch (e) {
7495
8274
  const err = e;
8275
+ const code = e?.code;
7496
8276
  error = {
7497
8277
  name: err.name || "Error",
7498
- message: err.message || "Unknown error"
8278
+ message: err.message || "Unknown error",
8279
+ ...toolError && typeof code === "string" ? { code } : {}
7499
8280
  };
7500
8281
  } finally {
7501
8282
  pendingToolCalls.delete(msg.callId);
@@ -7504,8 +8285,9 @@ var init_worker_pool_adapter = __esm({
7504
8285
  type: "tool-response",
7505
8286
  requestId: msg.requestId,
7506
8287
  callId: msg.callId,
7507
- result: sanitizeObject(result),
7508
- error
8288
+ result,
8289
+ error,
8290
+ ...error && toolError ? { toolError: true } : {}
7509
8291
  });
7510
8292
  }
7511
8293
  handleConsoleMessage(msg) {
@@ -7517,16 +8299,15 @@ var init_worker_pool_adapter = __esm({
7517
8299
  /**
7518
8300
  * Build result from worker message.
7519
8301
  *
7520
- * Note: The `msg.value as T` assertion is inherent to cross-thread
7521
- * serialization boundaries. The worker sanitizes output via sanitizeObject()
7522
- * before sending, but full runtime type validation would require schema
7523
- * definitions which are not available at this layer.
8302
+ * Note: The `as T` assertion is inherent to cross-thread serialization boundaries. The
8303
+ * worker sanitizes the result with sanitizeValue() and sends the values JSON cannot carry
8304
+ * (Dates, NaN, ...) separately; decodeResult() puts them back and refuses a malformed list.
7524
8305
  */
7525
- buildResult(msg, duration) {
8306
+ buildResult(msg, duration, sanitizeStacks) {
7526
8307
  if (msg.success) {
7527
8308
  return {
7528
8309
  success: true,
7529
- value: msg.value,
8310
+ value: decodeResult(msg.value, msg.specialValues),
7530
8311
  stats: {
7531
8312
  duration,
7532
8313
  toolCallCount: msg.stats.toolCallCount,
@@ -7543,7 +8324,8 @@ var init_worker_pool_adapter = __esm({
7543
8324
  name: error.name,
7544
8325
  message: error.message,
7545
8326
  code: error.code,
7546
- stack: error.stack
8327
+ // The worker trims its stack; sanitize it here too so the result obeys the option.
8328
+ stack: sanitizeStackTrace(error.stack, sanitizeStacks)
7547
8329
  },
7548
8330
  stats: {
7549
8331
  duration,
@@ -7745,7 +8527,7 @@ __export(index_exports, {
7745
8527
  module.exports = __toCommonJS(index_exports);
7746
8528
 
7747
8529
  // libs/core/src/enclave.ts
7748
- var import_ast3 = require("@enclave-vm/ast");
8530
+ var import_ast4 = require("@enclave-vm/ast");
7749
8531
 
7750
8532
  // libs/core/src/babel/babel-wrapper.ts
7751
8533
  var vm = __toESM(require("vm"));
@@ -8248,8 +9030,8 @@ function transformMultiple(files, options, limits, singleFileTransform) {
8248
9030
  }
8249
9031
 
8250
9032
  // libs/core/src/enclave.ts
8251
- var import_ast4 = require("@enclave-vm/ast");
8252
9033
  var import_ast5 = require("@enclave-vm/ast");
9034
+ var import_ast6 = require("@enclave-vm/ast");
8253
9035
  var acorn2 = __toESM(require("acorn"));
8254
9036
  var import_astring = require("astring");
8255
9037
 
@@ -8431,6 +9213,7 @@ var DEFAULT_DOUBLE_VM_CONFIG = {
8431
9213
  };
8432
9214
 
8433
9215
  // libs/core/src/globals-validator.ts
9216
+ var import_util = require("util");
8434
9217
  var DANGEROUS_FUNCTION_PATTERNS = [
8435
9218
  /\beval\b/,
8436
9219
  // eval() calls
@@ -8458,7 +9241,55 @@ var DANGEROUS_FUNCTION_PATTERNS = [
8458
9241
  // Synchronous spawn
8459
9242
  ];
8460
9243
  var DANGEROUS_GLOBAL_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
8461
- function validateGlobalValue(key, value, options = {}, path2 = [], visited = /* @__PURE__ */ new WeakSet()) {
9244
+ var MapEntries = Map.prototype.entries;
9245
+ var SetValues = Set.prototype.values;
9246
+ var ReflectApply = Reflect.apply;
9247
+ var ReflectOwnKeys = Reflect.ownKeys;
9248
+ var ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
9249
+ var ObjectGetPrototypeOf = Object.getPrototypeOf;
9250
+ var ArrayPrototype = Array.prototype;
9251
+ var MapPrototype = Map.prototype;
9252
+ var SetPrototype = Set.prototype;
9253
+ var IteratorPrototype = ObjectGetPrototypeOf(ObjectGetPrototypeOf([][Symbol.iterator]()));
9254
+ var AsyncIteratorPrototype = ObjectGetPrototypeOf(
9255
+ ObjectGetPrototypeOf(
9256
+ async function* () {
9257
+ }.prototype
9258
+ )
9259
+ );
9260
+ function describeOpaqueContainer(obj) {
9261
+ if (import_util.types.isPromise(obj)) return "a Promise";
9262
+ if (import_util.types.isWeakMap(obj)) return "a WeakMap";
9263
+ if (import_util.types.isGeneratorObject(obj)) return "a generator";
9264
+ if (import_util.types.isMapIterator(obj) || import_util.types.isSetIterator(obj) || Object.prototype.isPrototypeOf.call(IteratorPrototype, obj) || Object.prototype.isPrototypeOf.call(AsyncIteratorPrototype, obj)) {
9265
+ return "an iterator";
9266
+ }
9267
+ return void 0;
9268
+ }
9269
+ function isPlainDataObject(obj) {
9270
+ const proto = ObjectGetPrototypeOf(obj);
9271
+ return proto === null || proto === Object.prototype || import_util.types.isDate(obj) || import_util.types.isRegExp(obj) || import_util.types.isArrayBufferView(obj) || import_util.types.isAnyArrayBuffer(obj);
9272
+ }
9273
+ function describeInstance(obj) {
9274
+ try {
9275
+ const name = ObjectGetPrototypeOf(obj)?.constructor?.name;
9276
+ if (typeof name === "string" && name) return `a ${name} instance`;
9277
+ } catch {
9278
+ }
9279
+ return "a non-plain object";
9280
+ }
9281
+ function collectionError(key, what, path2) {
9282
+ return new Error(
9283
+ `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.`
9284
+ );
9285
+ }
9286
+ function mapValueSegment(mapKey, index) {
9287
+ if (typeof mapKey === "string" || typeof mapKey === "number" || typeof mapKey === "boolean") {
9288
+ return `get(${JSON.stringify(mapKey)})`;
9289
+ }
9290
+ return `values()[${index}]`;
9291
+ }
9292
+ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /* @__PURE__ */ new WeakSet(), collectionVisited = /* @__PURE__ */ new WeakSet(), inCollection = false) {
8462
9293
  const maxDepth = options.maxDepth ?? 10;
8463
9294
  const allowFunctions = options.allowFunctions ?? false;
8464
9295
  const allowGettersSetters = options.allowGettersSetters ?? false;
@@ -8482,6 +9313,9 @@ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /*
8482
9313
  }
8483
9314
  if (type === "function") {
8484
9315
  const funcName = value.name || "anonymous";
9316
+ if (inCollection && (allowFunctions || allowedFunctionNames.includes(funcName))) {
9317
+ throw collectionError(key, "a function", path2);
9318
+ }
8485
9319
  if (allowedFunctionNames.includes(funcName)) {
8486
9320
  return;
8487
9321
  }
@@ -8508,35 +9342,89 @@ function validateGlobalValue(key, value, options = {}, path2 = [], visited = /*
8508
9342
  }
8509
9343
  if (type === "object") {
8510
9344
  const obj = value;
8511
- if (visited.has(obj)) {
9345
+ const seen = inCollection ? collectionVisited : visited;
9346
+ if (seen.has(obj)) {
8512
9347
  return;
8513
9348
  }
8514
- visited.add(obj);
9349
+ seen.add(obj);
9350
+ const opaque = describeOpaqueContainer(obj);
9351
+ if (opaque) {
9352
+ throw new Error(
9353
+ `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.`
9354
+ );
9355
+ }
9356
+ const isArray = Array.isArray(obj);
9357
+ const isMap = import_util.types.isMap(obj);
9358
+ const isSet = import_util.types.isSet(obj);
9359
+ if (isArray) {
9360
+ const hidden = import_util.types.isProxy(obj) ? "a Proxy array" : ObjectGetPrototypeOf(obj) !== ArrayPrototype ? "an array with a custom prototype" : void 0;
9361
+ if (hidden) {
9362
+ throw new Error(
9363
+ `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.`
9364
+ );
9365
+ }
9366
+ }
9367
+ if (inCollection) {
9368
+ if (import_util.types.isProxy(obj)) {
9369
+ throw collectionError(key, "a Proxy", path2);
9370
+ }
9371
+ if (!isArray && !isMap && !isSet && !isPlainDataObject(obj)) {
9372
+ throw collectionError(key, describeInstance(obj), path2);
9373
+ }
9374
+ if ((isMap || isSet) && ObjectGetPrototypeOf(obj) !== (isMap ? MapPrototype : SetPrototype)) {
9375
+ throw collectionError(key, describeInstance(obj), path2);
9376
+ }
9377
+ }
8515
9378
  if (!allowGettersSetters) {
8516
- const descriptors = Object.getOwnPropertyDescriptors(obj);
8517
- for (const [prop, desc] of Object.entries(descriptors)) {
8518
- if (desc.get || desc.set) {
9379
+ for (const prop of ReflectOwnKeys(obj)) {
9380
+ const desc = ReflectGetOwnPropertyDescriptor(obj, prop);
9381
+ if (desc && (desc.get || desc.set)) {
9382
+ const at = [...path2, typeof prop === "string" ? prop : `[${String(prop)}]`].join(".");
8519
9383
  throw new Error(
8520
- `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.`
9384
+ `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.`
8521
9385
  );
8522
9386
  }
8523
9387
  }
8524
9388
  }
8525
- if (Array.isArray(obj)) {
8526
- for (let i = 0; i < obj.length; i++) {
8527
- validateGlobalValue(key, obj[i], options, [...path2, String(i)], visited);
9389
+ if (isMap) {
9390
+ let index = 0;
9391
+ for (const [mapKey, mapValue] of ReflectApply(MapEntries, obj, [])) {
9392
+ validateGlobalValue(key, mapKey, options, [...path2, `keys()[${index}]`], visited, collectionVisited, true);
9393
+ validateGlobalValue(
9394
+ key,
9395
+ mapValue,
9396
+ options,
9397
+ [...path2, mapValueSegment(mapKey, index)],
9398
+ visited,
9399
+ collectionVisited,
9400
+ true
9401
+ );
9402
+ index++;
9403
+ }
9404
+ } else if (isSet) {
9405
+ let index = 0;
9406
+ for (const element of ReflectApply(SetValues, obj, [])) {
9407
+ validateGlobalValue(key, element, options, [...path2, `values()[${index}]`], visited, collectionVisited, true);
9408
+ index++;
8528
9409
  }
8529
- return;
8530
9410
  }
8531
- const keys = Object.keys(obj);
9411
+ const keys = isArray || inCollection ? ReflectOwnKeys(obj) : Object.keys(obj);
8532
9412
  for (const prop of keys) {
8533
- if (DANGEROUS_GLOBAL_KEYS.has(prop)) {
9413
+ if (typeof prop === "string" && DANGEROUS_GLOBAL_KEYS.has(prop)) {
8534
9414
  throw new Error(
8535
9415
  `Custom global "${key}" contains dangerous key "${prop}" at ${path2.join(".") || "root"}. Keys like "__proto__", "constructor", and "prototype" are not allowed.`
8536
9416
  );
8537
9417
  }
8538
9418
  const propValue = obj[prop];
8539
- validateGlobalValue(key, propValue, options, [...path2, prop], visited);
9419
+ validateGlobalValue(
9420
+ key,
9421
+ propValue,
9422
+ options,
9423
+ [...path2, typeof prop === "string" ? prop : `[${String(prop)}]`],
9424
+ visited,
9425
+ collectionVisited,
9426
+ inCollection || isArray
9427
+ );
8540
9428
  }
8541
9429
  return;
8542
9430
  }
@@ -10429,6 +11317,21 @@ function createScoringGate(config) {
10429
11317
  return new ScoringGate(config);
10430
11318
  }
10431
11319
 
11320
+ // libs/core/src/enclave.ts
11321
+ init_global_function_gate();
11322
+ init_stack_trace();
11323
+
11324
+ // libs/core/src/node-vm.ts
11325
+ var vm2 = __toESM(require("vm"));
11326
+ function assertNodeVmAvailable() {
11327
+ if (typeof vm2.createContext === "function" && typeof vm2.Script === "function") {
11328
+ return;
11329
+ }
11330
+ throw new Error(
11331
+ "@enclave-vm/core needs node:vm, which this runtime does not provide. In a browser, use @enclave-vm/browser; elsewhere, pass a sandboxAdapter (for example new InterpreterAdapter())."
11332
+ );
11333
+ }
11334
+
10432
11335
  // libs/core/src/enclave.ts
10433
11336
  var DEFAULT_SECURITY_LEVEL = "STANDARD";
10434
11337
  var DEFAULT_TOOL_BRIDGE_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
@@ -10484,6 +11387,8 @@ var Enclave = class {
10484
11387
  scoringGate;
10485
11388
  doubleVmConfig;
10486
11389
  customGlobalNames;
11390
+ toolNamespaces;
11391
+ sandboxAdapter;
10487
11392
  adapter;
10488
11393
  constructor(options = {}) {
10489
11394
  this.securityLevel = options.securityLevel ?? DEFAULT_SECURITY_LEVEL;
@@ -10517,7 +11422,7 @@ var Enclave = class {
10517
11422
  };
10518
11423
  const presetName = options.preset ?? "agentscript";
10519
11424
  if (presetName === "babel") {
10520
- const babelConfig = (0, import_ast3.getBabelConfig)(this.securityLevel);
11425
+ const babelConfig = (0, import_ast4.getBabelConfig)(this.securityLevel);
10521
11426
  const restrictedBabel = createRestrictedBabel({
10522
11427
  maxInputSize: babelConfig.maxInputSize,
10523
11428
  maxOutputSize: babelConfig.maxOutputSize,
@@ -10539,6 +11444,12 @@ var Enclave = class {
10539
11444
  }
10540
11445
  };
10541
11446
  }
11447
+ this.toolNamespaces = (0, import_ast6.normalizeToolNamespaces)(options.toolNamespaces, {
11448
+ reservedNames: Object.keys(initialGlobals)
11449
+ });
11450
+ if (options.maxGlobalFunctionCalls !== void 0 && !(Number.isInteger(options.maxGlobalFunctionCalls) && options.maxGlobalFunctionCalls >= 0)) {
11451
+ throw new TypeError("maxGlobalFunctionCalls must be a non-negative integer");
11452
+ }
10542
11453
  this.config = {
10543
11454
  ...BASE_CONFIG,
10544
11455
  timeout: securityConfig.timeout,
@@ -10553,9 +11464,13 @@ var Enclave = class {
10553
11464
  toolBridge: normalizedToolBridge,
10554
11465
  // secureProxyConfig must come AFTER options spread to use the merged config
10555
11466
  secureProxyConfig: securityConfig.secureProxyConfig,
10556
- globals: initialGlobals
11467
+ globals: initialGlobals,
11468
+ maxGlobalFunctionCalls: resolveMaxGlobalFunctionCalls({
11469
+ maxToolCalls: securityConfig.maxToolCalls,
11470
+ maxGlobalFunctionCalls: options.maxGlobalFunctionCalls
11471
+ })
10557
11472
  };
10558
- this.customGlobalNames = Object.keys(initialGlobals);
11473
+ this.customGlobalNames = [...Object.keys(initialGlobals), ...this.toolNamespaces.map((ns) => ns.name)];
10559
11474
  const customAllowedGlobals = this.customGlobalNames.flatMap((name) => [name, `__safe_${name}`]);
10560
11475
  this.validator = this.createValidator(presetName, customAllowedGlobals);
10561
11476
  this.validateCode = options.validate !== false;
@@ -10565,6 +11480,10 @@ var Enclave = class {
10565
11480
  this.scoringGate = new ScoringGate(options.scoringGate);
10566
11481
  }
10567
11482
  this.doubleVmConfig = this.buildDoubleVmConfig(options.doubleVm);
11483
+ if (options.sandboxAdapter !== void 0 && !isSandboxAdapter(options.sandboxAdapter)) {
11484
+ throw new TypeError("sandboxAdapter must have execute(code, context) and dispose() methods");
11485
+ }
11486
+ this.sandboxAdapter = options.sandboxAdapter;
10568
11487
  }
10569
11488
  /**
10570
11489
  * Build double VM configuration from user options
@@ -10599,11 +11518,31 @@ var Enclave = class {
10599
11518
  /**
10600
11519
  * Execute AgentScript code
10601
11520
  *
11521
+ * Every error returned obeys `sanitizeStackTraces`, whichever stage raised it.
11522
+ *
10602
11523
  * @param code AgentScript code to execute
10603
11524
  * @param toolHandler Optional tool handler (overrides constructor config)
10604
11525
  * @returns Execution result
10605
11526
  */
10606
11527
  async run(code, toolHandler) {
11528
+ const result = await this.execute(code, toolHandler);
11529
+ return this.applyStackTracePolicy(result);
11530
+ }
11531
+ /**
11532
+ * Single exit for returned errors: with `sanitizeStackTraces` on, strip host paths, file
11533
+ * locations and frames from the stack, whichever stage (validation, transform, compile,
11534
+ * execution, tool call) and adapter produced the error.
11535
+ */
11536
+ applyStackTracePolicy(result) {
11537
+ if (result.success || !result.error?.stack || !this.config.sanitizeStackTraces) {
11538
+ return result;
11539
+ }
11540
+ return { ...result, error: { ...result.error, stack: sanitizeStackTrace(result.error.stack, true) } };
11541
+ }
11542
+ /**
11543
+ * Transform, validate and execute. `run` applies the stack-trace policy to what this returns.
11544
+ */
11545
+ async execute(code, toolHandler) {
10607
11546
  const startTime = Date.now();
10608
11547
  const stats = {
10609
11548
  duration: 0,
@@ -10616,8 +11555,8 @@ var Enclave = class {
10616
11555
  try {
10617
11556
  let transformedCode = code;
10618
11557
  if (this.transformCode) {
10619
- const needsWrapping = !(0, import_ast4.isWrappedInMain)(code);
10620
- transformedCode = (0, import_ast4.transformAgentScript)(code, {
11558
+ const needsWrapping = !(0, import_ast5.isWrappedInMain)(code);
11559
+ transformedCode = (0, import_ast5.transformAgentScript)(code, {
10621
11560
  wrapInMain: needsWrapping,
10622
11561
  transformCallTool: true,
10623
11562
  transformLoops: true,
@@ -10688,7 +11627,8 @@ ${errorMessages}`,
10688
11627
  toolHandler: toolHandler || this.config.toolHandler,
10689
11628
  sidecar,
10690
11629
  referenceConfig: this.referenceConfig,
10691
- secureProxyConfig: this.config.secureProxyConfig
11630
+ secureProxyConfig: this.config.secureProxyConfig,
11631
+ toolNamespaces: this.toolNamespaces
10692
11632
  };
10693
11633
  const timeoutId = setTimeout(() => {
10694
11634
  context.aborted = true;
@@ -10760,7 +11700,7 @@ ${errorMessages}`,
10760
11700
  const throwOnBlocked = proxyConfig.throwOnBlocked ?? true;
10761
11701
  const parseModule = (source) => acorn2.parse(source, { ecmaVersion: "latest", sourceType: "module" });
10762
11702
  const ast = parseModule(code);
10763
- const { guardedCount } = (0, import_ast5.guardComputedMemberKeys)(ast, parseModule, { blockedKeys, throwOnBlocked });
11703
+ const { guardedCount } = (0, import_ast6.guardComputedMemberKeys)(ast, parseModule, { blockedKeys, throwOnBlocked });
10764
11704
  if (guardedCount === 0) {
10765
11705
  return code;
10766
11706
  }
@@ -10771,8 +11711,8 @@ ${errorMessages}`,
10771
11711
  ecmaVersion: "latest",
10772
11712
  sourceType: "module"
10773
11713
  });
10774
- (0, import_ast5.transformConcatenation)(ast);
10775
- (0, import_ast5.transformTemplateLiterals)(ast);
11714
+ (0, import_ast6.transformConcatenation)(ast);
11715
+ (0, import_ast6.transformTemplateLiterals)(ast);
10776
11716
  return (0, import_astring.generate)(ast);
10777
11717
  }
10778
11718
  /**
@@ -10790,21 +11730,22 @@ ${errorMessages}`,
10790
11730
  sourceType: "module"
10791
11731
  });
10792
11732
  if (this.referenceConfig?.extractionThreshold) {
10793
- (0, import_ast5.extractLargeStrings)(ast, {
11733
+ (0, import_ast6.extractLargeStrings)(ast, {
10794
11734
  threshold: this.referenceConfig.extractionThreshold,
10795
11735
  onExtract: (value) => {
10796
11736
  return sidecar.store(value, "extraction");
10797
11737
  }
10798
11738
  });
10799
11739
  }
10800
- (0, import_ast5.transformConcatenation)(ast);
10801
- (0, import_ast5.transformTemplateLiterals)(ast);
11740
+ (0, import_ast6.transformConcatenation)(ast);
11741
+ (0, import_ast6.transformTemplateLiterals)(ast);
10802
11742
  return (0, import_astring.generate)(ast);
10803
11743
  }
10804
11744
  /**
10805
11745
  * Get or create the sandbox adapter
10806
11746
  *
10807
- * When double VM is enabled (default), the base adapter is wrapped
11747
+ * A host-supplied `sandboxAdapter` is used as is. Otherwise, when double VM is enabled
11748
+ * (default), the base adapter is wrapped
10808
11749
  * with a double VM layer that provides:
10809
11750
  * - Nested VM isolation (Parent VM + Inner VM)
10810
11751
  * - Enhanced tool call validation
@@ -10812,9 +11753,15 @@ ${errorMessages}`,
10812
11753
  * - Defense-in-depth against VM escape attacks
10813
11754
  */
10814
11755
  async getAdapter() {
11756
+ if (this.sandboxAdapter) {
11757
+ return this.sandboxAdapter;
11758
+ }
10815
11759
  if (this.adapter) {
10816
11760
  return this.adapter;
10817
11761
  }
11762
+ if (this.doubleVmConfig.enabled || this.config.adapter === "vm") {
11763
+ assertNodeVmAvailable();
11764
+ }
10818
11765
  if (this.doubleVmConfig.enabled) {
10819
11766
  const { wrapWithDoubleVm: wrapWithDoubleVm3 } = await Promise.resolve().then(() => (init_double_vm(), double_vm_exports));
10820
11767
  this.adapter = wrapWithDoubleVm3(void 0, this.doubleVmConfig, this.securityLevel);
@@ -10877,7 +11824,7 @@ ${errorMessages}`,
10877
11824
  * @returns A configured JSAstValidator
10878
11825
  */
10879
11826
  createValidator(presetName, customAllowedGlobals) {
10880
- const securityLevelGlobals = (0, import_ast3.getAgentScriptGlobals)(this.securityLevel);
11827
+ const securityLevelGlobals = (0, import_ast4.getAgentScriptGlobals)(this.securityLevel);
10881
11828
  const enclaveSpecificGlobals = [
10882
11829
  "parallel",
10883
11830
  // Parallel execution API
@@ -10891,24 +11838,24 @@ ${errorMessages}`,
10891
11838
  const allAllowedGlobals = [...securityLevelGlobals, ...enclaveSpecificGlobals, ...customAllowedGlobals];
10892
11839
  switch (presetName) {
10893
11840
  case "agentscript":
10894
- return new import_ast3.JSAstValidator(
10895
- (0, import_ast3.createAgentScriptPreset)({
11841
+ return new import_ast4.JSAstValidator(
11842
+ (0, import_ast4.createAgentScriptPreset)({
10896
11843
  securityLevel: this.securityLevel,
10897
11844
  allowedGlobals: allAllowedGlobals,
10898
11845
  allowDynamicArrayFill: this.config.memoryLimit > 0
10899
11846
  })
10900
11847
  );
10901
11848
  case "strict":
10902
- return new import_ast3.JSAstValidator((0, import_ast3.createStrictPreset)());
11849
+ return new import_ast4.JSAstValidator((0, import_ast4.createStrictPreset)());
10903
11850
  case "secure":
10904
- return new import_ast3.JSAstValidator((0, import_ast3.createSecurePreset)());
11851
+ return new import_ast4.JSAstValidator((0, import_ast4.createSecurePreset)());
10905
11852
  case "standard":
10906
- return new import_ast3.JSAstValidator((0, import_ast3.createStandardPreset)());
11853
+ return new import_ast4.JSAstValidator((0, import_ast4.createStandardPreset)());
10907
11854
  case "permissive":
10908
- return new import_ast3.JSAstValidator((0, import_ast3.createPermissivePreset)());
11855
+ return new import_ast4.JSAstValidator((0, import_ast4.createPermissivePreset)());
10909
11856
  case "babel":
10910
- return new import_ast3.JSAstValidator(
10911
- (0, import_ast3.createBabelPreset)({
11857
+ return new import_ast4.JSAstValidator(
11858
+ (0, import_ast4.createBabelPreset)({
10912
11859
  securityLevel: this.securityLevel,
10913
11860
  allowedGlobals: allAllowedGlobals,
10914
11861
  allowDynamicArrayFill: this.config.memoryLimit > 0
@@ -10957,6 +11904,10 @@ ${errorMessages}`,
10957
11904
  return uniqueErrors.join("\n");
10958
11905
  }
10959
11906
  };
11907
+ function isSandboxAdapter(value) {
11908
+ const candidate = value;
11909
+ return typeof candidate === "object" && candidate !== null && typeof candidate.execute === "function" && typeof candidate.dispose === "function";
11910
+ }
10960
11911
  async function runAgentScript(code, options = {}) {
10961
11912
  const enclave = new Enclave(options);
10962
11913
  try {
@@ -11566,6 +12517,7 @@ function applyBinary(op, l, r) {
11566
12517
  }
11567
12518
 
11568
12519
  // libs/core/src/adapters/interpreter-adapter.ts
12520
+ init_stack_trace();
11569
12521
  var SAFE_GLOBALS = Object.freeze({ Math, JSON });
11570
12522
  var DEFAULT_MAX_STEPS = 5e6;
11571
12523
  var DEFAULT_MAX_CALL_DEPTH = 256;
@@ -11576,6 +12528,7 @@ var InterpreterAdapter = class {
11576
12528
  async execute(code, context) {
11577
12529
  const startTime = Date.now();
11578
12530
  let toolCallCount = 0;
12531
+ const sanitizeStacks = context.config.sanitizeStackTraces === true;
11579
12532
  const maxToolCalls = context.config.maxToolCalls ?? Number.POSITIVE_INFINITY;
11580
12533
  const toolHandler = context.toolHandler ?? context.config.toolHandler;
11581
12534
  const __safe_callTool = async (name, args) => {
@@ -11592,7 +12545,7 @@ var InterpreterAdapter = class {
11592
12545
  try {
11593
12546
  program = acorn3.parse(code, { ecmaVersion: "latest", sourceType: "script" });
11594
12547
  } catch (error) {
11595
- return this.fail(error, startTime, toolCallCount, 0, "SyntaxError");
12548
+ return this.fail(error, startTime, toolCallCount, 0, sanitizeStacks, "SyntaxError");
11596
12549
  }
11597
12550
  const timeout = context.config.timeout;
11598
12551
  const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
@@ -11617,6 +12570,7 @@ var InterpreterAdapter = class {
11617
12570
  startTime,
11618
12571
  toolCallCount,
11619
12572
  interpreter.stepCount,
12573
+ sanitizeStacks,
11620
12574
  "TimeoutError",
11621
12575
  "EXECUTION_TIMEOUT"
11622
12576
  );
@@ -11628,7 +12582,7 @@ var InterpreterAdapter = class {
11628
12582
  };
11629
12583
  } catch (error) {
11630
12584
  const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
11631
- return this.fail(error, startTime, toolCallCount, interpreter.stepCount, void 0, code2);
12585
+ return this.fail(error, startTime, toolCallCount, interpreter.stepCount, sanitizeStacks, void 0, code2);
11632
12586
  } finally {
11633
12587
  if (timer) clearTimeout(timer);
11634
12588
  if (timeoutHandle) clearTimeout(timeoutHandle);
@@ -11640,12 +12594,13 @@ var InterpreterAdapter = class {
11640
12594
  const endTime = Date.now();
11641
12595
  return { duration: endTime - startTime, toolCallCount, iterationCount, startTime, endTime };
11642
12596
  }
11643
- fail(error, startTime, toolCallCount, iterationCount, name, code) {
12597
+ fail(error, startTime, toolCallCount, iterationCount, sanitizeStacks, name, code) {
11644
12598
  const err = error instanceof Error ? error : new Error(String(error));
12599
+ const stack = sanitizeStackTrace(err.stack, sanitizeStacks);
11645
12600
  const execError = {
11646
12601
  message: err.message,
11647
12602
  name: name ?? err.name,
11648
- ...err.stack ? { stack: err.stack } : {},
12603
+ ...stack ? { stack } : {},
11649
12604
  ...code ? { code } : {}
11650
12605
  };
11651
12606
  return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };