@enclave-vm/core 2.19.2 → 2.20.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -192,6 +192,7 @@ var vm2 = __toESM(require("vm"));
192
192
 
193
193
  // libs/core/src/value-sanitizer.ts
194
194
  var DANGEROUS_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
195
+ var CIRCULAR_MARKER_BYTES = 12;
195
196
  var ReflectApply = Reflect.apply;
196
197
  var ReflectGet2 = Reflect.get;
197
198
  var ArrayIsArray2 = Array.isArray;
@@ -337,9 +338,12 @@ function sanitizeObjectValue(value, options, depth, context) {
337
338
  const sanitizedMap = ObjectCreate(null);
338
339
  const entries = ReflectApply(MapProtoEntries, inspected, []);
339
340
  for (const [key, val] of entries) {
341
+ context.propCount.count++;
342
+ if (context.propCount.count > maxProperties) {
343
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
344
+ }
340
345
  if (typeof key !== "string") continue;
341
346
  if (DANGEROUS_KEYS2.has(key)) continue;
342
- context.propCount.count++;
343
347
  sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
344
348
  }
345
349
  return sanitizedMap;
@@ -349,6 +353,9 @@ function sanitizeObjectValue(value, options, depth, context) {
349
353
  const result = [];
350
354
  for (const item of iter) {
351
355
  context.propCount.count++;
356
+ if (context.propCount.count > maxProperties) {
357
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
358
+ }
352
359
  result.push(sanitizeValue(item, options, depth + 1, context));
353
360
  }
354
361
  return result;
@@ -436,7 +443,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
436
443
  }
437
444
  if (ArrayIsArray2(value)) {
438
445
  if (currentPath.has(value)) {
439
- return 4;
446
+ return CIRCULAR_MARKER_BYTES;
440
447
  }
441
448
  currentPath.add(value);
442
449
  try {
@@ -462,7 +469,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
462
469
  if (type === "object") {
463
470
  const object = value;
464
471
  if (currentPath.has(object)) {
465
- return 4;
472
+ return CIRCULAR_MARKER_BYTES;
466
473
  }
467
474
  if (!isPlainObject(object)) {
468
475
  if (hasBrand(DateProtoGetTime, object)) {
@@ -554,6 +561,75 @@ function checkSerializedSize(value, maxBytes) {
554
561
  }
555
562
  }
556
563
 
564
+ // libs/core/src/bounded-json.ts
565
+ var JSONStringify = JSON.stringify;
566
+ var ReflectApply2 = Reflect.apply;
567
+ var ArrayIsArray3 = Array.isArray;
568
+ var StringValueOf = String.prototype.valueOf;
569
+ var NumberValueOf = Number.prototype.valueOf;
570
+ var JsonTooLargeError = class extends Error {
571
+ constructor(limit) {
572
+ super(`JSON text exceeds ${limit} bytes`);
573
+ this.name = "JsonTooLargeError";
574
+ }
575
+ };
576
+ var JsonTraversalLimitError = class extends Error {
577
+ constructor(limit) {
578
+ super(`JSON traversal exceeds ${limit} members`);
579
+ this.name = "JsonTraversalLimitError";
580
+ }
581
+ };
582
+ function hasSlot(valueOf, value) {
583
+ try {
584
+ ReflectApply2(valueOf, value, []);
585
+ return true;
586
+ } catch {
587
+ return false;
588
+ }
589
+ }
590
+ function stringifyWithin(value, limit) {
591
+ let bytes = 0;
592
+ let visits = 0;
593
+ const maxVisits = Math.max(1e4, Math.min(1e6, limit * 10));
594
+ let root = true;
595
+ return JSONStringify(value, function(key, member) {
596
+ if (++visits > maxVisits) throw new JsonTraversalLimitError(maxVisits);
597
+ if (member !== null && typeof member === "object") {
598
+ if (hasSlot(StringValueOf, member)) member = String(member);
599
+ else if (hasSlot(NumberValueOf, member)) member = Number(member);
600
+ }
601
+ let added;
602
+ switch (typeof member) {
603
+ case "string":
604
+ added = member.length + 2;
605
+ break;
606
+ case "number":
607
+ added = Number.isFinite(member) ? String(member).length : 4;
608
+ break;
609
+ case "boolean":
610
+ added = member ? 4 : 5;
611
+ break;
612
+ case "object":
613
+ case "bigint":
614
+ added = member === null ? 4 : 2;
615
+ break;
616
+ default:
617
+ added = 0;
618
+ }
619
+ if (!root) {
620
+ if (ArrayIsArray3(this)) added = added || 4;
621
+ else if (added > 0) added += key.length + 3;
622
+ }
623
+ root = false;
624
+ bytes += added;
625
+ if (bytes > limit) throw new JsonTooLargeError(limit);
626
+ return member;
627
+ });
628
+ }
629
+ function utf8Length(value) {
630
+ return Buffer.byteLength(value, "utf8");
631
+ }
632
+
557
633
  // libs/core/src/safe-error.ts
558
634
  var safeErrors = /* @__PURE__ */ new WeakSet();
559
635
  function isSafeError(value) {
@@ -620,7 +696,7 @@ function createSafeTypeError(message) {
620
696
  }
621
697
 
622
698
  // libs/core/src/stack-reserve.ts
623
- var ReflectApply2 = Reflect.apply;
699
+ var ReflectApply3 = Reflect.apply;
624
700
  var HOST_STACK_RESERVE_BYTES = 128 * 1024;
625
701
  var STACK_EXHAUSTED_MESSAGE = "Maximum call stack size exceeded";
626
702
  var SLOTS = [];
@@ -631,7 +707,7 @@ function nothing() {
631
707
  }
632
708
  function hasHostStackReserve() {
633
709
  try {
634
- ReflectApply2(nothing, void 0, SLOTS);
710
+ ReflectApply3(nothing, void 0, SLOTS);
635
711
  return true;
636
712
  } catch {
637
713
  return false;
@@ -639,11 +715,11 @@ function hasHostStackReserve() {
639
715
  }
640
716
 
641
717
  // libs/core/src/global-function-gate.ts
642
- var ReflectApply3 = Reflect.apply;
718
+ var ReflectApply4 = Reflect.apply;
643
719
  var ReflectOwnKeys = Reflect.ownKeys;
644
720
  var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
645
721
  var ObjectGetPrototypeOf2 = Object.getPrototypeOf;
646
- var ArrayIsArray3 = Array.isArray;
722
+ var ArrayIsArray4 = Array.isArray;
647
723
  var JsonStringify = JSON.stringify;
648
724
  var BUILTIN_PROTOTYPES = (() => {
649
725
  const typedArrays = [
@@ -799,7 +875,7 @@ function withoutFunctionSource(text, fn) {
799
875
  if (typeof fn !== "function") return text;
800
876
  let source;
801
877
  try {
802
- source = ReflectApply3(FunctionPrototypeToString, fn, []);
878
+ source = ReflectApply4(FunctionPrototypeToString, fn, []);
803
879
  } catch {
804
880
  return text;
805
881
  }
@@ -895,7 +971,7 @@ function isThenable(value) {
895
971
  }
896
972
  }
897
973
  function sanitizeArguments(args, limits, unwrap) {
898
- if (!ArrayIsArray3(args)) return [];
974
+ if (!ArrayIsArray4(args)) return [];
899
975
  const sanitized = sanitizeValue(args, {
900
976
  maxDepth: limits.maxDepth,
901
977
  maxProperties: limits.maxProperties,
@@ -903,7 +979,7 @@ function sanitizeArguments(args, limits, unwrap) {
903
979
  allowErrors: true,
904
980
  unwrap
905
981
  });
906
- return ArrayIsArray3(sanitized) ? sanitized : [];
982
+ return ArrayIsArray4(sanitized) ? sanitized : [];
907
983
  }
908
984
  function invokeGlobalFunction(fn, thisArg, args, limits, unwrap, activity) {
909
985
  if (typeof fn !== "function") {
@@ -925,7 +1001,7 @@ function invokeGlobalFunction(fn, thisArg, args, limits, unwrap, activity) {
925
1001
  }
926
1002
  let result;
927
1003
  try {
928
- result = activity?.inHostContext ? activity.inHostContext(() => ReflectApply3(fn, thisArg, safeArgs)) : ReflectApply3(fn, thisArg, safeArgs);
1004
+ result = activity?.inHostContext ? activity.inHostContext(() => ReflectApply4(fn, thisArg, safeArgs)) : ReflectApply4(fn, thisArg, safeArgs);
929
1005
  } catch (error) {
930
1006
  return failure(error, thisArg);
931
1007
  }
@@ -995,12 +1071,17 @@ var ReflectSet = Reflect.set;
995
1071
  var ReflectDefineProperty = Reflect.defineProperty;
996
1072
  var ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
997
1073
  var ReflectOwnKeys2 = Reflect.ownKeys;
998
- var ReflectApply4 = Reflect.apply;
1074
+ var ReflectApply5 = Reflect.apply;
999
1075
  var ReflectHas = Reflect.has;
1000
1076
  var ReflectConstruct = Reflect.construct;
1001
1077
  var ObjectGetPrototypeOf3 = Object.getPrototypeOf;
1002
1078
  var HostObjectPrototype = Object.prototype;
1003
1079
  var ReflectObject = Reflect;
1080
+ function isArrayIndexKey(property) {
1081
+ if (typeof property !== "string") return false;
1082
+ const index = Number(property);
1083
+ return index >>> 0 === index && index !== 4294967295 && String(index) === property;
1084
+ }
1004
1085
  var PINNED_REFLECT_VALUES = /* @__PURE__ */ new Map();
1005
1086
  for (const key of ReflectOwnKeys2(ReflectObject)) {
1006
1087
  PINNED_REFLECT_VALUES.set(key, ReflectGet3(ReflectObject, key));
@@ -1261,7 +1342,17 @@ function isOfBuiltinKind(receiver, homes) {
1261
1342
  }
1262
1343
  return false;
1263
1344
  }
1345
+ var TypedArrayPrototype = ObjectGetPrototypeOf3(Uint8Array.prototype);
1346
+ var COMPARING_BUILTINS = /* @__PURE__ */ new Set([
1347
+ Array.prototype.includes,
1348
+ Array.prototype.indexOf,
1349
+ Array.prototype.lastIndexOf,
1350
+ TypedArrayPrototype["includes"],
1351
+ TypedArrayPrototype["indexOf"],
1352
+ TypedArrayPrototype["lastIndexOf"]
1353
+ ]);
1264
1354
  function passesHostValuesToCallbacks(fn, builtinMethod) {
1355
+ if (COMPARING_BUILTINS.has(fn)) return false;
1265
1356
  return builtinMethod || fn === JsonParse || fn === JsonStringify2 || typeof fn === "function" && boundBuiltinMethods.has(fn);
1266
1357
  }
1267
1358
  function isProxyable(value) {
@@ -1269,7 +1360,7 @@ function isProxyable(value) {
1269
1360
  }
1270
1361
  function builtinTag(value) {
1271
1362
  try {
1272
- return ReflectApply4(ObjectToString, value, []);
1363
+ return ReflectApply5(ObjectToString, value, []);
1273
1364
  } catch {
1274
1365
  return "";
1275
1366
  }
@@ -1345,10 +1436,11 @@ function createSecureProxy(target, options = {}) {
1345
1436
  };
1346
1437
  const guardObjectArgument = (value) => {
1347
1438
  if (value === null || typeof value !== "object") return value;
1348
- if (proxySet.has(value) || guardedArguments.has(value) || Array.isArray(value)) return value;
1439
+ if (proxySet.has(value) || guardedArguments.has(value)) return value;
1349
1440
  if (heldBySandbox && heldBySandbox(value)) return value;
1350
1441
  const existing = lookupGuard(value);
1351
1442
  if (existing) return existing;
1443
+ if (Array.isArray(value)) return guardArrayArgument(value);
1352
1444
  const original = value;
1353
1445
  const guard = new Proxy(/* @__PURE__ */ Object.create(null), {
1354
1446
  get: (_shell, property) => guardMember(ReflectGet3(original, property, original), original),
@@ -1373,17 +1465,35 @@ function createSecureProxy(target, options = {}) {
1373
1465
  guardedArguments.set(guard, original);
1374
1466
  return guard;
1375
1467
  };
1468
+ const guardArrayArgument = (original) => {
1469
+ const guard = new Proxy(original, {
1470
+ get: (target2, property) => {
1471
+ const member = ReflectGet3(target2, property, target2);
1472
+ return property === "length" || isArrayIndexKey(property) ? member : guardMember(member, target2);
1473
+ },
1474
+ // What a host function stores in the array is a host value like any other
1475
+ set: (target2, property, stored) => ReflectSet(target2, property, toSandbox(stored), target2),
1476
+ defineProperty: (target2, property, descriptor) => {
1477
+ if ("get" in descriptor || "set" in descriptor) return false;
1478
+ const stored = "value" in descriptor ? { ...descriptor, value: toSandbox(descriptor.value) } : descriptor;
1479
+ return ReflectDefineProperty(target2, property, stored);
1480
+ }
1481
+ });
1482
+ storeGuard(original, guard);
1483
+ guardedArguments.set(guard, original);
1484
+ return guard;
1485
+ };
1376
1486
  const guardMember = (member, holder) => {
1377
1487
  if (typeof member !== "function") return guardObjectArgument(member);
1378
1488
  const method = function guardedMethod(...hostArgs) {
1379
- return guardArgument(ReflectApply4(member, holder, hostArgs.map(toSandbox)));
1489
+ return guardArgument(ReflectApply5(member, holder, hostArgs.map(toSandbox)));
1380
1490
  };
1381
1491
  guardedArguments.set(method, member);
1382
1492
  return method;
1383
1493
  };
1384
1494
  const guardCallback = (callback) => {
1385
1495
  const guarded = function guardedCallback(...hostArgs) {
1386
- return ReflectApply4(callback, toSandbox(this), hostArgs.map(toSandbox));
1496
+ return ReflectApply5(callback, toSandbox(this), hostArgs.map(toSandbox));
1387
1497
  };
1388
1498
  guardedArguments.set(guarded, callback);
1389
1499
  return guarded;
@@ -1437,7 +1547,7 @@ function createSecureProxy(target, options = {}) {
1437
1547
  if (typeof value === "function") {
1438
1548
  const tag = builtinTag(target2);
1439
1549
  if (INTERNAL_SLOT_TYPES.has(tag)) {
1440
- const boundMethod = ReflectApply4(FunctionBind, value, [target2]);
1550
+ const boundMethod = ReflectApply5(FunctionBind, value, [target2]);
1441
1551
  if (isBuiltinMethod(value)) {
1442
1552
  boundBuiltinMethods.add(boundMethod);
1443
1553
  }
@@ -1583,7 +1693,7 @@ function createSecureProxy(target, options = {}) {
1583
1693
  }
1584
1694
  let result;
1585
1695
  try {
1586
- result = ReflectApply4(
1696
+ result = ReflectApply5(
1587
1697
  target2,
1588
1698
  unwrappedThis,
1589
1699
  passesHostValuesToCallbacks(target2, builtinMethod) ? guardCallbackArguments(argArray) : argArray
@@ -2057,28 +2167,38 @@ var ReferenceResolver = class {
2057
2167
  /**
2058
2168
  * Check if a value contains any reference IDs
2059
2169
  *
2170
+ * Every value is looked at, at any depth: a reference or composite past `maxResolutionDepth`
2171
+ * cannot be resolved, and it must still be found, so that `resolve()` refuses the call rather
2172
+ * than the handler receiving it unresolved. The value is walked with a list instead of by
2173
+ * recursion, so a deep value cannot exhaust the stack, and an object is looked at once.
2174
+ *
2060
2175
  * @param value - The value to check
2061
- * @param depth - Current recursion depth (internal)
2176
+ * @param _depth - Unused; kept for callers that pass a depth
2062
2177
  * @returns true if the value or any nested value is a reference
2063
2178
  */
2064
- containsReferences(value, depth = 0) {
2065
- if (depth > this.config.maxResolutionDepth) {
2066
- return false;
2067
- }
2068
- if (isReferenceId(value) || isCompositeHandle(value)) {
2069
- return true;
2070
- }
2071
- if (Array.isArray(value)) {
2072
- const len = untrustedLength(value);
2073
- for (let i = 0; i < len; i++) {
2074
- if (this.containsReferences(untrustedAt(value, i), depth + 1)) {
2075
- return true;
2179
+ containsReferences(value, _depth = 0) {
2180
+ const pending = [value];
2181
+ const seen = /* @__PURE__ */ new Set();
2182
+ while (pending.length > 0) {
2183
+ const current = pending.pop();
2184
+ if (isReferenceId(current) || isCompositeHandle(current)) {
2185
+ return true;
2186
+ }
2187
+ if (current === null || typeof current !== "object" || seen.has(current)) {
2188
+ continue;
2189
+ }
2190
+ seen.add(current);
2191
+ if (Array.isArray(current)) {
2192
+ const len = untrustedLength(current);
2193
+ for (let i = 0; i < len; i++) {
2194
+ pending.push(untrustedAt(current, i));
2076
2195
  }
2196
+ continue;
2197
+ }
2198
+ const members = Object.values(current);
2199
+ for (let i = 0; i < members.length; i++) {
2200
+ pending.push(members[i]);
2077
2201
  }
2078
- return false;
2079
- }
2080
- if (value !== null && typeof value === "object") {
2081
- return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
2082
2202
  }
2083
2203
  return false;
2084
2204
  }
@@ -2631,6 +2751,7 @@ function createHostToolBridge(executionContext, options) {
2631
2751
  "Tool returned an unsupported value",
2632
2752
  "TOOL_RESULT_NOT_SAFE"
2633
2753
  );
2754
+ executionContext.onToolBridgeFailure?.();
2634
2755
  return serializeResponse(
2635
2756
  {
2636
2757
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -2640,6 +2761,34 @@ function createHostToolBridge(executionContext, options) {
2640
2761
  maxPayloadBytes
2641
2762
  );
2642
2763
  }
2764
+ const resultLimit = executionContext.maxToolResultBytes;
2765
+ if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
2766
+ let tooLarge = false;
2767
+ let tooComplex = false;
2768
+ try {
2769
+ const resultJson = stringifyWithin(sanitizedResult, resultLimit);
2770
+ tooLarge = resultJson !== void 0 && utf8ByteLength2(resultJson) > resultLimit;
2771
+ } catch (error) {
2772
+ tooLarge = error instanceof JsonTooLargeError;
2773
+ tooComplex = error instanceof JsonTraversalLimitError;
2774
+ }
2775
+ if (tooLarge || tooComplex) {
2776
+ executionContext.onToolBridgeFailure?.();
2777
+ return serializeResponse(
2778
+ {
2779
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
2780
+ ok: false,
2781
+ error: {
2782
+ name: "ToolBridgeError",
2783
+ message: tooComplex ? "Tool result exceeds the traversal limit" : `Tool result exceeds the limit of ${resultLimit} bytes`,
2784
+ code: tooComplex ? "TOOL_RESULT_TOO_COMPLEX" : "TOOL_RESULT_TOO_LARGE",
2785
+ toolError: true
2786
+ }
2787
+ },
2788
+ maxPayloadBytes
2789
+ );
2790
+ }
2791
+ }
2643
2792
  if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
2644
2793
  const size = utf8ByteLength2(sanitizedResult);
2645
2794
  if (size >= referenceConfig.extractionThreshold) {
@@ -2647,6 +2796,20 @@ function createHostToolBridge(executionContext, options) {
2647
2796
  const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
2648
2797
  sanitizedResult = refId;
2649
2798
  } catch {
2799
+ executionContext.onToolBridgeFailure?.();
2800
+ return serializeResponse(
2801
+ {
2802
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
2803
+ ok: false,
2804
+ error: {
2805
+ name: "ToolBridgeError",
2806
+ message: "Tool result could not be stored in the reference sidecar",
2807
+ code: "TOOL_RESULT_NOT_STORED",
2808
+ toolError: true
2809
+ }
2810
+ },
2811
+ maxPayloadBytes
2812
+ );
2650
2813
  }
2651
2814
  }
2652
2815
  }
@@ -2661,6 +2824,7 @@ function createHostToolBridge(executionContext, options) {
2661
2824
  "Tool result must be JSON-serializable",
2662
2825
  "TOOL_RESULT_NOT_JSON"
2663
2826
  );
2827
+ executionContext.onToolBridgeFailure?.();
2664
2828
  return serializeResponse(
2665
2829
  {
2666
2830
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -2671,6 +2835,7 @@ function createHostToolBridge(executionContext, options) {
2671
2835
  );
2672
2836
  }
2673
2837
  if (utf8ByteLength2(okJson) > maxPayloadBytes) {
2838
+ executionContext.onToolBridgeFailure?.();
2674
2839
  return serializeResponse(
2675
2840
  {
2676
2841
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -2877,15 +3042,73 @@ var CONSOLE_FACTORY_SOURCE = `
2877
3042
  var toText = ''.constructor;
2878
3043
  var freeze = Object.freeze;
2879
3044
  var RealmError = Error;
3045
+ var apply = Reflect.apply;
3046
+ var isArray = Array.isArray;
3047
+ var stringValueOf = ''.constructor.prototype.valueOf;
3048
+ var numberValueOf = (0).constructor.prototype.valueOf;
3049
+
3050
+ // Whether a value has the internal slot that a built-in's valueOf reads.
3051
+ function hasSlot(valueOf, value) {
3052
+ try {
3053
+ apply(valueOf, value, []);
3054
+ return true;
3055
+ } catch (e) {
3056
+ return false;
3057
+ }
3058
+ }
3059
+
3060
+ // The JSON text of a value, given up as soon as it would be longer than limit characters. A
3061
+ // value referenced many times is written as many times, so the text can be far longer than the
3062
+ // value is large. What each member adds is counted as JSON.stringify writes it, and the count
3063
+ // is a lower bound of its length (an escape only adds), so a text within the limit is never
3064
+ // given up. The members JSON.stringify visits are counted as well, also those it leaves out (a
3065
+ // function, undefined): at most as many as the limit has characters.
3066
+ var TOO_LARGE = {};
3067
+ function stringifyWithin(value, limit) {
3068
+ var length = 0;
3069
+ var visits = 0;
3070
+ var root = true;
3071
+ return stringify(value, function (key, member) {
3072
+ if (++visits > limit) throw TOO_LARGE;
3073
+ // A String or Number object is written as what it converts to; converted here, the way
3074
+ // JSON.stringify converts it and once, so the count is of what is written.
3075
+ if (member !== null && typeof member === 'object') {
3076
+ if (hasSlot(stringValueOf, member)) member = toText(member);
3077
+ else if (hasSlot(numberValueOf, member)) member = +member;
3078
+ }
3079
+ var added;
3080
+ var kind = typeof member;
3081
+ if (kind === 'string') added = member.length + 2;
3082
+ else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
3083
+ else if (kind === 'boolean') added = member ? 4 : 5;
3084
+ else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
3085
+ else added = 0;
3086
+ if (!root) {
3087
+ // An element of an array is written, as null if nothing else; a member of an object
3088
+ // that is written has its key in front of it.
3089
+ if (isArray(this)) added = added || 4;
3090
+ else if (added > 0) added += key.length + 3;
3091
+ }
3092
+ root = false;
3093
+ length += added;
3094
+ if (length > limit) throw TOO_LARGE;
3095
+ return member;
3096
+ });
3097
+ }
2880
3098
 
2881
- function formatArgument(value) {
3099
+ // An argument as it is written in the line, in at most room characters for an object: an
3100
+ // object is written only when the line has room left, and its text within that room. TOO_LARGE
3101
+ // when it does not fit.
3102
+ function formatArgument(value, room) {
2882
3103
  if (value === undefined) return 'undefined';
2883
3104
  if (value === null) return 'null';
2884
3105
  if (typeof value === 'object') {
3106
+ if (room <= 0) throw TOO_LARGE;
2885
3107
  try {
2886
- var json = stringify(value);
3108
+ var json = stringifyWithin(value, room);
2887
3109
  return json === undefined ? '' : json;
2888
3110
  } catch (e) {
3111
+ if (e === TOO_LARGE) throw e;
2889
3112
  return toText(value);
2890
3113
  }
2891
3114
  }
@@ -2896,19 +3119,38 @@ var CONSOLE_FACTORY_SOURCE = `
2896
3119
  var callCount = 0;
2897
3120
  var totalBytes = 0;
2898
3121
 
3122
+ function tooLarge() {
3123
+ return new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
3124
+ }
3125
+
2899
3126
  function method(level) {
2900
3127
  return (...args) => {
2901
3128
  callCount++;
2902
3129
  if (callCount > maxCalls) {
2903
3130
  throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
2904
3131
  }
3132
+ // The line is measured as it is built: what an argument may add is the room the limit
3133
+ // leaves, so the work done on a line that does not fit is in proportion to the limit.
2905
3134
  var line = '';
2906
3135
  for (var i = 0; i < args.length; i++) {
2907
- line += (i === 0 ? '' : ' ') + formatArgument(args[i]);
3136
+ var separator = i === 0 ? '' : ' ';
3137
+ var text;
3138
+ try {
3139
+ text = formatArgument(args[i], maxBytes - totalBytes - line.length - separator.length);
3140
+ } catch (e) {
3141
+ if (e !== TOO_LARGE) throw e;
3142
+ totalBytes = maxBytes + 1;
3143
+ throw tooLarge();
3144
+ }
3145
+ line += separator + text;
3146
+ if (totalBytes + line.length > maxBytes) {
3147
+ totalBytes = maxBytes + 1;
3148
+ throw tooLarge();
3149
+ }
2908
3150
  }
2909
3151
  totalBytes += line.length;
2910
3152
  if (totalBytes > maxBytes) {
2911
- throw new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
3153
+ throw tooLarge();
2912
3154
  }
2913
3155
  try {
2914
3156
  write(level, line);
@@ -3000,7 +3242,7 @@ var ReusableSandboxScript = api.ReusableSandboxScript;
3000
3242
  var import_util = require("util");
3001
3243
  var HostPromisePrototype = Promise.prototype;
3002
3244
  var ObjectGetPrototypeOf4 = Object.getPrototypeOf;
3003
- var ReflectApply5 = Reflect.apply;
3245
+ var ReflectApply6 = Reflect.apply;
3004
3246
  var isEnginePromise = import_util.types.isPromise;
3005
3247
  var MAX_PROTOTYPE_CHAIN = 32;
3006
3248
  var MAX_INSTALLS = 8;
@@ -3043,7 +3285,7 @@ function wrapEmit(previous) {
3043
3285
  return true;
3044
3286
  }
3045
3287
  }
3046
- return ReflectApply5(previous, this, [event, ...args]);
3288
+ return ReflectApply6(previous, this, [event, ...args]);
3047
3289
  };
3048
3290
  }
3049
3291
  function guardSandboxRejections() {
@@ -3163,6 +3405,26 @@ function buildToolNamespaceBindings(install, callTool, namespaces) {
3163
3405
  return namespaces.map((ns) => ({ name: ns.name, value: built[ns.name] }));
3164
3406
  }
3165
3407
 
3408
+ // libs/core/src/realm-regex-backstop.ts
3409
+ var REALM_REGEX_BACKSTOP_SOURCE = `
3410
+ (function () {
3411
+ 'use strict';
3412
+ var defineProperty = Object.defineProperty;
3413
+ var freeze = Object.freeze;
3414
+ var RealmTypeError = TypeError;
3415
+ var proto = RegExp.prototype;
3416
+ var refuse = () => {
3417
+ throw new RealmTypeError('Regular expressions are not available in this sandbox');
3418
+ };
3419
+ freeze(refuse);
3420
+ var keys = ['exec', 'test', 'compile', Symbol.match, Symbol.matchAll, Symbol.replace, Symbol.search, Symbol.split];
3421
+ for (var i = 0; i < keys.length; i++) {
3422
+ defineProperty(proto, keys[i], { value: refuse, writable: false, configurable: false, enumerable: false });
3423
+ }
3424
+ freeze(proto);
3425
+ })()
3426
+ `.trim();
3427
+
3166
3428
  // libs/core/src/deadline-guard.ts
3167
3429
  var walk = __toESM(require("acorn-walk"));
3168
3430
  var REALM_TICK_FN = "__safe_tick";
@@ -4362,7 +4624,9 @@ function realmArrayAccountingSource(memoryLimit) {
4362
4624
 
4363
4625
  // An array literal with spreads: [a, ...b, ...c] is compiled to
4364
4626
  // __safe_array(__safe_arrayStart(), [a, ...__safe_spread(b), ...__safe_spread(c)])
4365
- // so that each source is seen before it is spread and the result when it exists.
4627
+ // so that each source is seen before it is spread and the result when it exists. One without
4628
+ // spreads, [a, b], is compiled to __safe_array(0, [a, b]): it has no frame, and its slots are
4629
+ // checked and charged like those of any array.
4366
4630
  var frames = [];
4367
4631
  var nextId = 1;
4368
4632
 
@@ -4424,7 +4688,7 @@ function realmArrayAccountingSource(memoryLimit) {
4424
4688
 
4425
4689
  function arrayFinish(id, array) {
4426
4690
  var largest = 0;
4427
- for (var i = frames.length - 1; i >= 0; i--) {
4691
+ for (var i = id === 0 ? -1 : frames.length - 1; i >= 0; i--) {
4428
4692
  if (frames[i].id === id) {
4429
4693
  largest = frames[i].largest;
4430
4694
  frames.length = i;
@@ -4432,7 +4696,7 @@ function realmArrayAccountingSource(memoryLimit) {
4432
4696
  }
4433
4697
  }
4434
4698
  if (isArray(array)) {
4435
- checkLength(array.length, 'Array spread');
4699
+ checkLength(array.length, id === 0 ? 'Array literal' : 'Array spread');
4436
4700
  charge(array.length - largest);
4437
4701
  }
4438
4702
  return array;
@@ -4741,24 +5005,6 @@ var REALM_RUNTIME_GLOBALS = [
4741
5005
  "TypeError",
4742
5006
  "RangeError"
4743
5007
  ];
4744
- var INNER_REALM_REGEX_BACKSTOP_SOURCE = `
4745
- (function () {
4746
- 'use strict';
4747
- var defineProperty = Object.defineProperty;
4748
- var freeze = Object.freeze;
4749
- var RealmTypeError = TypeError;
4750
- var proto = RegExp.prototype;
4751
- var refuse = () => {
4752
- throw new RealmTypeError('Regular expressions are not available in this sandbox');
4753
- };
4754
- freeze(refuse);
4755
- var keys = ['exec', 'test', 'compile', Symbol.match, Symbol.matchAll, Symbol.replace, Symbol.search, Symbol.split];
4756
- for (var i = 0; i < keys.length; i++) {
4757
- defineProperty(proto, keys[i], { value: refuse, writable: false, configurable: false, enumerable: false });
4758
- }
4759
- freeze(proto);
4760
- })()
4761
- `.trim();
4762
5008
  var REALM_LOCKDOWN_SOURCE = `
4763
5009
  (function () {
4764
5010
  'use strict';
@@ -5491,6 +5737,10 @@ function generateParentVmBootstrap(options) {
5491
5737
  const __ag_FunctionToString = Function.prototype.toString;
5492
5738
  const __ag_ObjectToLocaleString = Object.prototype.toLocaleString;
5493
5739
  const __ag_Promise = Promise;
5740
+ const __ag_JSONStringify = JSON.stringify;
5741
+ const __ag_String = String;
5742
+ const __ag_StringValueOf = String.prototype.valueOf;
5743
+ const __ag_NumberValueOf = Number.prototype.valueOf;
5494
5744
 
5495
5745
  /**
5496
5746
  * Creates a "safe" error object that cannot be used to escape the sandbox.
@@ -5899,20 +6149,23 @@ function generateParentVmBootstrap(options) {
5899
6149
  * object, with a function member replaced by one that passes its arguments through
5900
6150
  * toSandboxValue (and keeps the script's object as its receiver), and an object member or
5901
6151
  * result guarded the same way. Its own properties are listed as they are, so a built-in that
5902
- * copies or serializes the object sees the same data. An array is data to every built-in and
5903
- * is passed as it is, as is a value that is behind the membrane already.
6152
+ * copies or serializes the object sees the same data. An array gets a guard that is still an
6153
+ * array, see guardArrayForHost. A value that is behind the membrane already is passed as it is.
5904
6154
  */
5905
6155
  function guardObjectForHost(value) {
5906
6156
  if (value === null || typeof value !== 'object') {
5907
6157
  return value;
5908
6158
  }
5909
- if (membraneProxies.has(value) || guardedHostArguments.has(value) || __ag_ArrayIsArray(value)) {
6159
+ if (membraneProxies.has(value) || guardedHostArguments.has(value)) {
5910
6160
  return value;
5911
6161
  }
5912
6162
  var existing = hostArgumentGuards.get(value);
5913
6163
  if (existing) {
5914
6164
  return existing;
5915
6165
  }
6166
+ if (__ag_ArrayIsArray(value)) {
6167
+ return guardArrayForHost(value);
6168
+ }
5916
6169
  // Over an empty object of this realm, not over the script's object: a frozen member of the
5917
6170
  // target would have to be reported as it is (proxy invariant), unguarded.
5918
6171
  var guard = new __ag_ParentProxy(__ag_objectCreate(null), {
@@ -5949,6 +6202,52 @@ function generateParentVmBootstrap(options) {
5949
6202
  return guard;
5950
6203
  }
5951
6204
 
6205
+ /**
6206
+ * An array of the script on its way into a built-in method of host data. The built-ins read
6207
+ * its length and its elements and spread it (concat), so its guard is a proxy of the array
6208
+ * itself, which is an array to them. An element and the length are answered as they are: they
6209
+ * are data. Every other member is read like a member of an object (guardMemberForHost): an
6210
+ * array can carry methods of its own, and the set operations call size, has and keys of
6211
+ * whatever set-like they are given, with the host's own values. A frozen method of the array
6212
+ * cannot be answered guarded (proxy invariant), so the built-in fails instead of calling it.
6213
+ */
6214
+ function guardArrayForHost(value) {
6215
+ var guard = new __ag_ParentProxy(value, {
6216
+ get: function(target, property) {
6217
+ var member = __ag_ReflectGet(target, property, target);
6218
+ if (property === 'length' || isArrayIndexKey(property)) {
6219
+ return member;
6220
+ }
6221
+ return guardMemberForHost(member, target);
6222
+ },
6223
+ // What a built-in stores in the array is a host value like any other.
6224
+ set: function(target, property, stored) {
6225
+ return __ag_ReflectSet(target, property, toSandboxValue(stored), target);
6226
+ },
6227
+ defineProperty: function(target, property, descriptor) {
6228
+ if ('get' in descriptor || 'set' in descriptor) {
6229
+ return false;
6230
+ }
6231
+ if ('value' in descriptor) {
6232
+ descriptor.value = toSandboxValue(descriptor.value);
6233
+ }
6234
+ return __ag_ReflectDefineProperty(target, property, descriptor);
6235
+ }
6236
+ });
6237
+ hostArgumentGuards.set(value, guard);
6238
+ guardedHostArguments.set(guard, value);
6239
+ return guard;
6240
+ }
6241
+
6242
+ /** Whether a property key is an array index ('0' to '4294967294' in canonical form). */
6243
+ function isArrayIndexKey(property) {
6244
+ if (typeof property !== 'string') {
6245
+ return false;
6246
+ }
6247
+ var index = +property;
6248
+ return index >>> 0 === index && index !== 4294967295 && '' + index === property;
6249
+ }
6250
+
5952
6251
  function guardMemberForHost(member, holder) {
5953
6252
  if (typeof member !== 'function') {
5954
6253
  return guardObjectForHost(member);
@@ -6742,8 +7041,11 @@ function generateParentVmBootstrap(options) {
6742
7041
  throw createSafeError('Operation name must be a non-empty string', 'TypeError');
6743
7042
  }
6744
7043
 
6745
- // Operation name pattern validation (whitelist)
7044
+ // Operation name pattern validation (whitelist). Each test starts at the beginning of the
7045
+ // name: a global or sticky pattern would otherwise go on from where its last match ended,
7046
+ // and decide the same name differently on the next call.
6746
7047
  if (validationConfig.validateOperationNames && typeof allowedOperationPattern !== 'undefined') {
7048
+ allowedOperationPattern.lastIndex = 0;
6747
7049
  if (!allowedOperationPattern.test(operationName)) {
6748
7050
  throw createSafeError('Operation "' + operationName + '" does not match allowed pattern');
6749
7051
  }
@@ -6752,6 +7054,7 @@ function generateParentVmBootstrap(options) {
6752
7054
  // Operation name pattern validation (blacklist)
6753
7055
  if (typeof blockedOperationPatterns !== 'undefined') {
6754
7056
  for (var i = 0; i < blockedOperationPatterns.length; i++) {
7057
+ blockedOperationPatterns[i].lastIndex = 0;
6755
7058
  if (blockedOperationPatterns[i].test(operationName)) {
6756
7059
  throw createSafeError('Operation "' + operationName + '" matches blocked pattern');
6757
7060
  }
@@ -6824,6 +7127,58 @@ function generateParentVmBootstrap(options) {
6824
7127
  return false;
6825
7128
  }
6826
7129
 
7130
+ /** Whether a value has the internal slot that a built-in's valueOf reads. */
7131
+ function hasSlot(valueOf, value) {
7132
+ try {
7133
+ __ag_ReflectApply(valueOf, value, []);
7134
+ return true;
7135
+ } catch (e) {
7136
+ return false;
7137
+ }
7138
+ }
7139
+
7140
+ /**
7141
+ * The JSON text of a value, given up as soon as it would be longer than limit bytes. A value
7142
+ * referenced many times is written as many times, so the text can be far longer than the value
7143
+ * is large. What each member adds is counted as JSON.stringify writes it, and the count is a
7144
+ * lower bound of its UTF-8 bytes (a code unit is at least one byte, an escape only adds), so a
7145
+ * value whose text is within the limit is never given up. The members JSON.stringify visits are
7146
+ * counted as well, also those it leaves out (a function, undefined): at most as many as the limit
7147
+ * has bytes.
7148
+ */
7149
+ var TOO_LARGE = {};
7150
+ function stringifyWithin(value, limit) {
7151
+ var bytes = 0;
7152
+ var visits = 0;
7153
+ var root = true;
7154
+ return __ag_JSONStringify(value, function(key, member) {
7155
+ if (++visits > limit) throw TOO_LARGE;
7156
+ // A String or Number object is written as what it converts to; converted here, the way
7157
+ // JSON.stringify converts it and once, so the count is of what is written.
7158
+ if (member !== null && typeof member === 'object') {
7159
+ if (hasSlot(__ag_StringValueOf, member)) member = __ag_String(member);
7160
+ else if (hasSlot(__ag_NumberValueOf, member)) member = +member;
7161
+ }
7162
+ var added;
7163
+ var kind = typeof member;
7164
+ if (kind === 'string') added = member.length + 2;
7165
+ else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
7166
+ else if (kind === 'boolean') added = member ? 4 : 5;
7167
+ else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
7168
+ else added = 0;
7169
+ if (!root) {
7170
+ // An element of an array is written, as null if nothing else; a member of an object
7171
+ // that is written has its key in front of it.
7172
+ if (__ag_ArrayIsArray(this)) added = added || 4;
7173
+ else if (added > 0) added += key.length + 3;
7174
+ }
7175
+ root = false;
7176
+ bytes += added;
7177
+ if (bytes > limit) throw TOO_LARGE;
7178
+ return member;
7179
+ });
7180
+ }
7181
+
6827
7182
  /**
6828
7183
  * Inner VM's callTool function
6829
7184
  * Proxies through parent VM with validation
@@ -6851,11 +7206,16 @@ function generateParentVmBootstrap(options) {
6851
7206
  throw createSafeError('Tool arguments must be an object', 'TypeError');
6852
7207
  }
6853
7208
 
6854
- // Double sanitization (defense in depth)
7209
+ // Double sanitization (defense in depth). The text is written within the payload limit (see
7210
+ // stringifyWithin), so what is done before the request is measured is in proportion to the
7211
+ // limit; in direct mode as well, where the request is held to the same limit below.
6855
7212
  var sanitizedArgs;
6856
7213
  try {
6857
- sanitizedArgs = JSON.parse(JSON.stringify(args));
7214
+ sanitizedArgs = JSON.parse(stringifyWithin(args, toolBridgeMaxPayloadBytes));
6858
7215
  } catch (e) {
7216
+ if (e === TOO_LARGE) {
7217
+ throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
7218
+ }
6859
7219
  throw createSafeError('Tool arguments must be JSON-serializable');
6860
7220
  }
6861
7221
 
@@ -6947,8 +7307,12 @@ function generateParentVmBootstrap(options) {
6947
7307
  throw createSafeError('Tool bridge returned invalid response');
6948
7308
  });
6949
7309
  } else {
6950
- // Direct mode: the rejection is mapped here rather than by launderThrown alone, which
6951
- // would drop the code the host uses to mark a failure of the tool itself.
7310
+ // Direct mode: the request is held to the payload limit as through the string bridge.
7311
+ if (exceedsPayloadLimit(JSON.stringify({ v: 1, tool: toolName, args: sanitizedArgs }), toolBridgeMaxPayloadBytes)) {
7312
+ throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
7313
+ }
7314
+ // The rejection is mapped here rather than by launderThrown alone, which would drop the
7315
+ // code the host uses to mark a failure of the tool itself.
6952
7316
  promise = deferHostCall(function() {
6953
7317
  return hostCallTool(toolName, sanitizedArgs);
6954
7318
  }, function(error) {
@@ -6958,9 +7322,16 @@ function generateParentVmBootstrap(options) {
6958
7322
  code = error && error.code;
6959
7323
  message = error && error.message;
6960
7324
  } catch (e) { /* treated as an unmarked failure */ }
6961
- if (code === 'TOOL_CALL_FAILED') {
7325
+ // A failure of the tool, or a result the host refused, keeps its code.
7326
+ if (
7327
+ code === 'TOOL_CALL_FAILED' ||
7328
+ code === 'TOOL_RESULT_NOT_STORED' ||
7329
+ code === 'TOOL_RESULT_TOO_LARGE' ||
7330
+ code === 'TOOL_RESULT_TOO_COMPLEX' ||
7331
+ code === 'TOOL_BRIDGE_RESPONSE_TOO_LARGE'
7332
+ ) {
6962
7333
  var text = typeof message === 'string' ? message : 'Tool call failed';
6963
- return markToolFailure(createSafeError(text), toolName, 'Error', text, 'TOOL_CALL_FAILED');
7334
+ return markToolFailure(createSafeError(text), toolName, 'Error', text, code);
6964
7335
  }
6965
7336
  return launderThrown(error);
6966
7337
  });
@@ -7220,8 +7591,9 @@ function generateParentVmBootstrap(options) {
7220
7591
  * Rate-limited console for inner VM
7221
7592
  */
7222
7593
  var consoleStats = { totalBytes: 0, callCount: 0 };
7223
- var maxConsoleBytes = hostConfig.maxConsoleOutputBytes || 65536;
7224
- var maxConsoleCalls = hostConfig.maxConsoleCalls || 100;
7594
+ // A limit of 0 is a limit: nothing may be written (it is not "unset").
7595
+ var maxConsoleBytes = typeof hostConfig.maxConsoleOutputBytes === 'number' ? hostConfig.maxConsoleOutputBytes : 65536;
7596
+ var maxConsoleCalls = typeof hostConfig.maxConsoleCalls === 'number' ? hostConfig.maxConsoleCalls : 100;
7225
7597
 
7226
7598
  function createSafeConsoleMethod(level) {
7227
7599
  return function() {
@@ -7774,7 +8146,7 @@ function generateParentVmBootstrap(options) {
7774
8146
  // After inner-runtime.js, whose one trusted pattern has kept its own matcher. Not optional:
7775
8147
  // a failure here aborts the execution.
7776
8148
  if (__ag_realmAllowed && __ag_realmAllowed.RegExp !== true) {
7777
- new vm.Script(${JSON.stringify(INNER_REALM_REGEX_BACKSTOP_SOURCE)}, {
8149
+ new vm.Script(${JSON.stringify(REALM_REGEX_BACKSTOP_SOURCE)}, {
7778
8150
  filename: 'inner-regex-backstop.js'
7779
8151
  }).runInContext(innerContext);
7780
8152
  }
@@ -8100,7 +8472,8 @@ var RAPID_ENUMERATION = {
8100
8472
  if (localConfig) {
8101
8473
  const defaultThreshold = localConfig.rapidEnumerationThreshold ?? 30;
8102
8474
  const overrides = localConfig.rapidEnumerationOverrides ?? {};
8103
- threshold = overrides[operationName] ?? defaultThreshold;
8475
+ const override = Object.prototype.hasOwnProperty.call(overrides, operationName) ? overrides[operationName] : void 0;
8476
+ threshold = typeof override === "number" ? override : defaultThreshold;
8104
8477
  }
8105
8478
  } catch {
8106
8479
  threshold = 30;
@@ -8198,6 +8571,12 @@ function serializePatterns(patterns) {
8198
8571
  }
8199
8572
 
8200
8573
  // libs/core/src/double-vm/double-vm-wrapper.ts
8574
+ var resultRefusals = /* @__PURE__ */ new WeakMap();
8575
+ function resultRefusal(message, code) {
8576
+ const error = new Error(message);
8577
+ resultRefusals.set(error, code);
8578
+ return error;
8579
+ }
8201
8580
  var DoubleVmWrapper = class {
8202
8581
  /**
8203
8582
  * @param config Double VM configuration
@@ -8521,33 +8900,72 @@ var DoubleVmWrapper = class {
8521
8900
  }
8522
8901
  resolvedArgs = resolver.resolve(args);
8523
8902
  }
8903
+ let handlerCompleted = false;
8524
8904
  try {
8525
8905
  const result = await toolHandler(toolName, resolvedArgs);
8906
+ handlerCompleted = true;
8526
8907
  const sanitized = sanitizeValue(result, {
8527
8908
  maxDepth: config.maxSanitizeDepth,
8528
8909
  maxProperties: config.maxSanitizeProperties,
8529
8910
  allowDates: true,
8530
8911
  allowErrors: true
8531
8912
  });
8913
+ const resultLimit = executionContext.maxToolResultBytes;
8914
+ if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
8915
+ try {
8916
+ const resultJson = stringifyWithin(sanitized, resultLimit);
8917
+ if (resultJson !== void 0 && utf8Length(resultJson) > resultLimit) {
8918
+ throw resultRefusal(`Tool result exceeds the limit of ${resultLimit} bytes`, "TOOL_RESULT_TOO_LARGE");
8919
+ }
8920
+ } catch (error) {
8921
+ if (error instanceof JsonTraversalLimitError) {
8922
+ throw resultRefusal("Tool result exceeds the traversal limit", "TOOL_RESULT_TOO_COMPLEX");
8923
+ }
8924
+ if (error instanceof JsonTooLargeError) {
8925
+ throw resultRefusal(`Tool result exceeds the limit of ${resultLimit} bytes`, "TOOL_RESULT_TOO_LARGE");
8926
+ }
8927
+ throw error;
8928
+ }
8929
+ }
8930
+ let outgoing = sanitized;
8532
8931
  if (sidecar && referenceConfig && typeof sanitized === "string") {
8533
8932
  const size = Buffer.byteLength(sanitized, "utf-8");
8534
8933
  if (size >= referenceConfig.extractionThreshold) {
8535
8934
  try {
8536
- const refId = sidecar.store(sanitized, "tool-result", { origin: toolName });
8537
- return refId;
8538
- } catch (storageError) {
8539
- if (process.env["NODE_ENV"] !== "production") {
8540
- console.debug(
8541
- `[DoubleVmWrapper] Sidecar storage failed for tool "${toolName}": ${storageError.message}`
8542
- );
8543
- }
8544
- return sanitized;
8935
+ outgoing = sidecar.store(sanitized, "tool-result", { origin: toolName });
8936
+ } catch {
8937
+ throw resultRefusal("Tool result could not be stored in the reference sidecar", "TOOL_RESULT_NOT_STORED");
8545
8938
  }
8546
8939
  }
8547
8940
  }
8548
- return sanitized;
8941
+ const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
8942
+ let responseJson;
8943
+ try {
8944
+ responseJson = outgoing === void 0 ? void 0 : stringifyWithin(outgoing, maxPayloadBytes);
8945
+ } catch (error) {
8946
+ if (error instanceof JsonTraversalLimitError) {
8947
+ throw resultRefusal("Tool response exceeds traversal limit", "TOOL_RESULT_TOO_COMPLEX");
8948
+ }
8949
+ if (!(error instanceof JsonTooLargeError)) throw error;
8950
+ throw resultRefusal(
8951
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
8952
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
8953
+ );
8954
+ }
8955
+ if (responseJson !== void 0 && utf8Length(responseJson) > maxPayloadBytes) {
8956
+ throw resultRefusal(
8957
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
8958
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
8959
+ );
8960
+ }
8961
+ return outgoing;
8549
8962
  } catch (error) {
8963
+ if (handlerCompleted) executionContext.onToolBridgeFailure?.();
8550
8964
  const err = error;
8965
+ const refused = resultRefusals.get(error);
8966
+ if (refused) {
8967
+ throw createSafeError(err.message, "Error", refused);
8968
+ }
8551
8969
  throw createSafeError(
8552
8970
  `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`,
8553
8971
  "Error",
@@ -8749,6 +9167,12 @@ function createSafeRuntime(context, options) {
8749
9167
  const secureProxyConfig = options?.secureProxyConfig;
8750
9168
  const memoryTracker = options?.memoryTracker;
8751
9169
  const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
9170
+ const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
9171
+ const codedError = (message, code) => Object.assign(new Error(message), { code });
9172
+ const refuseToolResult = (message, code) => {
9173
+ context.onToolBridgeFailure?.();
9174
+ throw codedError(message, code);
9175
+ };
8752
9176
  const proxyOptions = {
8753
9177
  ...secureProxyConfig ? { levelConfig: secureProxyConfig } : {},
8754
9178
  ...options?.exposeToSandbox ? { exposeToSandbox: options.exposeToSandbox } : {},
@@ -8775,6 +9199,21 @@ function createSafeRuntime(context, options) {
8775
9199
  if (!context.toolHandler) {
8776
9200
  throw createSafeError("No tool handler configured. Cannot execute tool calls.");
8777
9201
  }
9202
+ let requestJson;
9203
+ try {
9204
+ requestJson = stringifyWithin({ v: 1, tool: toolName, args }, maxPayloadBytes);
9205
+ } catch (error) {
9206
+ if (error instanceof JsonTooLargeError) {
9207
+ throw createSafeError(`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`, "RangeError");
9208
+ }
9209
+ if (error instanceof JsonTraversalLimitError) {
9210
+ throw createSafeError("Tool request exceeds traversal limit", "RangeError");
9211
+ }
9212
+ throw createSafeTypeError("Tool arguments must be JSON-serializable");
9213
+ }
9214
+ if (requestJson !== void 0 && utf8Length(requestJson) > maxPayloadBytes) {
9215
+ throw createSafeError(`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`, "RangeError");
9216
+ }
8778
9217
  let resolvedArgs = args;
8779
9218
  if (resolver && resolver.containsReferences(args)) {
8780
9219
  if (resolver.wouldExceedLimit(args)) {
@@ -8794,12 +9233,34 @@ function createSafeRuntime(context, options) {
8794
9233
  }
8795
9234
  try {
8796
9235
  const result = await context.toolHandler(toolName, resolvedArgs);
8797
- const sanitized = sanitizeValue(result, {
8798
- maxDepth: 20,
8799
- maxProperties: 1e4,
8800
- allowDates: true,
8801
- allowErrors: true
8802
- });
9236
+ let sanitized;
9237
+ try {
9238
+ sanitized = sanitizeValue(result, {
9239
+ maxDepth: config.maxSanitizeDepth ?? 20,
9240
+ maxProperties: config.maxSanitizeProperties ?? 1e4,
9241
+ allowDates: true,
9242
+ allowErrors: true
9243
+ });
9244
+ } catch {
9245
+ refuseToolResult("Tool returned an unsupported value", "TOOL_RESULT_NOT_SAFE");
9246
+ }
9247
+ const resultLimit = context.maxToolResultBytes;
9248
+ if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
9249
+ let tooLarge = false;
9250
+ try {
9251
+ const resultJson = stringifyWithin(sanitized, resultLimit);
9252
+ tooLarge = resultJson !== void 0 && utf8Length(resultJson) > resultLimit;
9253
+ } catch (error) {
9254
+ if (error instanceof JsonTraversalLimitError) {
9255
+ refuseToolResult("Tool result exceeds the traversal limit", "TOOL_RESULT_TOO_COMPLEX");
9256
+ }
9257
+ if (!(error instanceof JsonTooLargeError)) throw error;
9258
+ tooLarge = true;
9259
+ }
9260
+ if (tooLarge) {
9261
+ refuseToolResult(`Tool result exceeds the limit of ${resultLimit} bytes`, "TOOL_RESULT_TOO_LARGE");
9262
+ }
9263
+ }
8803
9264
  let value = sanitized;
8804
9265
  if (sidecar && referenceConfig && typeof sanitized === "string") {
8805
9266
  const size = Buffer.byteLength(sanitized, "utf-8");
@@ -8807,27 +9268,47 @@ function createSafeRuntime(context, options) {
8807
9268
  try {
8808
9269
  value = sidecar.store(sanitized, "tool-result", { origin: toolName });
8809
9270
  } catch {
8810
- value = sanitized;
9271
+ refuseToolResult("Tool result could not be stored in the reference sidecar", "TOOL_RESULT_NOT_STORED");
8811
9272
  }
8812
9273
  }
8813
9274
  }
9275
+ let responseJson;
9276
+ try {
9277
+ responseJson = value === void 0 ? void 0 : stringifyWithin(value, maxPayloadBytes);
9278
+ } catch (error) {
9279
+ if (error instanceof JsonTraversalLimitError) {
9280
+ refuseToolResult("Tool response exceeds traversal limit", "TOOL_RESULT_TOO_COMPLEX");
9281
+ }
9282
+ if (!(error instanceof JsonTooLargeError)) throw error;
9283
+ refuseToolResult(
9284
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
9285
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
9286
+ );
9287
+ }
9288
+ if (responseJson !== void 0 && utf8Length(responseJson) > maxPayloadBytes) {
9289
+ refuseToolResult(
9290
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
9291
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
9292
+ );
9293
+ }
8814
9294
  return throwOnError ? value : plainResult({ success: true, data: value });
8815
9295
  } catch (error) {
8816
9296
  const err = error;
8817
9297
  const message = `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`;
8818
9298
  if (!throwOnError) {
8819
- const code = error?.code;
9299
+ const code2 = error?.code;
8820
9300
  return plainResult({
8821
9301
  success: false,
8822
9302
  error: plainResult({
8823
9303
  name: "Error",
8824
9304
  message,
8825
- ...typeof code === "string" ? { code } : {},
9305
+ ...typeof code2 === "string" ? { code: code2 } : {},
8826
9306
  toolName
8827
9307
  })
8828
9308
  });
8829
9309
  }
8830
- throw createSafeError(message);
9310
+ const code = error?.code;
9311
+ throw createSafeError(message, "Error", typeof code === "string" ? code : void 0);
8831
9312
  }
8832
9313
  }
8833
9314
  function* __safe_forOf(iterable) {
@@ -9096,8 +9577,8 @@ var ReflectGet6 = Reflect.get;
9096
9577
  var ReflectHas2 = Reflect.has;
9097
9578
  var ReflectOwnKeys3 = Reflect.ownKeys;
9098
9579
  var ReflectGetOwnPropertyDescriptor2 = Reflect.getOwnPropertyDescriptor;
9099
- var ReflectApply6 = Reflect.apply;
9100
- var ArrayIsArray4 = Array.isArray;
9580
+ var ReflectApply7 = Reflect.apply;
9581
+ var ArrayIsArray5 = Array.isArray;
9101
9582
  var ObjectGetPrototypeOf5 = Object.getPrototypeOf;
9102
9583
  function isReference(value) {
9103
9584
  return value !== null && (typeof value === "object" || typeof value === "function");
@@ -9186,7 +9667,7 @@ function createRealmAirlock(realm) {
9186
9667
  return counterpart;
9187
9668
  }
9188
9669
  }
9189
- const kind = callable ? "function" : ArrayIsArray4(hostProxy) ? "array" : "object";
9670
+ const kind = callable ? "function" : ArrayIsArray5(hostProxy) ? "array" : "object";
9190
9671
  const readValue = (key) => {
9191
9672
  const value2 = ReflectGet6(hostProxy, key, hostProxy);
9192
9673
  if (typeof value2 === "function") {
@@ -9241,7 +9722,7 @@ function createRealmAirlock(realm) {
9241
9722
  for (let i = 0; i < args.length; i++) {
9242
9723
  passed[i] = args[i];
9243
9724
  }
9244
- return toRealm(ReflectApply6(hostProxy, toHost(thisArg), passed));
9725
+ return toRealm(ReflectApply7(hostProxy, toHost(thisArg), passed));
9245
9726
  },
9246
9727
  construct() {
9247
9728
  throw createSafeError("Host functions cannot be called with new", "TypeError");
@@ -10223,6 +10704,10 @@ var VmAdapter = class {
10223
10704
  var promiseThen = Promise.prototype.then;
10224
10705
  var settled = Promise.resolve();
10225
10706
  var reflectApply = Reflect.apply;
10707
+ var isArray = Array.isArray;
10708
+ var StringOf = String;
10709
+ var stringValueOf = String.prototype.valueOf;
10710
+ var numberValueOf = Number.prototype.valueOf;
10226
10711
  var maxBytes = ${numericLiteral("toolBridge.maxPayloadBytes", maxPayloadBytes)};
10227
10712
  var limitMessage = ${JSON.stringify(limitMessage)};
10228
10713
 
@@ -10291,6 +10776,56 @@ var VmAdapter = class {
10291
10776
  return err;
10292
10777
  }
10293
10778
 
10779
+ // Whether a value has the internal slot that a built-in's valueOf reads.
10780
+ function hasSlot(valueOf, value) {
10781
+ try {
10782
+ reflectApply(valueOf, value, []);
10783
+ return true;
10784
+ } catch (e) {
10785
+ return false;
10786
+ }
10787
+ }
10788
+
10789
+ // The JSON text of a value, given up as soon as it would be longer than limit bytes.
10790
+ // A value referenced many times is written as many times, so the text can be far longer
10791
+ // than the value is large. What each member adds is counted as JSON.stringify writes it,
10792
+ // and the count is a lower bound of its UTF-8 bytes (a code unit is at least one byte,
10793
+ // an escape only adds), so a value whose text is within the limit is never given up.
10794
+ // The members JSON.stringify visits are counted as well, also those it leaves out (a
10795
+ // function, undefined): at most as many as the limit has bytes.
10796
+ var TOO_LARGE = {};
10797
+ function stringifyWithin(value, limit) {
10798
+ var bytes = 0;
10799
+ var visits = 0;
10800
+ var root = true;
10801
+ return stringify(value, function (key, member) {
10802
+ if (++visits > limit) throw TOO_LARGE;
10803
+ // A String or Number object is written as what it converts to; converted here, the
10804
+ // way JSON.stringify converts it and once, so the count is of what is written.
10805
+ if (member !== null && typeof member === 'object') {
10806
+ if (hasSlot(stringValueOf, member)) member = StringOf(member);
10807
+ else if (hasSlot(numberValueOf, member)) member = +member;
10808
+ }
10809
+ var added;
10810
+ var kind = typeof member;
10811
+ if (kind === 'string') added = member.length + 2;
10812
+ else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
10813
+ else if (kind === 'boolean') added = member ? 4 : 5;
10814
+ else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
10815
+ else added = 0;
10816
+ if (!root) {
10817
+ // An element of an array is written, as null if nothing else; a member of an
10818
+ // object that is written has its key in front of it.
10819
+ if (isArray(this)) added = added || 4;
10820
+ else if (added > 0) added += key.length + 3;
10821
+ }
10822
+ root = false;
10823
+ bytes += added;
10824
+ if (bytes > limit) throw TOO_LARGE;
10825
+ return member;
10826
+ });
10827
+ }
10828
+
10294
10829
  return async function __safe_callTool(toolName, args, options) {
10295
10830
  // callTool options: only { throwOnError: false } changes behavior. Tool failures
10296
10831
  // then resolve to { success: false, error }; the enclave's own refusals still throw.
@@ -10311,11 +10846,23 @@ var VmAdapter = class {
10311
10846
  throw makeError('Tool bridge is not available', 'Error');
10312
10847
  }
10313
10848
 
10314
- // Defense-in-depth: ensure JSON-serializable input.
10849
+ // Counted here, where the call is made and before anything is done with its
10850
+ // arguments: the first maxToolCalls calls are the ones that run, also when several
10851
+ // are made before any of them is started, and a call over the limit costs nothing.
10852
+ if (countCall() !== true) {
10853
+ throw makeError(limitMessage, 'ToolLimitError');
10854
+ }
10855
+
10856
+ // Defense-in-depth: ensure JSON-serializable input. The text is written within the
10857
+ // payload limit (see stringifyWithin), so what is done before the request is
10858
+ // measured is in proportion to the limit.
10315
10859
  var sanitizedArgs;
10316
10860
  try {
10317
- sanitizedArgs = parse(stringify(args));
10861
+ sanitizedArgs = parse(stringifyWithin(args, maxBytes));
10318
10862
  } catch (e) {
10863
+ if (e === TOO_LARGE) {
10864
+ throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
10865
+ }
10319
10866
  throw makeError('Tool arguments must be JSON-serializable', 'TypeError');
10320
10867
  }
10321
10868
 
@@ -10330,11 +10877,6 @@ var VmAdapter = class {
10330
10877
  throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
10331
10878
  }
10332
10879
 
10333
- // Counted here, where the call is made: the first maxToolCalls calls are the ones
10334
- // that run, also when several are made before any of them is started.
10335
- if (countCall() !== true) {
10336
- throw makeError(limitMessage, 'ToolLimitError');
10337
- }
10338
10880
  var responseJson = await callBridge(requestJson);
10339
10881
  if (typeof responseJson !== 'string') {
10340
10882
  throw makeError('Tool bridge returned invalid response', 'Error');
@@ -10488,6 +11030,12 @@ var VmAdapter = class {
10488
11030
  enumerable: false
10489
11031
  });
10490
11032
  }
11033
+ const realmAllowlist = executionContext.realmGlobalAllowlist;
11034
+ if (realmAllowlist && !realmAllowlist.includes("RegExp")) {
11035
+ compileSandboxScript(REALM_REGEX_BACKSTOP_SOURCE, { filename: "realm-regex-backstop.js" }).runInContext(
11036
+ baseSandbox
11037
+ );
11038
+ }
10491
11039
  try {
10492
11040
  INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT.runInContext(baseSandbox);
10493
11041
  } catch {
@@ -10547,8 +11095,8 @@ var VmAdapter = class {
10547
11095
  }
10548
11096
  const depthDefaulted = config.maxSanitizeDepth ?? 20;
10549
11097
  const propsDefaulted = config.maxSanitizeProperties ?? 100;
10550
- const clampedDepth = Math.max(5, Math.min(50, depthDefaulted));
10551
- const clampedProperties = Math.max(50, Math.min(1e3, propsDefaulted));
11098
+ const clampedDepth = Math.min(50, depthDefaulted);
11099
+ const clampedProperties = Math.min(1e3, propsDefaulted);
10552
11100
  const sanitizedValue = sanitizeValue(value, {
10553
11101
  maxDepth: clampedDepth,
10554
11102
  maxProperties: clampedProperties,