@enclave-vm/core 2.19.1 → 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.
Files changed (53) hide show
  1. package/README.md +291 -105
  2. package/adapters/worker-pool/config.d.ts +15 -5
  3. package/adapters/worker-pool/protocol.d.ts +27 -1
  4. package/adapters/worker-pool/worker-pool-adapter.d.ts +24 -0
  5. package/adapters/worker-pool/worker-slot.d.ts +35 -6
  6. package/async-context.d.ts +34 -0
  7. package/babel/babel-wrapper.d.ts +21 -12
  8. package/babel/multi-file-transform.d.ts +3 -0
  9. package/babel/text-scan.d.ts +54 -0
  10. package/bounded-json.d.ts +33 -0
  11. package/deadline-guard.d.ts +16 -0
  12. package/dynamic-import.d.ts +25 -0
  13. package/enclave-options.d.ts +62 -0
  14. package/enclave.d.ts +35 -8
  15. package/esm/index.mjs +5520 -917
  16. package/esm/worker.mjs +2777 -195
  17. package/execution-deadline.d.ts +6 -0
  18. package/global-function-gate.d.ts +34 -1
  19. package/index.d.ts +3 -3
  20. package/index.js +5562 -959
  21. package/interpreter/interpreter.d.ts +207 -10
  22. package/memory-tracker.d.ts +7 -0
  23. package/package.json +3 -3
  24. package/portable-enclave.d.ts +51 -0
  25. package/portable-globals.d.ts +2 -0
  26. package/realm-airlock.d.ts +6 -1
  27. package/realm-memory.d.ts +89 -0
  28. package/realm-regex-backstop.d.ts +18 -0
  29. package/realm-stack.d.ts +25 -0
  30. package/safe-runtime.d.ts +2 -0
  31. package/sandbox-rejections.d.ts +3 -1
  32. package/scoring/feature-extractor.d.ts +52 -1
  33. package/scoring/index.d.ts +2 -1
  34. package/scoring/scorers/index.d.ts +2 -1
  35. package/scoring/scorers/local-llm.scorer.d.ts +9 -3
  36. package/scoring/scorers/progressive.scorer.d.ts +28 -1
  37. package/scoring/scorers/rule-based.scorer.d.ts +11 -1
  38. package/scoring/scoring-gate.d.ts +2 -0
  39. package/scoring/types.d.ts +36 -8
  40. package/secure-proxy.d.ts +17 -3
  41. package/session/session.d.ts +8 -1
  42. package/session-types.d.ts +6 -4
  43. package/sidecar/index.d.ts +1 -1
  44. package/sidecar/reference-config.d.ts +18 -1
  45. package/sidecar/reference-resolver.d.ts +26 -3
  46. package/sidecar/reference-sidecar.d.ts +37 -0
  47. package/src/adapters/worker-pool/package.json +3 -3
  48. package/src/adapters/worker-pool/worker-script.js +2835 -465
  49. package/thrown-value.d.ts +59 -0
  50. package/types.d.ts +85 -19
  51. package/value-sanitizer.d.ts +6 -1
  52. package/worker.d.ts +2 -0
  53. package/worker.js +2767 -195
@@ -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;
@@ -240,8 +241,6 @@ function isPlainObject(value) {
240
241
  function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
241
242
  const maxDepth = options.maxDepth ?? 20;
242
243
  const maxProperties = options.maxProperties ?? 1e4;
243
- const allowDates = options.allowDates ?? true;
244
- const allowErrors = options.allowErrors ?? true;
245
244
  if (depth > maxDepth) {
246
245
  throw new Error(
247
246
  `Tool handler return value exceeds maximum depth (${maxDepth}). This limit prevents deeply nested objects that could cause stack overflow.`
@@ -277,7 +276,19 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
277
276
  return "[Circular]";
278
277
  }
279
278
  context.visited.add(value);
279
+ try {
280
+ return sanitizeObjectValue(value, options, depth, context);
281
+ } finally {
282
+ context.visited.delete(value);
283
+ }
280
284
  }
285
+ return String(value);
286
+ }
287
+ function sanitizeObjectValue(value, options, depth, context) {
288
+ const maxProperties = options.maxProperties ?? 1e4;
289
+ const allowDates = options.allowDates ?? true;
290
+ const allowErrors = options.allowErrors ?? true;
291
+ const type = typeof value;
281
292
  if (ArrayIsArray2(value)) {
282
293
  const rawLen = ReflectGet2(value, "length");
283
294
  const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
@@ -327,9 +338,12 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
327
338
  const sanitizedMap = ObjectCreate(null);
328
339
  const entries = ReflectApply(MapProtoEntries, inspected, []);
329
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
+ }
330
345
  if (typeof key !== "string") continue;
331
346
  if (DANGEROUS_KEYS2.has(key)) continue;
332
- context.propCount.count++;
333
347
  sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
334
348
  }
335
349
  return sanitizedMap;
@@ -339,6 +353,9 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
339
353
  const result = [];
340
354
  for (const item of iter) {
341
355
  context.propCount.count++;
356
+ if (context.propCount.count > maxProperties) {
357
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
358
+ }
342
359
  result.push(sanitizeValue(item, options, depth + 1, context));
343
360
  }
344
361
  return result;
@@ -426,7 +443,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
426
443
  }
427
444
  if (ArrayIsArray2(value)) {
428
445
  if (currentPath.has(value)) {
429
- return 4;
446
+ return CIRCULAR_MARKER_BYTES;
430
447
  }
431
448
  currentPath.add(value);
432
449
  try {
@@ -452,7 +469,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
452
469
  if (type === "object") {
453
470
  const object = value;
454
471
  if (currentPath.has(object)) {
455
- return 4;
472
+ return CIRCULAR_MARKER_BYTES;
456
473
  }
457
474
  if (!isPlainObject(object)) {
458
475
  if (hasBrand(DateProtoGetTime, object)) {
@@ -544,6 +561,75 @@ function checkSerializedSize(value, maxBytes) {
544
561
  }
545
562
  }
546
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
+
547
633
  // libs/core/src/safe-error.ts
548
634
  var safeErrors = /* @__PURE__ */ new WeakSet();
549
635
  function isSafeError(value) {
@@ -610,7 +696,7 @@ function createSafeTypeError(message) {
610
696
  }
611
697
 
612
698
  // libs/core/src/stack-reserve.ts
613
- var ReflectApply2 = Reflect.apply;
699
+ var ReflectApply3 = Reflect.apply;
614
700
  var HOST_STACK_RESERVE_BYTES = 128 * 1024;
615
701
  var STACK_EXHAUSTED_MESSAGE = "Maximum call stack size exceeded";
616
702
  var SLOTS = [];
@@ -621,7 +707,7 @@ function nothing() {
621
707
  }
622
708
  function hasHostStackReserve() {
623
709
  try {
624
- ReflectApply2(nothing, void 0, SLOTS);
710
+ ReflectApply3(nothing, void 0, SLOTS);
625
711
  return true;
626
712
  } catch {
627
713
  return false;
@@ -629,11 +715,11 @@ function hasHostStackReserve() {
629
715
  }
630
716
 
631
717
  // libs/core/src/global-function-gate.ts
632
- var ReflectApply3 = Reflect.apply;
718
+ var ReflectApply4 = Reflect.apply;
633
719
  var ReflectOwnKeys = Reflect.ownKeys;
634
720
  var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
635
721
  var ObjectGetPrototypeOf2 = Object.getPrototypeOf;
636
- var ArrayIsArray3 = Array.isArray;
722
+ var ArrayIsArray4 = Array.isArray;
637
723
  var JsonStringify = JSON.stringify;
638
724
  var BUILTIN_PROTOTYPES = (() => {
639
725
  const typedArrays = [
@@ -687,21 +773,29 @@ var BUILTIN_PROTOTYPES = (() => {
687
773
  return prototypes.filter((prototype) => prototype !== null && typeof prototype === "object");
688
774
  })();
689
775
  var BUILTIN_PROTOTYPE_SET = new WeakSet(BUILTIN_PROTOTYPES);
690
- var BUILTIN_METHODS = (() => {
691
- const methods = /* @__PURE__ */ new WeakSet();
776
+ var BUILTIN_METHOD_HOMES = (() => {
777
+ const homes = /* @__PURE__ */ new WeakMap();
692
778
  for (const prototype of BUILTIN_PROTOTYPES) {
693
779
  for (const key of ReflectOwnKeys(prototype)) {
694
780
  if (key === "constructor") continue;
695
781
  const descriptor = ObjectGetOwnPropertyDescriptor(prototype, key);
696
782
  if (descriptor && typeof descriptor.value === "function") {
697
- methods.add(descriptor.value);
783
+ const known = homes.get(descriptor.value);
784
+ if (!known) {
785
+ homes.set(descriptor.value, [prototype]);
786
+ } else if (!known.includes(prototype)) {
787
+ known.push(prototype);
788
+ }
698
789
  }
699
790
  }
700
791
  }
701
- return methods;
792
+ return homes;
702
793
  })();
703
794
  function isBuiltinMethod(fn) {
704
- return (typeof fn === "function" || typeof fn === "object" && fn !== null) && BUILTIN_METHODS.has(fn);
795
+ return (typeof fn === "function" || typeof fn === "object" && fn !== null) && BUILTIN_METHOD_HOMES.has(fn);
796
+ }
797
+ function builtinMethodHomes(fn) {
798
+ return typeof fn === "function" || typeof fn === "object" && fn !== null ? BUILTIN_METHOD_HOMES.get(fn) : void 0;
705
799
  }
706
800
  var MUTATING_BUILTIN_METHODS = (() => {
707
801
  const methods = /* @__PURE__ */ new WeakSet();
@@ -747,6 +841,46 @@ var REGEXP_MATCH_METHODS = (() => {
747
841
  function isRegExpMatchMethod(fn) {
748
842
  return (typeof fn === "function" || typeof fn === "object" && fn !== null) && REGEXP_MATCH_METHODS.has(fn);
749
843
  }
844
+ var FunctionPrototypeToString = Function.prototype.toString;
845
+ var ObjectPrototypeToLocaleString = Object.prototype.toLocaleString;
846
+ function isFunctionTextMethod(fn) {
847
+ return fn === FunctionPrototypeToString || fn === ObjectPrototypeToLocaleString;
848
+ }
849
+ var MAX_FUNCTION_NAME_LENGTH = 64;
850
+ function isPlainIdentifier(name) {
851
+ if (name.length === 0 || name.length > MAX_FUNCTION_NAME_LENGTH) return false;
852
+ for (let i = 0; i < name.length; i++) {
853
+ const c = name.charCodeAt(i);
854
+ const letter = c >= 65 && c <= 90 || c >= 97 && c <= 122 || c === 95 || c === 36;
855
+ const digit = c >= 48 && c <= 57;
856
+ if (!letter && !(digit && i > 0)) return false;
857
+ }
858
+ return true;
859
+ }
860
+ function hostFunctionText(fn) {
861
+ let name = "";
862
+ try {
863
+ if (typeof fn === "function") {
864
+ const descriptor = ObjectGetOwnPropertyDescriptor(fn, "name");
865
+ const value = descriptor && "value" in descriptor ? descriptor.value : void 0;
866
+ if (typeof value === "string" && isPlainIdentifier(value)) {
867
+ name = value;
868
+ }
869
+ }
870
+ } catch {
871
+ }
872
+ return `function ${name}() { [native code] }`;
873
+ }
874
+ function withoutFunctionSource(text, fn) {
875
+ if (typeof fn !== "function") return text;
876
+ let source;
877
+ try {
878
+ source = ReflectApply4(FunctionPrototypeToString, fn, []);
879
+ } catch {
880
+ return text;
881
+ }
882
+ return source.length > 0 && text.includes(source) ? text.split(source).join(hostFunctionText(fn)) : text;
883
+ }
750
884
  var HOST_REGEXP_MESSAGE = "A regular expression passed in globals cannot be run in the sandbox, and a pattern cannot be run on a String object passed in globals. Read its source and flags (or the text), or pass a function that does the matching.";
751
885
  var DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL = 10;
752
886
  var DEFAULT_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
@@ -776,7 +910,7 @@ function resultLimits(context) {
776
910
  function truncate(value, max) {
777
911
  return value.length <= max ? value : `${value.slice(0, max)}\u2026`;
778
912
  }
779
- function failure(error) {
913
+ function failure(error, receiver) {
780
914
  let name = "Error";
781
915
  let message = "Global function call failed";
782
916
  try {
@@ -792,8 +926,8 @@ function failure(error) {
792
926
  }
793
927
  return {
794
928
  ok: false,
795
- name: truncate(name, MAX_ERROR_NAME_LENGTH),
796
- message: truncate(message, MAX_ERROR_MESSAGE_LENGTH)
929
+ name: truncate(withoutFunctionSource(name, receiver), MAX_ERROR_NAME_LENGTH),
930
+ message: truncate(withoutFunctionSource(message, receiver), MAX_ERROR_MESSAGE_LENGTH)
797
931
  };
798
932
  }
799
933
  function jsonReplacer(_key, value) {
@@ -837,7 +971,7 @@ function isThenable(value) {
837
971
  }
838
972
  }
839
973
  function sanitizeArguments(args, limits, unwrap) {
840
- if (!ArrayIsArray3(args)) return [];
974
+ if (!ArrayIsArray4(args)) return [];
841
975
  const sanitized = sanitizeValue(args, {
842
976
  maxDepth: limits.maxDepth,
843
977
  maxProperties: limits.maxProperties,
@@ -845,7 +979,7 @@ function sanitizeArguments(args, limits, unwrap) {
845
979
  allowErrors: true,
846
980
  unwrap
847
981
  });
848
- return ArrayIsArray3(sanitized) ? sanitized : [];
982
+ return ArrayIsArray4(sanitized) ? sanitized : [];
849
983
  }
850
984
  function invokeGlobalFunction(fn, thisArg, args, limits, unwrap, activity) {
851
985
  if (typeof fn !== "function") {
@@ -867,9 +1001,9 @@ function invokeGlobalFunction(fn, thisArg, args, limits, unwrap, activity) {
867
1001
  }
868
1002
  let result;
869
1003
  try {
870
- result = ReflectApply3(fn, thisArg, safeArgs);
1004
+ result = activity?.inHostContext ? activity.inHostContext(() => ReflectApply4(fn, thisArg, safeArgs)) : ReflectApply4(fn, thisArg, safeArgs);
871
1005
  } catch (error) {
872
- return failure(error);
1006
+ return failure(error, thisArg);
873
1007
  }
874
1008
  if (isThenable(result)) {
875
1009
  const end = activity?.begin();
@@ -880,7 +1014,7 @@ function invokeGlobalFunction(fn, thisArg, args, limits, unwrap, activity) {
880
1014
  },
881
1015
  (error) => {
882
1016
  end?.();
883
- return failure(error);
1017
+ return failure(error, thisArg);
884
1018
  }
885
1019
  );
886
1020
  }
@@ -899,7 +1033,7 @@ function createHostGlobalFunctionInvoker(context) {
899
1033
  return outcome instanceof Promise ? outcome.then(toEnvelope) : toEnvelope(outcome);
900
1034
  };
901
1035
  }
902
- function createGlobalFunctionGate(context, realm, unwrap) {
1036
+ function createGlobalFunctionGate(context, realm, unwrap, ownedBySandbox) {
903
1037
  const limits = resultLimits(context);
904
1038
  const max = resolveMaxGlobalFunctionCalls(context.config);
905
1039
  let calls = 0;
@@ -910,7 +1044,7 @@ function createGlobalFunctionGate(context, realm, unwrap) {
910
1044
  return outcome.json === void 0 ? void 0 : realm.parseJson(outcome.json);
911
1045
  };
912
1046
  return {
913
- gates: (target) => !isBuiltinMethod(target),
1047
+ gates: (target) => !isBuiltinMethod(target) && !(ownedBySandbox !== void 0 && typeof target === "function" && ownedBySandbox(target)),
914
1048
  call: (target, thisArg, args) => {
915
1049
  if (context.aborted) {
916
1050
  throw createSafeError("Execution aborted");
@@ -937,11 +1071,17 @@ var ReflectSet = Reflect.set;
937
1071
  var ReflectDefineProperty = Reflect.defineProperty;
938
1072
  var ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
939
1073
  var ReflectOwnKeys2 = Reflect.ownKeys;
940
- var ReflectApply4 = Reflect.apply;
1074
+ var ReflectApply5 = Reflect.apply;
1075
+ var ReflectHas = Reflect.has;
941
1076
  var ReflectConstruct = Reflect.construct;
942
1077
  var ObjectGetPrototypeOf3 = Object.getPrototypeOf;
943
1078
  var HostObjectPrototype = Object.prototype;
944
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
+ }
945
1085
  var PINNED_REFLECT_VALUES = /* @__PURE__ */ new Map();
946
1086
  for (const key of ReflectOwnKeys2(ReflectObject)) {
947
1087
  PINNED_REFLECT_VALUES.set(key, ReflectGet3(ReflectObject, key));
@@ -1167,17 +1307,60 @@ var INTERNAL_SLOT_BUILTINS = /* @__PURE__ */ new Set([
1167
1307
  ]);
1168
1308
  var INTERNAL_SLOT_TYPES = /* @__PURE__ */ new Set(["[object Promise]"]);
1169
1309
  var boundBuiltinMethods = /* @__PURE__ */ new WeakSet();
1310
+ var argumentGuards = /* @__PURE__ */ new WeakMap();
1311
+ var gatedArgumentGuards = /* @__PURE__ */ new WeakMap();
1312
+ function gatedArgumentGuardCache(gate) {
1313
+ let cache = gatedArgumentGuards.get(gate);
1314
+ if (!cache) {
1315
+ cache = /* @__PURE__ */ new WeakMap();
1316
+ gatedArgumentGuards.set(gate, cache);
1317
+ }
1318
+ return cache;
1319
+ }
1320
+ var guardedArguments = /* @__PURE__ */ new WeakMap();
1170
1321
  var JsonParse = JSON.parse;
1171
1322
  var JsonStringify2 = JSON.stringify;
1172
- function passesHostValuesToCallbacks(fn) {
1173
- return isBuiltinMethod(fn) || fn === JsonParse || fn === JsonStringify2 || typeof fn === "function" && boundBuiltinMethods.has(fn);
1323
+ var HOST_RECEIVER_MESSAGE = "A built-in method of a value passed in globals can only be called on a value passed in globals. Use the method of the same name of your own value.";
1324
+ var HOST_RECEIVER_KIND_MESSAGE = "A built-in method of a value passed in globals can only be called on a value of the same kind (an array method on an array, a Map method on a Map).";
1325
+ function isOfBuiltinKind(receiver, homes) {
1326
+ for (let h = 0; h < homes.length; h++) {
1327
+ const home = homes[h];
1328
+ if (home === HostObjectPrototype) {
1329
+ return true;
1330
+ }
1331
+ try {
1332
+ let proto = ObjectGetPrototypeOf3(receiver);
1333
+ for (let depth = 0; depth < 32 && proto !== null; depth++) {
1334
+ if (proto === home) {
1335
+ return true;
1336
+ }
1337
+ proto = ObjectGetPrototypeOf3(proto);
1338
+ }
1339
+ } catch {
1340
+ return false;
1341
+ }
1342
+ }
1343
+ return false;
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
+ ]);
1354
+ function passesHostValuesToCallbacks(fn, builtinMethod) {
1355
+ if (COMPARING_BUILTINS.has(fn)) return false;
1356
+ return builtinMethod || fn === JsonParse || fn === JsonStringify2 || typeof fn === "function" && boundBuiltinMethods.has(fn);
1174
1357
  }
1175
1358
  function isProxyable(value) {
1176
1359
  return value !== null && (typeof value === "object" || typeof value === "function");
1177
1360
  }
1178
1361
  function builtinTag(value) {
1179
1362
  try {
1180
- return ReflectApply4(ObjectToString, value, []);
1363
+ return ReflectApply5(ObjectToString, value, []);
1181
1364
  } catch {
1182
1365
  return "";
1183
1366
  }
@@ -1189,6 +1372,20 @@ function createSecureProxy(target, options = {}) {
1189
1372
  const cacheKey = getFullCacheKey(options);
1190
1373
  const gateCache = options.callGate ? gatedProxyCache(options.callGate) : void 0;
1191
1374
  const lookupCached = (obj) => gateCache ? gateCache.get(obj) : proxyCache.get(obj)?.get(cacheKey);
1375
+ const gateGuards = options.callGate ? gatedArgumentGuardCache(options.callGate) : void 0;
1376
+ const lookupGuard = (obj) => gateGuards ? gateGuards.get(obj) : argumentGuards.get(obj)?.get(cacheKey);
1377
+ const storeGuard = (obj, guard) => {
1378
+ if (gateGuards) {
1379
+ gateGuards.set(obj, guard);
1380
+ return;
1381
+ }
1382
+ let guards = argumentGuards.get(obj);
1383
+ if (!guards) {
1384
+ guards = /* @__PURE__ */ new Map();
1385
+ argumentGuards.set(obj, guards);
1386
+ }
1387
+ guards.set(cacheKey, guard);
1388
+ };
1192
1389
  const cached = lookupCached(target);
1193
1390
  if (cached) {
1194
1391
  return cached;
@@ -1198,14 +1395,27 @@ function createSecureProxy(target, options = {}) {
1198
1395
  const configuredMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
1199
1396
  const maxDepth = Number.isFinite(configuredMaxDepth) ? Math.max(configuredMaxDepth, MIN_MEMBRANE_RECURSION_DEPTH) : MIN_MEMBRANE_RECURSION_DEPTH;
1200
1397
  const throwOnBlocked = options.throwOnBlocked ?? options.levelConfig?.throwOnBlocked ?? false;
1398
+ const { ownedBySandbox, heldBySandbox } = options;
1399
+ const classifiesValues = ownedBySandbox !== void 0 || heldBySandbox !== void 0;
1400
+ const passesAsItIs = (value) => heldBySandbox !== void 0 && heldBySandbox(value) || ownedBySandbox !== void 0 && !proxySet.has(value) && ownedBySandbox(value);
1201
1401
  function proxyWithDepth(obj, depth) {
1202
1402
  if (!isProxyable(obj)) {
1203
1403
  return obj;
1204
1404
  }
1405
+ if (guardedArguments.has(obj)) {
1406
+ const guarded = guardedArguments.get(obj);
1407
+ if (!classifiesValues || !isProxyable(guarded)) {
1408
+ return guarded;
1409
+ }
1410
+ obj = guarded;
1411
+ }
1205
1412
  const cachedProxy = lookupCached(obj);
1206
1413
  if (cachedProxy) {
1207
1414
  return cachedProxy;
1208
1415
  }
1416
+ if (depth > 0 && passesAsItIs(obj)) {
1417
+ return obj;
1418
+ }
1209
1419
  if (depth > maxDepth) {
1210
1420
  throw createSafeError(
1211
1421
  `Security violation: secure-proxy recursion depth (${maxDepth}) exceeded. The value cannot be exposed without breaking the sandbox barrier.`,
@@ -1213,21 +1423,88 @@ function createSecureProxy(target, options = {}) {
1213
1423
  );
1214
1424
  }
1215
1425
  const hasInternalSlots = INTERNAL_SLOT_BUILTINS.has(builtinTag(obj));
1216
- const guardCallbackArguments = (args) => args.map((arg) => {
1217
- if (typeof arg !== "function" || proxySet.has(arg)) return arg;
1218
- const callback = arg;
1219
- const toSandbox = (value) => {
1220
- const laundered = launderHostError(value);
1221
- if (options.ownedBySandbox && isProxyable(laundered) && !proxySet.has(laundered) && options.ownedBySandbox(laundered)) {
1222
- return laundered;
1223
- }
1224
- const wrapped = isProxyable(laundered) && !isSafeError(laundered) ? proxyWithDepth(laundered, depth + 1) : laundered;
1225
- return options.exposeToSandbox ? options.exposeToSandbox(wrapped) : wrapped;
1426
+ const toSandbox = (value) => {
1427
+ if (!isProxyable(value)) {
1428
+ return value;
1429
+ }
1430
+ if (heldBySandbox && heldBySandbox(value)) {
1431
+ return value;
1432
+ }
1433
+ const laundered = launderHostError(value);
1434
+ const wrapped = isProxyable(laundered) && !isSafeError(laundered) ? proxyWithDepth(laundered, depth + 1) : laundered;
1435
+ return options.exposeToSandbox ? options.exposeToSandbox(wrapped) : wrapped;
1436
+ };
1437
+ const guardObjectArgument = (value) => {
1438
+ if (value === null || typeof value !== "object") return value;
1439
+ if (proxySet.has(value) || guardedArguments.has(value)) return value;
1440
+ if (heldBySandbox && heldBySandbox(value)) return value;
1441
+ const existing = lookupGuard(value);
1442
+ if (existing) return existing;
1443
+ if (Array.isArray(value)) return guardArrayArgument(value);
1444
+ const original = value;
1445
+ const guard = new Proxy(/* @__PURE__ */ Object.create(null), {
1446
+ get: (_shell, property) => guardMember(ReflectGet3(original, property, original), original),
1447
+ has: (_shell, property) => ReflectHas(original, property),
1448
+ // A function that lists the object (to copy or to serialize it, as JSON.stringify does)
1449
+ // sees the script's own properties, each as a data property holding what a read gives.
1450
+ ownKeys: () => ReflectOwnKeys2(original),
1451
+ getOwnPropertyDescriptor: (_shell, property) => {
1452
+ const descriptor = ReflectGetOwnPropertyDescriptor(original, property);
1453
+ if (!descriptor) return void 0;
1454
+ return {
1455
+ value: guardMember(ReflectGet3(original, property, original), original),
1456
+ writable: true,
1457
+ enumerable: descriptor.enumerable === true,
1458
+ configurable: true
1459
+ };
1460
+ },
1461
+ // What a host function stores in the object is a host value like any other
1462
+ set: (_shell, property, stored) => ReflectSet(original, property, toSandbox(stored), original)
1463
+ });
1464
+ storeGuard(original, guard);
1465
+ guardedArguments.set(guard, original);
1466
+ return guard;
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
+ };
1486
+ const guardMember = (member, holder) => {
1487
+ if (typeof member !== "function") return guardObjectArgument(member);
1488
+ const method = function guardedMethod(...hostArgs) {
1489
+ return guardArgument(ReflectApply5(member, holder, hostArgs.map(toSandbox)));
1226
1490
  };
1227
- return function guardedCallback(...hostArgs) {
1228
- return ReflectApply4(callback, toSandbox(this), hostArgs.map(toSandbox));
1491
+ guardedArguments.set(method, member);
1492
+ return method;
1493
+ };
1494
+ const guardCallback = (callback) => {
1495
+ const guarded = function guardedCallback(...hostArgs) {
1496
+ return ReflectApply5(callback, toSandbox(this), hostArgs.map(toSandbox));
1229
1497
  };
1230
- });
1498
+ guardedArguments.set(guarded, callback);
1499
+ return guarded;
1500
+ };
1501
+ const guardArgument = (arg) => {
1502
+ if (typeof arg === "function") {
1503
+ return proxySet.has(arg) || guardedArguments.has(arg) || heldBySandbox && heldBySandbox(arg) ? arg : guardCallback(arg);
1504
+ }
1505
+ return guardObjectArgument(arg);
1506
+ };
1507
+ const guardCallbackArguments = (args) => args.map(guardArgument);
1231
1508
  const proxy = new Proxy(obj, {
1232
1509
  get(target2, property, receiver) {
1233
1510
  const propName = typeof property === "symbol" ? property.toString() : property;
@@ -1270,7 +1547,7 @@ function createSecureProxy(target, options = {}) {
1270
1547
  if (typeof value === "function") {
1271
1548
  const tag = builtinTag(target2);
1272
1549
  if (INTERNAL_SLOT_TYPES.has(tag)) {
1273
- const boundMethod = ReflectApply4(FunctionBind, value, [target2]);
1550
+ const boundMethod = ReflectApply5(FunctionBind, value, [target2]);
1274
1551
  if (isBuiltinMethod(value)) {
1275
1552
  boundBuiltinMethods.add(boundMethod);
1276
1553
  }
@@ -1394,17 +1671,32 @@ function createSecureProxy(target, options = {}) {
1394
1671
  // Intercept function calls to proxy return values
1395
1672
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
1396
1673
  apply(target2, thisArg, argArray) {
1397
- const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
1674
+ const receiverIsReference = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function");
1675
+ const wrappedReceiver = receiverIsReference ? proxyToTarget.get(thisArg) : void 0;
1676
+ const unwrappedThis = wrappedReceiver !== void 0 ? wrappedReceiver : thisArg;
1677
+ if (classifiesValues && typeof wrappedReceiver === "function" && isFunctionTextMethod(target2)) {
1678
+ return hostFunctionText(wrappedReceiver);
1679
+ }
1398
1680
  if (options.callGate && options.callGate.gates(target2)) {
1399
1681
  const hostReceiver = unwrappedThis !== thisArg ? unwrappedThis : void 0;
1400
1682
  return options.callGate.call(target2, hostReceiver, argArray);
1401
1683
  }
1684
+ const homes = builtinMethodHomes(target2);
1685
+ const builtinMethod = homes !== void 0;
1686
+ if (builtinMethod && heldBySandbox !== void 0 && receiverIsReference) {
1687
+ if (wrappedReceiver === void 0) {
1688
+ throw createSafeError(HOST_RECEIVER_MESSAGE, "TypeError");
1689
+ }
1690
+ if (!isOfBuiltinKind(wrappedReceiver, homes)) {
1691
+ throw createSafeError(HOST_RECEIVER_KIND_MESSAGE, "TypeError");
1692
+ }
1693
+ }
1402
1694
  let result;
1403
1695
  try {
1404
- result = ReflectApply4(
1696
+ result = ReflectApply5(
1405
1697
  target2,
1406
1698
  unwrappedThis,
1407
- passesHostValuesToCallbacks(target2) ? guardCallbackArguments(argArray) : argArray
1699
+ passesHostValuesToCallbacks(target2, builtinMethod) ? guardCallbackArguments(argArray) : argArray
1408
1700
  );
1409
1701
  } catch (error) {
1410
1702
  throw launderHostError(error);
@@ -1594,6 +1886,18 @@ function isReferenceId(value) {
1594
1886
  return typeof value === "string" && REF_ID_PATTERN.test(value);
1595
1887
  }
1596
1888
 
1889
+ // libs/core/src/sidecar/reference-sidecar.ts
1890
+ var SidecarLimitError = class _SidecarLimitError extends Error {
1891
+ constructor(message, code, limit, current) {
1892
+ super(message);
1893
+ this.code = code;
1894
+ this.limit = limit;
1895
+ this.current = current;
1896
+ this.name = "SidecarLimitError";
1897
+ Object.setPrototypeOf(this, _SidecarLimitError.prototype);
1898
+ }
1899
+ };
1900
+
1597
1901
  // libs/core/src/sidecar/reference-resolver.ts
1598
1902
  var ReflectGet4 = Reflect.get;
1599
1903
  var NumberIsFinite3 = Number.isFinite;
@@ -1701,17 +2005,88 @@ var ReferenceResolver = class {
1701
2005
  /**
1702
2006
  * Check if resolution would exceed size limits
1703
2007
  *
2008
+ * Two limits apply: `maxResolvedSize` to what this value expands to, and
2009
+ * `maxTotalResolvedSize` to what the execution has had resolved so far plus what resolving
2010
+ * this value would add (see `predictAddedSize`).
2011
+ *
1704
2012
  * @param value - The value to check
1705
- * @returns true if resolution would exceed maxResolvedSize
2013
+ * @returns true if resolution would exceed maxResolvedSize or the execution's total
1706
2014
  */
1707
2015
  wouldExceedLimit(value) {
1708
2016
  try {
1709
2017
  const size = this.predictExpandedSize(value);
1710
- return size > this.config.maxResolvedSize;
2018
+ if (size > this.config.maxResolvedSize) {
2019
+ return true;
2020
+ }
2021
+ return !this.sidecar.canResolve(this.predictAddedSize(value, 0, /* @__PURE__ */ new Set()));
1711
2022
  } catch {
1712
2023
  return true;
1713
2024
  }
1714
2025
  }
2026
+ /**
2027
+ * Predict what resolving a value would add to the execution's total of resolved data,
2028
+ * WITHOUT allocating memory
2029
+ *
2030
+ * A stored value adds its size the first time it is resolved in the execution and nothing
2031
+ * afterwards (`counted` holds the ones this walk has seen). A composite adds the size of the
2032
+ * string it is joined into, every time, besides what its parts add.
2033
+ */
2034
+ predictAddedSize(value, depth, counted) {
2035
+ if (depth > this.config.maxResolutionDepth) {
2036
+ throw new ResolutionLimitError(
2037
+ `Maximum resolution depth exceeded (${this.config.maxResolutionDepth})`,
2038
+ "MAX_RESOLUTION_DEPTH",
2039
+ this.config.maxResolutionDepth,
2040
+ depth
2041
+ );
2042
+ }
2043
+ if (isReferenceId(value)) {
2044
+ if (counted.has(value) || this.sidecar.isResolved(value)) {
2045
+ return 0;
2046
+ }
2047
+ counted.add(value);
2048
+ return this.sidecar.getSize(value) ?? 0;
2049
+ }
2050
+ if (isCompositeHandle(value)) {
2051
+ const parts = value.__parts;
2052
+ const len = untrustedLength(parts);
2053
+ let sum = this.predictExpandedSize(value, depth);
2054
+ for (let i = 0; i < len; i++) {
2055
+ sum += this.predictAddedSize(untrustedAt(parts, i), depth + 1, counted);
2056
+ }
2057
+ return sum;
2058
+ }
2059
+ if (Array.isArray(value)) {
2060
+ const len = untrustedLength(value);
2061
+ let sum = 0;
2062
+ for (let i = 0; i < len; i++) {
2063
+ sum += this.predictAddedSize(untrustedAt(value, i), depth + 1, counted);
2064
+ }
2065
+ return sum;
2066
+ }
2067
+ if (value !== null && typeof value === "object") {
2068
+ let sum = 0;
2069
+ for (const val of Object.values(value)) {
2070
+ sum += this.predictAddedSize(val, depth + 1, counted);
2071
+ }
2072
+ return sum;
2073
+ }
2074
+ return 0;
2075
+ }
2076
+ /**
2077
+ * Run a step that counts resolved data against the execution's total; when the sidecar
2078
+ * refuses it, the refusal is thrown as the resolution error callers of `resolve` handle
2079
+ */
2080
+ withinTotal(count) {
2081
+ try {
2082
+ count();
2083
+ } catch (error) {
2084
+ if (error instanceof SidecarLimitError) {
2085
+ throw new ResolutionLimitError(error.message, error.code, error.limit, error.current);
2086
+ }
2087
+ throw error;
2088
+ }
2089
+ }
1715
2090
  /**
1716
2091
  * Resolve all reference IDs in a value tree
1717
2092
  *
@@ -1734,7 +2109,10 @@ var ReferenceResolver = class {
1734
2109
  );
1735
2110
  }
1736
2111
  if (isReferenceId(value)) {
1737
- const data = this.sidecar.retrieveString(value);
2112
+ let data;
2113
+ this.withinTotal(() => {
2114
+ data = this.sidecar.resolveString(value);
2115
+ });
1738
2116
  if (data === void 0) {
1739
2117
  throw new Error(`Unknown reference: ${value}`);
1740
2118
  }
@@ -1772,6 +2150,8 @@ var ReferenceResolver = class {
1772
2150
  * Resolve a composite handle by concatenating its parts
1773
2151
  */
1774
2152
  resolveComposite(handle, depth) {
2153
+ const joinedSize = this.predictExpandedSize(handle, depth);
2154
+ this.withinTotal(() => this.sidecar.countResolved(joinedSize));
1775
2155
  const out = [];
1776
2156
  const source = handle.__parts;
1777
2157
  const len = untrustedLength(source);
@@ -1787,28 +2167,38 @@ var ReferenceResolver = class {
1787
2167
  /**
1788
2168
  * Check if a value contains any reference IDs
1789
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
+ *
1790
2175
  * @param value - The value to check
1791
- * @param depth - Current recursion depth (internal)
2176
+ * @param _depth - Unused; kept for callers that pass a depth
1792
2177
  * @returns true if the value or any nested value is a reference
1793
2178
  */
1794
- containsReferences(value, depth = 0) {
1795
- if (depth > this.config.maxResolutionDepth) {
1796
- return false;
1797
- }
1798
- if (isReferenceId(value) || isCompositeHandle(value)) {
1799
- return true;
1800
- }
1801
- if (Array.isArray(value)) {
1802
- const len = untrustedLength(value);
1803
- for (let i = 0; i < len; i++) {
1804
- if (this.containsReferences(untrustedAt(value, i), depth + 1)) {
1805
- 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));
1806
2195
  }
2196
+ continue;
2197
+ }
2198
+ const members = Object.values(current);
2199
+ for (let i = 0; i < members.length; i++) {
2200
+ pending.push(members[i]);
1807
2201
  }
1808
- return false;
1809
- }
1810
- if (value !== null && typeof value === "object") {
1811
- return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
1812
2202
  }
1813
2203
  return false;
1814
2204
  }
@@ -1881,6 +2271,8 @@ var MemoryTracker = class {
1881
2271
  trackedBytes = 0;
1882
2272
  peakTrackedBytes = 0;
1883
2273
  allocationCount = 0;
2274
+ /** Whether this tracker has refused an allocation since it was started */
2275
+ limitExceeded = false;
1884
2276
  config;
1885
2277
  constructor(config = {}) {
1886
2278
  this.config = {
@@ -1897,6 +2289,14 @@ var MemoryTracker = class {
1897
2289
  this.trackedBytes = 0;
1898
2290
  this.peakTrackedBytes = 0;
1899
2291
  this.allocationCount = 0;
2292
+ this.limitExceeded = false;
2293
+ }
2294
+ /**
2295
+ * Whether the limit was exceeded since tracking started: the tracker itself refused an
2296
+ * allocation. An error that only says so about itself is not evidence of that.
2297
+ */
2298
+ hasExceededLimit() {
2299
+ return this.limitExceeded;
1900
2300
  }
1901
2301
  /**
1902
2302
  * Track an allocation
@@ -1907,6 +2307,7 @@ var MemoryTracker = class {
1907
2307
  track(bytes) {
1908
2308
  if (typeof bytes !== "number" || Number.isNaN(bytes)) {
1909
2309
  if (this.config.memoryLimit > 0) {
2310
+ this.limitExceeded = true;
1910
2311
  throw new MemoryLimitError(
1911
2312
  "Memory limit exceeded: allocation size is not a number",
1912
2313
  this.trackedBytes,
@@ -1922,6 +2323,7 @@ var MemoryTracker = class {
1922
2323
  this.peakTrackedBytes = this.trackedBytes;
1923
2324
  }
1924
2325
  if (this.config.memoryLimit > 0 && this.trackedBytes > this.config.memoryLimit) {
2326
+ this.limitExceeded = true;
1925
2327
  throw new MemoryLimitError(
1926
2328
  `Memory limit exceeded: ${this.formatBytes(this.trackedBytes)} used > ${this.formatBytes(
1927
2329
  this.config.memoryLimit
@@ -2349,6 +2751,7 @@ function createHostToolBridge(executionContext, options) {
2349
2751
  "Tool returned an unsupported value",
2350
2752
  "TOOL_RESULT_NOT_SAFE"
2351
2753
  );
2754
+ executionContext.onToolBridgeFailure?.();
2352
2755
  return serializeResponse(
2353
2756
  {
2354
2757
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -2358,6 +2761,34 @@ function createHostToolBridge(executionContext, options) {
2358
2761
  maxPayloadBytes
2359
2762
  );
2360
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
+ }
2361
2792
  if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
2362
2793
  const size = utf8ByteLength2(sanitizedResult);
2363
2794
  if (size >= referenceConfig.extractionThreshold) {
@@ -2365,6 +2796,20 @@ function createHostToolBridge(executionContext, options) {
2365
2796
  const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
2366
2797
  sanitizedResult = refId;
2367
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
+ );
2368
2813
  }
2369
2814
  }
2370
2815
  }
@@ -2379,6 +2824,7 @@ function createHostToolBridge(executionContext, options) {
2379
2824
  "Tool result must be JSON-serializable",
2380
2825
  "TOOL_RESULT_NOT_JSON"
2381
2826
  );
2827
+ executionContext.onToolBridgeFailure?.();
2382
2828
  return serializeResponse(
2383
2829
  {
2384
2830
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -2389,6 +2835,7 @@ function createHostToolBridge(executionContext, options) {
2389
2835
  );
2390
2836
  }
2391
2837
  if (utf8ByteLength2(okJson) > maxPayloadBytes) {
2838
+ executionContext.onToolBridgeFailure?.();
2392
2839
  return serializeResponse(
2393
2840
  {
2394
2841
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -2565,8 +3012,8 @@ function redactLine(line) {
2565
3012
  }
2566
3013
  function sanitizeStackTrace(stack, sanitize = true) {
2567
3014
  if (typeof stack !== "string" || !stack || !sanitize) return stack;
2568
- const bounded = stack.length > MAX_STACK_LENGTH ? stack.slice(0, MAX_STACK_LENGTH) : stack;
2569
- return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
3015
+ const bounded2 = stack.length > MAX_STACK_LENGTH ? stack.slice(0, MAX_STACK_LENGTH) : stack;
3016
+ return bounded2.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
2570
3017
  }
2571
3018
 
2572
3019
  // libs/core/src/console-handler.ts
@@ -2595,15 +3042,73 @@ var CONSOLE_FACTORY_SOURCE = `
2595
3042
  var toText = ''.constructor;
2596
3043
  var freeze = Object.freeze;
2597
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
+ }
2598
3098
 
2599
- 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) {
2600
3103
  if (value === undefined) return 'undefined';
2601
3104
  if (value === null) return 'null';
2602
3105
  if (typeof value === 'object') {
3106
+ if (room <= 0) throw TOO_LARGE;
2603
3107
  try {
2604
- var json = stringify(value);
3108
+ var json = stringifyWithin(value, room);
2605
3109
  return json === undefined ? '' : json;
2606
3110
  } catch (e) {
3111
+ if (e === TOO_LARGE) throw e;
2607
3112
  return toText(value);
2608
3113
  }
2609
3114
  }
@@ -2614,19 +3119,38 @@ var CONSOLE_FACTORY_SOURCE = `
2614
3119
  var callCount = 0;
2615
3120
  var totalBytes = 0;
2616
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
+
2617
3126
  function method(level) {
2618
3127
  return (...args) => {
2619
3128
  callCount++;
2620
3129
  if (callCount > maxCalls) {
2621
3130
  throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
2622
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.
2623
3134
  var line = '';
2624
3135
  for (var i = 0; i < args.length; i++) {
2625
- 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
+ }
2626
3150
  }
2627
3151
  totalBytes += line.length;
2628
3152
  if (totalBytes > maxBytes) {
2629
- throw new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
3153
+ throw tooLarge();
2630
3154
  }
2631
3155
  try {
2632
3156
  write(level, line);
@@ -2715,9 +3239,11 @@ var SandboxScript = api.SandboxScript;
2715
3239
  var ReusableSandboxScript = api.ReusableSandboxScript;
2716
3240
 
2717
3241
  // libs/core/src/sandbox-rejections.ts
3242
+ var import_util = require("util");
2718
3243
  var HostPromisePrototype = Promise.prototype;
2719
3244
  var ObjectGetPrototypeOf4 = Object.getPrototypeOf;
2720
- var ReflectApply5 = Reflect.apply;
3245
+ var ReflectApply6 = Reflect.apply;
3246
+ var isEnginePromise = import_util.types.isPromise;
2721
3247
  var MAX_PROTOTYPE_CHAIN = 32;
2722
3248
  var MAX_INSTALLS = 8;
2723
3249
  function isHostPromise(promise) {
@@ -2737,6 +3263,9 @@ function isHostPromise(promise) {
2737
3263
  }
2738
3264
  return false;
2739
3265
  }
3266
+ function isSandboxPromise(value) {
3267
+ return isEnginePromise(value) && !isHostPromise(value);
3268
+ }
2740
3269
  var PROBE_EVENT = `enclave-vm:rejection-guard:${Math.random().toString(36).slice(2)}`;
2741
3270
  var active = false;
2742
3271
  var optedOut = false;
@@ -2749,14 +3278,14 @@ function wrapEmit(previous) {
2749
3278
  return false;
2750
3279
  }
2751
3280
  if (active) {
2752
- if (event === "unhandledRejection" && !isHostPromise(args[1])) {
3281
+ if (event === "unhandledRejection" && isSandboxPromise(args[1])) {
2753
3282
  return true;
2754
3283
  }
2755
- if (event === "rejectionHandled" && !isHostPromise(args[0])) {
3284
+ if (event === "rejectionHandled" && isSandboxPromise(args[0])) {
2756
3285
  return true;
2757
3286
  }
2758
3287
  }
2759
- return ReflectApply5(previous, this, [event, ...args]);
3288
+ return ReflectApply6(previous, this, [event, ...args]);
2760
3289
  };
2761
3290
  }
2762
3291
  function guardSandboxRejections() {
@@ -2776,18 +3305,66 @@ function guardSandboxRejections() {
2776
3305
  process.emit = wrapEmit(process.emit);
2777
3306
  }
2778
3307
 
2779
- // libs/core/src/tool-namespaces.ts
2780
- var TOOL_NAMESPACE_FACTORY_SOURCE = `
2781
- (function () {
2782
- 'use strict';
2783
- var parse = JSON.parse;
2784
- var freeze = Object.freeze;
2785
- var isArray = Array.isArray;
2786
-
2787
- function isSafeKey(key) {
2788
- return typeof key === 'string' && key.length > 0 &&
2789
- !(key.charAt(0) === '_' && key.charAt(1) === '_') &&
2790
- key !== 'constructor' && key !== 'prototype';
3308
+ // libs/core/src/thrown-value.ts
3309
+ var MAX_THROWN_NAME_LENGTH = 256;
3310
+ var MAX_THROWN_MESSAGE_LENGTH = 16 * 1024;
3311
+ var MAX_THROWN_STACK_LENGTH = 64 * 1024;
3312
+ var ReflectGet5 = Reflect.get;
3313
+ function bounded(text, max) {
3314
+ return text.length > max ? text.slice(0, max) : text;
3315
+ }
3316
+ function stringMember(value, key, max) {
3317
+ try {
3318
+ const member = ReflectGet5(value, key);
3319
+ return typeof member === "string" ? bounded(member, max) : void 0;
3320
+ } catch {
3321
+ return void 0;
3322
+ }
3323
+ }
3324
+ function describeThrown(thrown) {
3325
+ if (typeof thrown === "string") {
3326
+ return { message: bounded(thrown, MAX_THROWN_MESSAGE_LENGTH) };
3327
+ }
3328
+ if (thrown === null || thrown === void 0) {
3329
+ return { message: `The script threw ${String(thrown)}` };
3330
+ }
3331
+ if (typeof thrown === "symbol") {
3332
+ return { message: "The script threw a symbol" };
3333
+ }
3334
+ if (typeof thrown !== "object" && typeof thrown !== "function") {
3335
+ return { message: bounded(`The script threw the ${typeof thrown} ${String(thrown)}`, MAX_THROWN_MESSAGE_LENGTH) };
3336
+ }
3337
+ const name = stringMember(thrown, "name", MAX_THROWN_NAME_LENGTH);
3338
+ const message = stringMember(thrown, "message", MAX_THROWN_MESSAGE_LENGTH);
3339
+ const stack = stringMember(thrown, "stack", MAX_THROWN_STACK_LENGTH);
3340
+ return {
3341
+ ...name !== void 0 ? { name } : {},
3342
+ ...message !== void 0 ? { message } : {},
3343
+ ...stack !== void 0 ? { stack } : {}
3344
+ };
3345
+ }
3346
+ function isMemoryLimitPayload(thrown) {
3347
+ if (thrown === null || typeof thrown !== "object" && typeof thrown !== "function") return false;
3348
+ try {
3349
+ return ReflectGet5(thrown, "code") === "MEMORY_LIMIT_EXCEEDED";
3350
+ } catch {
3351
+ return false;
3352
+ }
3353
+ }
3354
+ var THROWN_WITHOUT_MESSAGE = "The script threw a value that is not an error";
3355
+
3356
+ // libs/core/src/tool-namespaces.ts
3357
+ var TOOL_NAMESPACE_FACTORY_SOURCE = `
3358
+ (function () {
3359
+ 'use strict';
3360
+ var parse = JSON.parse;
3361
+ var freeze = Object.freeze;
3362
+ var isArray = Array.isArray;
3363
+
3364
+ function isSafeKey(key) {
3365
+ return typeof key === 'string' && key.length > 0 &&
3366
+ !(key.charAt(0) === '_' && key.charAt(1) === '_') &&
3367
+ key !== 'constructor' && key !== 'prototype';
2791
3368
  }
2792
3369
 
2793
3370
  function bind(callTool, toolName) {
@@ -2828,35 +3405,1315 @@ function buildToolNamespaceBindings(install, callTool, namespaces) {
2828
3405
  return namespaces.map((ns) => ({ name: ns.name, value: built[ns.name] }));
2829
3406
  }
2830
3407
 
2831
- // libs/core/src/deadline-guard.ts
2832
- var walk = __toESM(require("acorn-walk"));
2833
- var REALM_TICK_FN = "__safe_tick";
2834
- var TICKS_PER_CLOCK_CHECK = 256;
2835
- function realmTickSource(timeoutMs) {
2836
- const timeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.floor(timeoutMs) : 0;
2837
- return `
2838
- (function (timeoutMs) {
2839
- 'use strict';
2840
- var now = Date.now;
2841
- // No positive timeout means no deadline.
2842
- var deadline = timeoutMs > 0 ? now() + timeoutMs : Infinity;
2843
- var expired = false;
2844
- var count = 0;
2845
- var message = 'Script execution timed out after ' + timeoutMs + 'ms';
2846
- Object.defineProperty(globalThis, ${JSON.stringify(REALM_TICK_FN)}, {
2847
- value: function () {
2848
- if (!expired) {
2849
- count++;
2850
- if (count % ${TICKS_PER_CLOCK_CHECK} !== 0 || now() < deadline) return;
2851
- expired = true;
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
+
3428
+ // libs/core/src/deadline-guard.ts
3429
+ var walk = __toESM(require("acorn-walk"));
3430
+ var REALM_TICK_FN = "__safe_tick";
3431
+ var TICKS_PER_CLOCK_CHECK = 256;
3432
+ var TICKS_AFTER_END = 1024;
3433
+ var EXECUTION_ENDED_MESSAGE = "Script execution has ended";
3434
+ function realmTickSource(timeoutMs) {
3435
+ const timeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.floor(timeoutMs) : 0;
3436
+ return `
3437
+ (function (timeoutMs) {
3438
+ 'use strict';
3439
+ var now = Date.now;
3440
+ // No positive timeout means no deadline.
3441
+ var deadline = timeoutMs > 0 ? now() + timeoutMs : Infinity;
3442
+ var expired = false;
3443
+ var count = 0;
3444
+ // Set when the execution has ended; what the script left behind then gets graceLeft more
3445
+ // checks to settle in.
3446
+ var ended = false;
3447
+ var graceLeft = ${TICKS_AFTER_END};
3448
+ var message = 'Script execution timed out after ' + timeoutMs + 'ms';
3449
+ Object.defineProperty(globalThis, ${JSON.stringify(REALM_TICK_FN)}, {
3450
+ value: function () {
3451
+ if (!expired) {
3452
+ if (ended) {
3453
+ if (graceLeft-- > 0) return;
3454
+ } else {
3455
+ count++;
3456
+ if (count % ${TICKS_PER_CLOCK_CHECK} !== 0 || now() < deadline) return;
3457
+ }
3458
+ expired = true;
3459
+ }
3460
+ throw message;
3461
+ },
3462
+ writable: false,
3463
+ configurable: false,
3464
+ enumerable: false
3465
+ });
3466
+ return function () {
3467
+ if (!expired && !ended) {
3468
+ ended = true;
3469
+ message = ${JSON.stringify(EXECUTION_ENDED_MESSAGE)};
3470
+ }
3471
+ };
3472
+ })(${timeout})
3473
+ `.trim();
3474
+ }
3475
+
3476
+ // libs/core/src/types.ts
3477
+ var SECURITY_LEVEL_CONFIGS = {
3478
+ /**
3479
+ * STRICT: Maximum security for untrusted code
3480
+ *
3481
+ * Use for:
3482
+ * - AI-generated code from external sources
3483
+ * - User-submitted scripts
3484
+ * - Untrusted third-party integrations
3485
+ *
3486
+ * Characteristics:
3487
+ * - Short timeout (5s)
3488
+ * - Low iteration limits (1000)
3489
+ * - Limited tool calls (10)
3490
+ * - Deep value sanitization
3491
+ * - Full stack trace sanitization
3492
+ */
3493
+ STRICT: {
3494
+ timeout: 5e3,
3495
+ maxIterations: 1e3,
3496
+ maxToolCalls: 10,
3497
+ maxSanitizeDepth: 5,
3498
+ maxSanitizeProperties: 50,
3499
+ sanitizeStackTraces: true,
3500
+ blockTimingAPIs: true,
3501
+ allowUnboundedLoops: false,
3502
+ unicodeSecurityCheck: true,
3503
+ allowFunctionsInGlobals: false,
3504
+ maxConsoleOutputBytes: 64 * 1024,
3505
+ // 64KB - prevent I/O flood attacks
3506
+ maxConsoleCalls: 100,
3507
+ secureProxy: {
3508
+ blockConstructor: true,
3509
+ blockPrototype: true,
3510
+ blockLegacyAccessors: true,
3511
+ proxyMaxDepth: 5,
3512
+ throwOnBlocked: true
3513
+ }
3514
+ },
3515
+ /**
3516
+ * SECURE: High security with more headroom
3517
+ *
3518
+ * Use for:
3519
+ * - AI-generated code from trusted models
3520
+ * - Internal automation scripts
3521
+ * - Controlled multi-tenant environments
3522
+ *
3523
+ * Characteristics:
3524
+ * - Moderate timeout (15s)
3525
+ * - Moderate iteration limits (5000)
3526
+ * - Moderate tool calls (50)
3527
+ * - Standard value sanitization
3528
+ * - Stack trace sanitization
3529
+ */
3530
+ SECURE: {
3531
+ timeout: 15e3,
3532
+ maxIterations: 5e3,
3533
+ maxToolCalls: 50,
3534
+ maxSanitizeDepth: 10,
3535
+ maxSanitizeProperties: 100,
3536
+ sanitizeStackTraces: true,
3537
+ blockTimingAPIs: false,
3538
+ allowUnboundedLoops: false,
3539
+ unicodeSecurityCheck: true,
3540
+ allowFunctionsInGlobals: false,
3541
+ maxConsoleOutputBytes: 256 * 1024,
3542
+ // 256KB
3543
+ maxConsoleCalls: 500,
3544
+ secureProxy: {
3545
+ blockConstructor: true,
3546
+ blockPrototype: true,
3547
+ blockLegacyAccessors: true,
3548
+ proxyMaxDepth: 10,
3549
+ throwOnBlocked: true
3550
+ }
3551
+ },
3552
+ /**
3553
+ * STANDARD: Balanced security and functionality (DEFAULT)
3554
+ *
3555
+ * Use for:
3556
+ * - Internal tools and scripts
3557
+ * - Development and testing
3558
+ * - Trusted environments
3559
+ *
3560
+ * Characteristics:
3561
+ * - Standard timeout (30s)
3562
+ * - Standard iteration limits (10000)
3563
+ * - Standard tool calls (100)
3564
+ * - Basic value sanitization
3565
+ * - Minimal stack trace sanitization
3566
+ */
3567
+ STANDARD: {
3568
+ timeout: 3e4,
3569
+ maxIterations: 1e4,
3570
+ maxToolCalls: 100,
3571
+ maxSanitizeDepth: 20,
3572
+ maxSanitizeProperties: 500,
3573
+ sanitizeStackTraces: false,
3574
+ blockTimingAPIs: false,
3575
+ allowUnboundedLoops: true,
3576
+ unicodeSecurityCheck: false,
3577
+ allowFunctionsInGlobals: false,
3578
+ maxConsoleOutputBytes: 1024 * 1024,
3579
+ // 1MB
3580
+ maxConsoleCalls: 1e3,
3581
+ secureProxy: {
3582
+ blockConstructor: true,
3583
+ blockPrototype: true,
3584
+ blockLegacyAccessors: true,
3585
+ proxyMaxDepth: 15,
3586
+ throwOnBlocked: true
3587
+ }
3588
+ },
3589
+ /**
3590
+ * PERMISSIVE: Minimal restrictions
3591
+ *
3592
+ * Use for:
3593
+ * - Local development only
3594
+ * - Debugging
3595
+ * - Performance testing
3596
+ *
3597
+ * WARNING: Not recommended for production use with untrusted code
3598
+ *
3599
+ * Characteristics:
3600
+ * - Long timeout (60s)
3601
+ * - High iteration limits (100000)
3602
+ * - High tool calls (1000)
3603
+ * - Minimal sanitization
3604
+ * - No stack trace sanitization
3605
+ * - All features enabled
3606
+ */
3607
+ PERMISSIVE: {
3608
+ timeout: 6e4,
3609
+ maxIterations: 1e5,
3610
+ maxToolCalls: 1e3,
3611
+ maxSanitizeDepth: 50,
3612
+ maxSanitizeProperties: 1e3,
3613
+ sanitizeStackTraces: false,
3614
+ blockTimingAPIs: false,
3615
+ allowUnboundedLoops: true,
3616
+ unicodeSecurityCheck: false,
3617
+ allowFunctionsInGlobals: true,
3618
+ maxConsoleOutputBytes: 10 * 1024 * 1024,
3619
+ // 10MB
3620
+ maxConsoleCalls: 1e4,
3621
+ secureProxy: {
3622
+ blockConstructor: false,
3623
+ // Allow constructor access for development/debugging
3624
+ blockPrototype: true,
3625
+ // Still block prototype for safety
3626
+ blockLegacyAccessors: true,
3627
+ proxyMaxDepth: 20,
3628
+ throwOnBlocked: false
3629
+ // Return undefined instead of throwing for development
3630
+ }
3631
+ }
3632
+ };
3633
+ var DEFAULT_DOUBLE_VM_CONFIG = {
3634
+ enabled: true,
3635
+ parentTimeoutBuffer: 1e3,
3636
+ parentValidation: {
3637
+ validateOperationNames: true,
3638
+ maxOperationsPerSecond: 100,
3639
+ blockSuspiciousSequences: true,
3640
+ rapidEnumerationThreshold: 30,
3641
+ rapidEnumerationOverrides: {},
3642
+ suspiciousPatterns: []
3643
+ // Default patterns added at runtime
3644
+ }
3645
+ };
3646
+
3647
+ // libs/core/src/enclave-options.ts
3648
+ function describe(value) {
3649
+ if (value === null) return "null";
3650
+ if (typeof value === "number") return String(value);
3651
+ if (Array.isArray(value)) return "an array";
3652
+ if (typeof value === "string") return "a string";
3653
+ return `a value of type ${typeof value}`;
3654
+ }
3655
+ function numericLiteral(name, value) {
3656
+ if (typeof value !== "number" || !Number.isFinite(value)) {
3657
+ throw new TypeError(`${name} must be a finite number, got ${describe(value)}`);
3658
+ }
3659
+ return String(value);
3660
+ }
3661
+ function booleanLiteral(name, value) {
3662
+ if (typeof value !== "boolean") {
3663
+ throw new TypeError(`${name} must be true or false, got ${describe(value)}`);
3664
+ }
3665
+ return value ? "true" : "false";
3666
+ }
3667
+
3668
+ // libs/core/src/realm-stack.ts
3669
+ var STACK_CAPTURE_OFF_SOURCE = `
3670
+ (function () {
3671
+ 'use strict';
3672
+ try {
3673
+ Object.defineProperty(Error, 'stackTraceLimit', {
3674
+ value: undefined,
3675
+ writable: false,
3676
+ configurable: false,
3677
+ enumerable: false
3678
+ });
3679
+ } catch (e) { /* defined already */ }
3680
+ })();
3681
+ `.trim();
3682
+
3683
+ // libs/core/src/realm-memory.ts
3684
+ var ARRAY_ELEMENT_BYTES = 8;
3685
+ var ARRAY_START_FN = "__safe_arrayStart";
3686
+ var ARRAY_SPREAD_FN = "__safe_spread";
3687
+ var ARRAY_FINISH_FN = "__safe_array";
3688
+ var ARRAY_SET_FN = "__safe_set";
3689
+ var ARRAY_SLOT_FN = "__safe_slot";
3690
+ function realmArrayAccountingSource(memoryLimit) {
3691
+ return `
3692
+ (function (memoryLimit, track) {
3693
+ 'use strict';
3694
+ // Everything the patched functions use is taken now: none of it is looked up again on an
3695
+ // object a script can write to.
3696
+ var apply = Reflect.apply;
3697
+ var isArray = Array.isArray;
3698
+ var defineProperty = Object.defineProperty;
3699
+ var objectCreate = Object.create;
3700
+ var ObjectCtor = Object;
3701
+ var construct = Reflect.construct;
3702
+ var ownKeys = Reflect.ownKeys;
3703
+ var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
3704
+ var ProxyCtor = typeof Proxy === 'function' ? Proxy : undefined;
3705
+ var RangeErrorCtor = RangeError;
3706
+ var TypeErrorCtor = TypeError;
3707
+ var StringCtor = String;
3708
+ var arrayProto = Array.prototype;
3709
+ var stringProto = String.prototype;
3710
+ var ArrayCtor = Array;
3711
+ var iteratorSymbol = Symbol.iterator;
3712
+ var speciesSymbol = Symbol.species;
3713
+ var spreadableSymbol = Symbol.isConcatSpreadable;
3714
+ var asyncIteratorSymbol = Symbol.asyncIterator;
3715
+ var MAX_SAFE_INTEGER = 9007199254740991;
3716
+ var limited = memoryLimit > 0 && typeof track === 'function';
3717
+ var BYTES = ${ARRAY_ELEMENT_BYTES};
3718
+ // Charged to the tracker in batches: a call into the host for every pushed element is not
3719
+ // affordable, and what is pending is at most this much.
3720
+ var BATCH = 4096;
3721
+ var pending = 0;
3722
+
3723
+ // A refusal goes through the tracker, which answers an amount over the limit with the
3724
+ // execution's memory-limit error; the RangeError is for a tracker that did not.
3725
+ function refuse(label, bytes) {
3726
+ // A finite amount: a length a script made up can be anything
3727
+ if (!(bytes <= MAX_SAFE_INTEGER)) bytes = MAX_SAFE_INTEGER;
3728
+ track(bytes > memoryLimit ? bytes : memoryLimit + 1);
3729
+ throw new RangeErrorCtor(label + ' would exceed memory limit');
3730
+ }
3731
+
3732
+ /** Rule 1: an array of that many elements is not made. */
3733
+ function checkLength(length, label) {
3734
+ if (limited && typeof length === 'number' && length * BYTES > memoryLimit) refuse(label, length * BYTES);
3735
+ }
3736
+
3737
+ /** Rule 2: that many elements were added. */
3738
+ function charge(elements) {
3739
+ if (!limited || !(elements > 0)) return;
3740
+ pending += elements * BYTES;
3741
+ if (pending >= BATCH) {
3742
+ var bytes = pending;
3743
+ pending = 0;
3744
+ track(bytes);
3745
+ }
3746
+ }
3747
+
3748
+ function lengthOf(value) {
3749
+ return isArray(value) ? value.length : 0;
3750
+ }
3751
+
3752
+ // Rule 3: the conversions of the language, done once. Each throws where the built-in would
3753
+ // (a Symbol, a BigInt), and may run code of the script (valueOf, toString): once.
3754
+
3755
+ /** ToIntegerOrInfinity */
3756
+ function toInteger(value) {
3757
+ var number = +value;
3758
+ if (number !== number) return 0;
3759
+ if (number === Infinity || number === -Infinity) return number;
3760
+ return number < 0 ? -((-number) - ((-number) % 1)) : number - (number % 1);
3761
+ }
3762
+
3763
+ /** ToLength */
3764
+ function toLength(value) {
3765
+ var integer = toInteger(value);
3766
+ if (integer <= 0) return 0;
3767
+ return integer > MAX_SAFE_INTEGER ? MAX_SAFE_INTEGER : integer;
3768
+ }
3769
+
3770
+ /** A start or end argument relative to a length, as fill, slice and the like read it. */
3771
+ function relativeIndex(value, length, whenUndefined) {
3772
+ if (value === undefined) return whenUndefined;
3773
+ var relative = toInteger(value);
3774
+ if (relative < 0) {
3775
+ var fromEnd = length + relative;
3776
+ return fromEnd > 0 ? fromEnd : 0;
3777
+ }
3778
+ return relative < length ? relative : length;
3779
+ }
3780
+
3781
+ /** ToString, for a value that is not null or undefined */
3782
+ function toText(value) {
3783
+ if (typeof value === 'string') return value;
3784
+ if (typeof value === 'symbol') throw new TypeErrorCtor('Cannot convert a Symbol value to a string');
3785
+ return StringCtor(value);
3786
+ }
3787
+
3788
+ function isObject(value) {
3789
+ return value !== null && (typeof value === 'object' || typeof value === 'function');
3790
+ }
3791
+
3792
+ /** ToObject: what a built-in works on. Null for a receiver the built-in refuses. */
3793
+ function toObject(value) {
3794
+ if (value === null || value === undefined) return null;
3795
+ return isObject(value) ? value : ObjectCtor(value);
3796
+ }
3797
+
3798
+ /**
3799
+ * A plain array of what a source answers for its first slots. Each slot is asked once, with
3800
+ * the source itself as the receiver of the read; with \`holes\`, a slot the source does not
3801
+ * have stays empty. The caller has checked the length: this makes an array of it.
3802
+ */
3803
+ function snapshot(source, length, holes) {
3804
+ var copy = [];
3805
+ for (var i = 0; i < length; i++) {
3806
+ if (!holes || i in source) copy[i] = source[i];
3807
+ }
3808
+ if (copy.length !== length) copy.length = length;
3809
+ return copy;
3810
+ }
3811
+
3812
+ /**
3813
+ * What a built-in is given to read a source by its length: the length that was checked, and
3814
+ * each slot when the built-in asks for it, read from the source itself. Nothing else (no
3815
+ * prototype, no iterator), so the built-in can only read it that way, and it reads a slot
3816
+ * when it gets to it, as it does on the source: what a mapping function changed in between
3817
+ * is what it finds. The handler has no prototype either: what a proxy looks up on its
3818
+ * handler is not looked up on an object a script can write to.
3819
+ */
3820
+ function slotsOf(source, length) {
3821
+ var handler = objectCreate(null);
3822
+ handler.get = function (target, key) {
3823
+ if (key === 'length') return length;
3824
+ return typeof key === 'string' ? source[key] : undefined;
3825
+ };
3826
+ return new ProxyCtor(objectCreate(null), handler);
3827
+ }
3828
+
3829
+ /**
3830
+ * The empty array a built-in would make for a result of the receiver's kind
3831
+ * (ArraySpeciesCreate): null for a plain array, which the caller makes itself.
3832
+ */
3833
+ function emptyOfKind(receiver) {
3834
+ if (!isArray(receiver)) return null;
3835
+ var kind = receiver.constructor;
3836
+ if (kind === ArrayCtor) return null;
3837
+ if (isObject(kind)) {
3838
+ kind = kind[speciesSymbol];
3839
+ if (kind === null) kind = undefined;
3840
+ }
3841
+ if (kind === undefined || kind === ArrayCtor) return null;
3842
+ return construct(kind, [0]);
3843
+ }
3844
+
3845
+ // The accounting is installed in full or the realm is not set up. A part of it that cannot
3846
+ // be put in place (a global or a method that cannot be replaced any more) is not skipped:
3847
+ // the checks that rest on it would be off, and nothing would say so.
3848
+ function cannotInstall(what) {
3849
+ throw new TypeErrorCtor('Array accounting: ' + what + ' of the realm cannot be replaced');
3850
+ }
3851
+
3852
+ // A proxy a script makes answers for its length and its slots as its handler likes, and
3853
+ // \`Array.isArray\` says yes to a proxy of an array. Where a realm leaves a script the Proxy
3854
+ // constructor (the double VM at STANDARD and PERMISSIVE), the script gets a stand-in for it
3855
+ // that makes the same proxy and remembers it. A remembered proxy is not handed to a built-in
3856
+ // as an array: it is read once, like any object that states a length.
3857
+ var scriptProxies = null;
3858
+ var proxyMade = false;
3859
+ if (limited && ProxyCtor !== undefined) {
3860
+ if (typeof WeakSet !== 'function') cannotInstall('Proxy');
3861
+ var remember = WeakSet.prototype.add;
3862
+ var remembered = WeakSet.prototype.has;
3863
+ var makeRevocable = ProxyCtor.revocable;
3864
+ scriptProxies = new WeakSet();
3865
+ var ProxyStandIn = function Proxy(target, handler) {
3866
+ if (new.target === undefined) throw new TypeErrorCtor("Constructor Proxy requires 'new'");
3867
+ var made = new ProxyCtor(target, handler);
3868
+ apply(remember, scriptProxies, [made]);
3869
+ proxyMade = true;
3870
+ return made;
3871
+ };
3872
+ // Like the built-in, it has no prototype of its own to give
3873
+ ProxyStandIn.prototype = undefined;
3874
+ defineProperty(ProxyStandIn, 'revocable', {
3875
+ value: function revocable(target, handler) {
3876
+ var pair = apply(makeRevocable, ProxyCtor, [target, handler]);
3877
+ apply(remember, scriptProxies, [pair.proxy]);
3878
+ proxyMade = true;
3879
+ return pair;
3880
+ },
3881
+ writable: true,
3882
+ enumerable: false,
3883
+ configurable: true
3884
+ });
3885
+ try {
3886
+ defineProperty(globalThis, 'Proxy', { value: ProxyStandIn, writable: true, enumerable: false, configurable: true });
3887
+ } catch (e) {
3888
+ cannotInstall('Proxy');
3889
+ }
3890
+ }
3891
+
3892
+ function isScriptProxy(value) {
3893
+ return proxyMade && isObject(value) && apply(remembered, scriptProxies, [value]);
3894
+ }
3895
+
3896
+ /** An array that answers for itself: not one behind a proxy a script made. */
3897
+ function ownArray(value) {
3898
+ return isArray(value) && !isScriptProxy(value);
3899
+ }
3900
+
3901
+ // Rule 4: no array has more slots than the limit holds, and no built-in walks more.
3902
+
3903
+ /** The index a property key is on an array, or -1. */
3904
+ function arrayIndex(key) {
3905
+ if (typeof key === 'number') return (key >>> 0) === key && key !== 4294967295 ? key : -1;
3906
+ if (typeof key !== 'string') return -1;
3907
+ var number = +key;
3908
+ return (number >>> 0) === number && number !== 4294967295 && StringCtor(number) === key ? number : -1;
3909
+ }
3910
+
3911
+ /** ToPropertyKey, done once: what a member access makes of the key. */
3912
+ function propertyKey(key) {
3913
+ var type = typeof key;
3914
+ return type === 'string' || type === 'symbol' || type === 'number' ? key : StringCtor(key);
3915
+ }
3916
+
3917
+ /**
3918
+ * A write to an array through its length or through an index beyond its end: refused when it
3919
+ * would give the array more slots than the limit holds, and charged for the slots it adds
3920
+ * (the slots between the old end and the new one are part of what a built-in walks).
3921
+ * Returns the value to write: for the length, the number it was converted to, once.
3922
+ */
3923
+ function growing(target, key, value) {
3924
+ // The bound is checked whatever the array says its length is now: behind a proxy that is
3925
+ // not the array's own answer
3926
+ if (key === 'length') {
3927
+ var wanted = +value;
3928
+ checkLength(wanted, 'Array length');
3929
+ var before = target.length;
3930
+ if (wanted > before) charge(wanted - before);
3931
+ return wanted;
3932
+ }
3933
+ var index = arrayIndex(key);
3934
+ if (index >= 0) {
3935
+ checkLength(index + 1, 'Array index');
3936
+ var length = target.length;
3937
+ if (index >= length) charge(index + 1 - length);
3938
+ }
3939
+ return value;
3940
+ }
3941
+
3942
+ /** \`target[key] = value\`, with the key converted once and an array kept within the limit. */
3943
+ function guardedSet(target, key, value) {
3944
+ // The common write: a number that is inside the array. Nothing grows, nothing to convert.
3945
+ // (Not for an array behind a proxy a script made: the length it states is not the array's.)
3946
+ if (typeof key === 'number' && key >= 0 && isArray(target) && !(proxyMade && isScriptProxy(target)) && key < target.length) {
3947
+ target[key] = value;
3948
+ return value;
3949
+ }
3950
+ var k = propertyKey(key);
3951
+ if (limited && isArray(target)) {
3952
+ target[k] = growing(target, k, value);
3953
+ } else {
3954
+ target[k] = value;
3955
+ }
3956
+ return value;
3957
+ }
3958
+
3959
+ /**
3960
+ * What stands in for \`X[K]\` where it is written in another way than \`X[K] = V\` (a compound
3961
+ * assignment, \`++\`, a target in a destructuring pattern or in the head of a loop): an object
3962
+ * whose one member \`v\` reads and writes that slot, so the write is the guarded one.
3963
+ */
3964
+ function Slot(target, key) {
3965
+ this.t = target;
3966
+ this.k = propertyKey(key);
3967
+ }
3968
+ Slot.prototype = ObjectCtor.freeze(objectCreate(null, {
3969
+ v: {
3970
+ get: function () { return this.t[this.k]; },
3971
+ set: function (value) { guardedSet(this.t, this.k, value); },
3972
+ enumerable: false,
3973
+ configurable: false
3974
+ }
3975
+ }));
3976
+ function slot(target, key) {
3977
+ return new Slot(target, key);
3978
+ }
3979
+
3980
+ /**
3981
+ * The receiver of a built-in that reads its receiver by its length. An array is itself: its
3982
+ * length is its own, and it has no more slots than a script could give it. Anything else is
3983
+ * read here, once, into a plain array of the length it states, which is checked first. Null
3984
+ * for a receiver the built-in refuses by itself.
3985
+ */
3986
+ function walked(self, label) {
3987
+ if (isArray(self) && !(proxyMade && isScriptProxy(self))) return self;
3988
+ var receiver = toObject(self);
3989
+ if (receiver === null) return null;
3990
+ var length = toLength(receiver.length);
3991
+ checkLength(length, label);
3992
+ return snapshot(receiver, length, true);
3993
+ }
3994
+
3995
+ /**
3996
+ * Whether a built-in that moves the slots of its receiver can be given the receiver itself:
3997
+ * an array, or an object whose length is a number it holds (checked here) or that has none.
3998
+ * The built-in reads the length again, and such a length answers the same.
3999
+ */
4000
+ function movable(self, label) {
4001
+ if (!isObject(self) || ownArray(self)) return true;
4002
+ if (isScriptProxy(self)) return false;
4003
+ var held = getOwnPropertyDescriptor(self, 'length');
4004
+ if (held === undefined) return !('length' in self);
4005
+ if (!('value' in held) || typeof held.value !== 'number') return false;
4006
+ checkLength(toLength(held.value), label);
4007
+ return true;
4008
+ }
4009
+
4010
+ /**
4011
+ * A built-in that moves the slots of its receiver, applied to a receiver whose length is
4012
+ * computed (an accessor, an inherited length, a proxy a script made): the receiver is read
4013
+ * once into a plain array, the built-in works on that, and the result is written back.
4014
+ */
4015
+ function moveThroughCopy(original, self, given, label) {
4016
+ var length = toLength(self.length);
4017
+ checkLength(length, label);
4018
+ var copy = snapshot(self, length, true);
4019
+ var result = apply(original, copy, given);
4020
+ var after = copy.length;
4021
+ for (var i = 0; i < after; i++) {
4022
+ if (i in copy) guardedSet(self, i, copy[i]);
4023
+ else delete self[i];
4024
+ }
4025
+ for (var gone = after; gone < length; gone++) delete self[gone];
4026
+ guardedSet(self, 'length', after);
4027
+ return result === copy ? self : result;
4028
+ }
4029
+
4030
+ /** Rule 1, for a text: that many characters are not made. */
4031
+ function checkText(characters, label) {
4032
+ if (limited && characters * 2 > memoryLimit) refuse(label, characters * 2);
4033
+ }
4034
+
4035
+ function patch(holder, name, make) {
4036
+ var original = holder[name];
4037
+ if (typeof original !== 'function') return;
4038
+ var replacement = make(original);
4039
+ // The replacement answers for its name and its number of parameters like the built-in
4040
+ try {
4041
+ defineProperty(replacement, 'name', { value: name, writable: false, enumerable: false, configurable: true });
4042
+ defineProperty(replacement, 'length', { value: original.length, writable: false, enumerable: false, configurable: true });
4043
+ } catch (e) { /* left as it is */ }
4044
+ try {
4045
+ defineProperty(holder, name, { value: replacement, writable: true, enumerable: false, configurable: true });
4046
+ } catch (e) {
4047
+ cannotInstall(name);
4048
+ }
4049
+ }
4050
+
4051
+ if (limited) {
4052
+ // push, unshift: every argument is a new element
4053
+ patch(arrayProto, 'push', function (original) {
4054
+ return function push() {
4055
+ charge(arguments.length);
4056
+ return apply(original, this, arguments);
4057
+ };
4058
+ });
4059
+ // The global Array, once it is the guarded one (see the end of this block)
4060
+ var guardedArray = null;
4061
+ patch(arrayProto, 'unshift', function (original) {
4062
+ return function unshift() {
4063
+ charge(arguments.length);
4064
+ if (!movable(this, 'Array.unshift')) return moveThroughCopy(original, this, arguments, 'Array.unshift');
4065
+ return apply(original, this, arguments);
4066
+ };
4067
+ });
4068
+ // splice: the arguments after the first two are inserted
4069
+ patch(arrayProto, 'splice', function (original) {
4070
+ return function splice() {
4071
+ if (arguments.length > 2) charge(arguments.length - 2);
4072
+ if (!movable(this, 'Array.splice')) return moveThroughCopy(original, this, arguments, 'Array.splice');
4073
+ return apply(original, this, arguments);
4074
+ };
4075
+ });
4076
+ // concat: the result has, for the receiver and each argument, its elements or itself. It
4077
+ // is built here, in the pass that counts it and in the order the built-in works: each value
4078
+ // is asked once whether it is spread (the language's symbol for it, otherwise whether it
4079
+ // is an array), a value that is spread is asked once for its length and once for each
4080
+ // slot, and the count is checked before the slots are copied. The built-in does not run.
4081
+ // It would ask every value again, and what answers can be code of the script (an accessor
4082
+ // on an array, the constructor of the receiver's kind): an array that was counted could
4083
+ // hold more by the time the built-in copies it, as often as it is named.
4084
+ function copySlots(target, at, source, length) {
4085
+ // A slot that is not there stays empty in the result
4086
+ for (var k = 0; k < length; k++) {
4087
+ if (k in source) target[at + k] = source[k];
4088
+ }
4089
+ }
4090
+ patch(arrayProto, 'concat', function (original) {
4091
+ return function concat() {
4092
+ var receiver = toObject(this);
4093
+ if (receiver === null) return apply(original, this, arguments);
4094
+ // The result is of the receiver's kind, and is made first, as in the built-in
4095
+ var ofKind = emptyOfKind(receiver);
4096
+ var plain = ofKind === null;
4097
+ var target = plain ? [] : ofKind;
4098
+ if (plain) {
4099
+ // A first size for the result, so that it is not made in steps: what the arrays
4100
+ // among the values hold now. It decides nothing. Every value is asked and counted
4101
+ // below, and the result ends with the length that was counted.
4102
+ var expected = 0;
4103
+ for (var e = -1; e < arguments.length; e++) {
4104
+ var one = e < 0 ? receiver : arguments[e];
4105
+ expected += ownArray(one) ? one.length : 1;
4106
+ }
4107
+ if (expected * BYTES <= memoryLimit) target.length = expected;
4108
+ }
4109
+ var count = 0;
4110
+ var own = 0;
4111
+ for (var i = -1; i < arguments.length; i++) {
4112
+ var item = i < 0 ? receiver : arguments[i];
4113
+ var spread = false;
4114
+ if (isObject(item)) {
4115
+ var flag = item[spreadableSymbol];
4116
+ spread = flag === undefined ? isArray(item) : !!flag;
4117
+ }
4118
+ if (!spread) {
4119
+ checkLength(count + 1, 'Array.concat');
4120
+ if (plain) {
4121
+ target[count] = item;
4122
+ } else {
4123
+ defineProperty(target, count, { value: item, writable: true, enumerable: true, configurable: true });
4124
+ }
4125
+ count++;
4126
+ continue;
4127
+ }
4128
+ var length = toLength(item.length);
4129
+ checkLength(count + length, 'Array.concat');
4130
+ if (i < 0 && ownArray(item)) own = length;
4131
+ if (plain) {
4132
+ copySlots(target, count, item, length);
4133
+ } else {
4134
+ for (var k = 0; k < length; k++) {
4135
+ if (!(k in item)) continue;
4136
+ defineProperty(target, count + k, { value: item[k], writable: true, enumerable: true, configurable: true });
4137
+ }
4138
+ }
4139
+ count += length;
4140
+ }
4141
+ target.length = count;
4142
+ charge(count - own);
4143
+ return target;
4144
+ };
4145
+ });
4146
+
4147
+ // flat: the result is built here, in the pass that counts it, to the depth the built-in
4148
+ // flattens. Each slot is asked once (is it there, what is it) and each nested array for its
4149
+ // length once, so what is counted is what the result is made of. The pass walks the nesting
4150
+ // with a list of its own, so the depth of the nesting is not the depth of a call stack, and
4151
+ // it stops at the limit: by the slots counted so far, and by the arrays entered (an array
4152
+ // of empty arrays has nothing to count and everything to visit).
4153
+ function flatten(root, rootLength, levels, target, plain) {
4154
+ var budget = memoryLimit / BYTES;
4155
+ var slots = rootLength;
4156
+ var entered = 0;
4157
+ if (slots > budget) refuse('Array.flat', slots * BYTES);
4158
+ var sources = [root];
4159
+ var lengths = [rootLength];
4160
+ var depths = [levels];
4161
+ var next = [0];
4162
+ var top = 0;
4163
+ var count = 0;
4164
+ while (top >= 0) {
4165
+ var index = next[top];
4166
+ if (index >= lengths[top]) {
4167
+ top--;
4168
+ continue;
4169
+ }
4170
+ next[top] = index + 1;
4171
+ var source = sources[top];
4172
+ // A slot that is not there is left out, as in the built-in
4173
+ if (!(index in source)) continue;
4174
+ var item = source[index];
4175
+ if (depths[top] >= 1 && isArray(item)) {
4176
+ // The slot gives way to what the array holds
4177
+ var length = toLength(item.length);
4178
+ slots += length - 1;
4179
+ entered++;
4180
+ if (slots > budget || entered > budget) {
4181
+ refuse('Array.flat', (slots > entered ? slots : entered) * BYTES);
4182
+ }
4183
+ top++;
4184
+ sources[top] = item;
4185
+ lengths[top] = length;
4186
+ depths[top] = depths[top - 1] - 1;
4187
+ next[top] = 0;
4188
+ continue;
4189
+ }
4190
+ if (plain) {
4191
+ target[count] = item;
4192
+ } else {
4193
+ defineProperty(target, count, { value: item, writable: true, enumerable: true, configurable: true });
4194
+ }
4195
+ count++;
4196
+ }
4197
+ return count;
4198
+ }
4199
+ patch(arrayProto, 'flat', function (original) {
4200
+ return function flat(depth) {
4201
+ var receiver = toObject(this);
4202
+ if (receiver === null) return apply(original, this, arguments);
4203
+ var length = toLength(receiver.length);
4204
+ var levels = depth === undefined ? 1 : toInteger(depth);
4205
+ if (levels < 0) levels = 0;
4206
+ var ofKind = emptyOfKind(receiver);
4207
+ var target = ofKind === null ? [] : ofKind;
4208
+ var count = flatten(receiver, length, levels, target, ofKind === null);
4209
+ charge(count - (isArray(receiver) ? length : 0));
4210
+ return target;
4211
+ };
4212
+ });
4213
+ // flatMap: what the callback hands back is counted as it comes
4214
+ patch(arrayProto, 'flatMap', function (original) {
4215
+ return function flatMap(callback, thisArg) {
4216
+ if (typeof callback !== 'function') return apply(original, this, arguments);
4217
+ var receiver = walked(this, 'Array.flatMap');
4218
+ if (receiver === null) return apply(original, this, arguments);
4219
+ var produced = 0;
4220
+ var result = apply(original, receiver, [function (value, index, array) {
4221
+ var item = apply(callback, this, [value, index, array]);
4222
+ if (isScriptProxy(item) && isArray(item)) {
4223
+ // An array behind a proxy a script made: the built-in gets what was counted
4224
+ var length = toLength(item.length);
4225
+ produced += length;
4226
+ checkLength(produced, 'Array.flatMap');
4227
+ return snapshot(item, length, true);
4228
+ }
4229
+ produced += isArray(item) ? item.length : 1;
4230
+ checkLength(produced, 'Array.flatMap');
4231
+ return item;
4232
+ }, thisArg]);
4233
+ charge(lengthOf(result) - lengthOf(this));
4234
+ return result;
4235
+ };
4236
+ });
4237
+ // The copying methods turn every slot of the receiver into an element, holes included.
4238
+ // Of something that is not an array they get a plain copy, of the length that was checked.
4239
+ var copying = ['toSorted', 'toReversed', 'toSpliced', 'with'];
4240
+ for (var c = 0; c < copying.length; c++) {
4241
+ (function (name) {
4242
+ patch(arrayProto, name, function (original) {
4243
+ return function () {
4244
+ var receiver = toObject(this);
4245
+ if (receiver === null) return apply(original, this, arguments);
4246
+ var length = toLength(receiver.length);
4247
+ var array = ownArray(receiver);
4248
+ // The copy that is made of something that is not an array has its length
4249
+ if (!array) checkLength(length, 'Array.' + name);
4250
+ var given = arguments;
4251
+ if (name === 'toSpliced') {
4252
+ // The result has the receiver's slots, less the ones skipped, plus the ones
4253
+ // inserted: worked out here by the built-in's rules, and the built-in gets the
4254
+ // two numbers
4255
+ var start = relativeIndex(arguments[0], length, 0);
4256
+ var skip = arguments.length === 0 ? 0 : arguments.length === 1 ? length - start : toInteger(arguments[1]);
4257
+ if (skip < 0) skip = 0;
4258
+ if (skip > length - start) skip = length - start;
4259
+ var inserted = arguments.length > 2 ? arguments.length - 2 : 0;
4260
+ checkLength(length + inserted - skip, 'Array.toSpliced');
4261
+ given = [start, skip];
4262
+ for (var g = 2; g < arguments.length; g++) given[g] = arguments[g];
4263
+ } else {
4264
+ checkLength(length, 'Array.' + name);
4265
+ }
4266
+ return apply(original, array ? receiver : snapshot(receiver, length, false), given);
4267
+ };
4268
+ });
4269
+ })(copying[c]);
4270
+ }
4271
+ // Array.from. Of something with a length: that many elements, whatever is behind it. Of
4272
+ // something that is iterated: as many as it yields, so the built-in is stopped at the
4273
+ // limit by the mapping function it calls for each element. Which of the two it is, is
4274
+ // decided here, once, for an array as for anything else: the built-in is given a source
4275
+ // that can only be read that way.
4276
+ patch(ArrayCtor, 'from', function (original) {
4277
+ return function from(items, mapFn, thisArg) {
4278
+ // What the built-in refuses by itself, it refuses before it makes anything
4279
+ if (items === null || items === undefined) return apply(original, this, arguments);
4280
+ if (mapFn !== undefined && typeof mapFn !== 'function') return apply(original, this, arguments);
4281
+
4282
+ var source = items;
4283
+ var iterate = items[iteratorSymbol];
4284
+ if (iterate === undefined || iterate === null) {
4285
+ var receiver = toObject(items);
4286
+ var length = toLength(receiver.length);
4287
+ checkLength(length, 'Array.from');
4288
+ source = slotsOf(receiver, length);
4289
+ } else if (typeof iterate !== 'function') {
4290
+ // What the built-in answers for an iterator that cannot be called: answered here, so
4291
+ // that it is not asked a second time
4292
+ throw new TypeErrorCtor('Array.from: the iterator of the source is not a function');
4293
+ } else if (isObject(items)) {
4294
+ var held = {};
4295
+ held[iteratorSymbol] = { value: function () { return apply(iterate, items, []); } };
4296
+ source = objectCreate(null, held);
4297
+ }
4298
+
4299
+ var produced = 0;
4300
+ var mapped = mapFn !== undefined;
4301
+ // The guarded Array stands for the built-in one: what is made here is counted here
4302
+ var result = apply(original, this === guardedArray ? ArrayCtor : this, [source, function (value, index) {
4303
+ produced++;
4304
+ if (produced * BYTES > memoryLimit) refuse('Array.from', produced * BYTES);
4305
+ return mapped ? apply(mapFn, this, [value, index]) : value;
4306
+ }, thisArg]);
4307
+ checkLength(lengthOf(result), 'Array.from');
4308
+ if (!isArray(items)) charge(lengthOf(result));
4309
+ return result;
4310
+ };
4311
+ });
4312
+
4313
+ // fill: the range is worked out here, by the built-in's rules, checked and charged, and
4314
+ // the built-in gets the range as two numbers. Something that is not an array is filled
4315
+ // here: the built-in would read its length again.
4316
+ patch(arrayProto, 'fill', function (original) {
4317
+ return function fill(value, start, end) {
4318
+ if (!isObject(this)) return apply(original, this, arguments);
4319
+ var array = ownArray(this);
4320
+ var length = array ? this.length : toLength(this.length);
4321
+ var from = relativeIndex(start, length, 0);
4322
+ var to = relativeIndex(end, length, length);
4323
+ var count = to > from ? to - from : 0;
4324
+ checkLength(count, 'Array.fill');
4325
+ if (array) {
4326
+ // The slots of an array were charged when it got them
4327
+ return apply(original, this, [value, from, to]);
4328
+ }
4329
+ charge(count);
4330
+ for (var i = from; i < to; i++) {
4331
+ this[i] = value;
4332
+ }
4333
+ return this;
4334
+ };
4335
+ });
4336
+
4337
+ // Every other built-in that works through its receiver by its length. One call into such a
4338
+ // built-in is finished by the engine, however long the length says the receiver is: the
4339
+ // deadline is not looked at inside it. So none of them is given a length above what an
4340
+ // array may have, whether the receiver is an array with that many slots (most of them
4341
+ // empty) or an object that states the length.
4342
+ var reading = [
4343
+ 'indexOf', 'lastIndexOf', 'includes', 'forEach', 'map', 'filter', 'some', 'every', 'reduce',
4344
+ 'reduceRight', 'find', 'findIndex', 'findLast', 'findLastIndex', 'slice', 'keys', 'values', 'entries'
4345
+ ];
4346
+ for (var r = 0; r < reading.length; r++) {
4347
+ (function (name) {
4348
+ var label = 'Array.' + name;
4349
+ patch(arrayProto, name, function (original) {
4350
+ return function () {
4351
+ var receiver = walked(this, label);
4352
+ return apply(original, receiver === null ? this : receiver, arguments);
4353
+ };
4354
+ });
4355
+ })(reading[r]);
4356
+ }
4357
+ var moving = ['reverse', 'sort', 'copyWithin', 'shift'];
4358
+ for (var m = 0; m < moving.length; m++) {
4359
+ (function (name) {
4360
+ var label = 'Array.' + name;
4361
+ patch(arrayProto, name, function (original) {
4362
+ return function () {
4363
+ if (!movable(this, label)) return moveThroughCopy(original, this, arguments, label);
4364
+ return apply(original, this, arguments);
4365
+ };
4366
+ });
4367
+ })(moving[m]);
4368
+ }
4369
+
4370
+ // The other ways to write to an array. Each is the guarded write, or checked like it.
4371
+ patch(ObjectCtor, 'assign', function (original) {
4372
+ return function assign(target) {
4373
+ if (!isArray(target)) return apply(original, this, arguments);
4374
+ for (var s = 1; s < arguments.length; s++) {
4375
+ var source = arguments[s];
4376
+ if (source === null || source === undefined) continue;
4377
+ var from = ObjectCtor(source);
4378
+ var keys = ownKeys(from);
4379
+ for (var i = 0; i < keys.length; i++) {
4380
+ var held = getOwnPropertyDescriptor(from, keys[i]);
4381
+ if (held !== undefined && held.enumerable) guardedSet(target, keys[i], from[keys[i]]);
4382
+ }
4383
+ }
4384
+ return target;
4385
+ };
4386
+ });
4387
+ // A descriptor, read once: the built-in reads its members again
4388
+ var descriptorMembers = ['enumerable', 'configurable', 'value', 'writable', 'get', 'set'];
4389
+ function pinned(descriptor) {
4390
+ if (!isObject(descriptor)) return descriptor;
4391
+ var copy = objectCreate(null);
4392
+ for (var d = 0; d < descriptorMembers.length; d++) {
4393
+ if (descriptorMembers[d] in descriptor) copy[descriptorMembers[d]] = descriptor[descriptorMembers[d]];
4394
+ }
4395
+ return copy;
4396
+ }
4397
+ // The key and the descriptor a definition on an array is made with
4398
+ function definition(target, key, descriptor) {
4399
+ var k = propertyKey(key);
4400
+ var copy = pinned(descriptor);
4401
+ if (isObject(copy)) {
4402
+ if (k !== 'length') growing(target, k, undefined);
4403
+ else if ('value' in copy) copy.value = growing(target, k, copy.value);
4404
+ }
4405
+ return [target, k, copy];
4406
+ }
4407
+ var defineOne = ObjectCtor.defineProperty;
4408
+ patch(ObjectCtor, 'defineProperty', function (original) {
4409
+ return function defineProperty(target, key, descriptor) {
4410
+ if (!isArray(target)) return apply(original, this, arguments);
4411
+ return apply(original, this, definition(target, key, descriptor));
4412
+ };
4413
+ });
4414
+ patch(ObjectCtor, 'defineProperties', function (original) {
4415
+ return function defineProperties(target, properties) {
4416
+ if (!isArray(target) || properties === null || properties === undefined) return apply(original, this, arguments);
4417
+ var from = ObjectCtor(properties);
4418
+ var keys = ownKeys(from);
4419
+ for (var i = 0; i < keys.length; i++) {
4420
+ var held = getOwnPropertyDescriptor(from, keys[i]);
4421
+ if (held !== undefined && held.enumerable) apply(defineOne, ObjectCtor, definition(target, keys[i], from[keys[i]]));
4422
+ }
4423
+ return target;
4424
+ };
4425
+ });
4426
+ if (typeof Reflect === 'object' && Reflect !== null) {
4427
+ patch(Reflect, 'defineProperty', function (original) {
4428
+ return function defineProperty(target, key, descriptor) {
4429
+ if (!isArray(target)) return apply(original, this, arguments);
4430
+ return apply(original, this, definition(target, key, descriptor));
4431
+ };
4432
+ });
4433
+ patch(Reflect, 'set', function (original) {
4434
+ return function set(target, key, value, receiver) {
4435
+ // The write lands on the receiver, which is the target unless one is given
4436
+ var landing = arguments.length > 3 ? receiver : target;
4437
+ if (!isArray(landing)) return apply(original, this, arguments);
4438
+ var k = propertyKey(key);
4439
+ var written = growing(landing, k, value);
4440
+ return apply(original, this, arguments.length > 3 ? [target, k, written, receiver] : [target, k, written]);
4441
+ };
4442
+ });
4443
+ }
4444
+ var legacy = ['__defineGetter__', '__defineSetter__'];
4445
+ for (var l = 0; l < legacy.length; l++) {
4446
+ (function (name) {
4447
+ patch(ObjectCtor.prototype, name, function (original) {
4448
+ return function (key, accessor) {
4449
+ if (!isArray(this)) return apply(original, this, arguments);
4450
+ var k = propertyKey(key);
4451
+ growing(this, k, undefined);
4452
+ return apply(original, this, [k, accessor]);
4453
+ };
4454
+ });
4455
+ })(legacy[l]);
4456
+ }
4457
+
4458
+ // Array(n) and new Array(n) make n slots: checked and charged like every other way to get
4459
+ // them. The global is put behind a proxy for that (made here, while the realm still has
4460
+ // the means), so it holds for every way to call it; \`Array.prototype.constructor\` stays the
4461
+ // built-in, which the results of the built-ins are made with.
4462
+ patch(ArrayCtor, 'of', function (original) {
4463
+ return function of() {
4464
+ return apply(original, this === guardedArray ? ArrayCtor : this, arguments);
4465
+ };
4466
+ });
4467
+ // (Without a Proxy constructor in the realm there is nothing to put the global behind.)
4468
+ if (ProxyCtor === undefined) cannotInstall('Array');
4469
+ {
4470
+ var slotsFor = function (given) {
4471
+ if (given.length === 1 && typeof given[0] === 'number') {
4472
+ checkLength(given[0], 'Array');
4473
+ charge(given[0]);
4474
+ } else {
4475
+ checkLength(given.length, 'Array');
4476
+ }
4477
+ };
4478
+ // (A handler without a prototype: the traps of the stand-in are these two and no other)
4479
+ var arrayTraps = objectCreate(null);
4480
+ arrayTraps.apply = function (target, self, given) {
4481
+ slotsFor(given);
4482
+ return apply(target, self, given);
4483
+ };
4484
+ arrayTraps.construct = function (target, given, newTarget) {
4485
+ slotsFor(given);
4486
+ return construct(target, given, newTarget);
4487
+ };
4488
+ guardedArray = new ProxyCtor(ArrayCtor, arrayTraps);
4489
+ try {
4490
+ defineProperty(globalThis, 'Array', { value: guardedArray, writable: true, enumerable: false, configurable: true });
4491
+ } catch (e) {
4492
+ cannotInstall('Array');
4493
+ }
4494
+ }
4495
+
4496
+ // Array.fromAsync: like Array.from. How the source is read is decided here, once, and what
4497
+ // it yields is counted as it comes. The built-in answers every failure with a promise that
4498
+ // is rejected, never with an error at the call. So an iterator that cannot be called is
4499
+ // handed on as the value it is, and an error the source raises while it is read here is
4500
+ // kept and raised again by the source the built-in is given: the answer is the built-in's
4501
+ // own, and the source is not asked a second time. The limit's refusal is not an answer of
4502
+ // the built-in: it ends the call.
4503
+ patch(ArrayCtor, 'fromAsync', function (original) {
4504
+ return function fromAsync(items, mapFn, thisArg) {
4505
+ if (items === null || items === undefined) return apply(original, this, arguments);
4506
+ if (mapFn !== undefined && typeof mapFn !== 'function') return apply(original, this, arguments);
4507
+ var source;
4508
+ var receiver;
4509
+ var length = -1;
4510
+ var failed = false;
4511
+ var failure;
4512
+ try {
4513
+ var iterate = asyncIteratorSymbol === undefined ? undefined : items[asyncIteratorSymbol];
4514
+ var symbol = asyncIteratorSymbol;
4515
+ if (iterate === undefined || iterate === null) {
4516
+ iterate = items[iteratorSymbol];
4517
+ symbol = iteratorSymbol;
4518
+ }
4519
+ if (iterate === undefined || iterate === null) {
4520
+ receiver = toObject(items);
4521
+ length = toLength(receiver.length);
4522
+ } else {
4523
+ var held = {};
4524
+ held[symbol] = {
4525
+ value: typeof iterate === 'function' ? function () { return apply(iterate, items, []); } : iterate
4526
+ };
4527
+ source = objectCreate(null, held);
4528
+ }
4529
+ } catch (error) {
4530
+ failed = true;
4531
+ failure = error;
4532
+ }
4533
+ if (!failed && length >= 0) {
4534
+ checkLength(length, 'Array.fromAsync');
4535
+ source = slotsOf(receiver, length);
4536
+ }
4537
+ if (failed) {
4538
+ var raising = {};
4539
+ raising[asyncIteratorSymbol === undefined ? iteratorSymbol : asyncIteratorSymbol] = {
4540
+ get: function () { throw failure; }
4541
+ };
4542
+ source = objectCreate(null, raising);
4543
+ }
4544
+ var produced = 0;
4545
+ var mapped = mapFn !== undefined;
4546
+ return apply(original, this === guardedArray ? ArrayCtor : this, [source, function (value, index) {
4547
+ produced++;
4548
+ if (produced * BYTES > memoryLimit) refuse('Array.fromAsync', produced * BYTES);
4549
+ charge(1);
4550
+ return mapped ? apply(mapFn, this, [value, index]) : value;
4551
+ }, thisArg]);
4552
+ };
4553
+ });
4554
+
4555
+ // join and toLocaleString: each item is converted to its text here, once, the texts are
4556
+ // counted as they come, and the built-in joins the texts.
4557
+ var joining = [];
4558
+ function textsOf(receiver, length, separatorLength, label, convert) {
4559
+ // The list of the texts is an array of that length
4560
+ checkLength(length, label);
4561
+ var texts = [];
4562
+ var characters = 0;
4563
+ for (var i = 0; i < length; i++) {
4564
+ var item = receiver[i];
4565
+ var text = (item === undefined || item === null) ? '' : convert(item);
4566
+ texts[i] = text;
4567
+ characters += text.length + (i > 0 ? separatorLength : 0);
4568
+ checkText(characters, label);
4569
+ }
4570
+ return texts;
4571
+ }
4572
+ function joined(receiver, label, separator, convert, join) {
4573
+ var array = isArray(receiver);
4574
+ var length = array ? receiver.length : toLength(receiver.length);
4575
+ // An array that contains itself contributes nothing the second time, as in the built-in
4576
+ for (var j = 0; j < joining.length; j++) {
4577
+ if (joining[j] === receiver) return '';
4578
+ }
4579
+ joining[joining.length] = receiver;
4580
+ var texts;
4581
+ try {
4582
+ texts = textsOf(receiver, length, separator.length, label, convert);
4583
+ } finally {
4584
+ joining.length = joining.length - 1;
4585
+ }
4586
+ return apply(join, texts, [separator]);
4587
+ }
4588
+ var joinBefore = arrayProto.join;
4589
+ patch(arrayProto, 'join', function (previous) {
4590
+ return function join(separator) {
4591
+ if (!isObject(this)) return apply(previous, this, arguments);
4592
+ var between = separator === undefined ? ',' : toText(separator);
4593
+ return joined(this, 'Array.join', between, toText, previous);
4594
+ };
4595
+ });
4596
+ patch(arrayProto, 'toLocaleString', function (previous) {
4597
+ return function toLocaleString(locales, options) {
4598
+ if (!isObject(this) || typeof joinBefore !== 'function') return apply(previous, this, arguments);
4599
+ return joined(this, 'Array.toLocaleString', ',', function (item) {
4600
+ return toText(item.toLocaleString(locales, options));
4601
+ }, joinBefore);
4602
+ };
4603
+ });
4604
+
4605
+ // repeat, padStart, padEnd: the receiver and the count are converted here, once
4606
+ patch(stringProto, 'repeat', function (previous) {
4607
+ return function repeat(count) {
4608
+ if (this === null || this === undefined) return apply(previous, this, arguments);
4609
+ return apply(previous, toText(this), [toInteger(count)]);
4610
+ };
4611
+ });
4612
+ var padding = ['padStart', 'padEnd'];
4613
+ for (var p = 0; p < padding.length; p++) {
4614
+ (function (name) {
4615
+ patch(stringProto, name, function (previous) {
4616
+ return function (targetLength, padString) {
4617
+ if (this === null || this === undefined) return apply(previous, this, arguments);
4618
+ return apply(previous, toText(this), [toLength(targetLength), padString === undefined ? undefined : toText(padString)]);
4619
+ };
4620
+ });
4621
+ })(padding[p]);
4622
+ }
4623
+ }
4624
+
4625
+ // An array literal with spreads: [a, ...b, ...c] is compiled to
4626
+ // __safe_array(__safe_arrayStart(), [a, ...__safe_spread(b), ...__safe_spread(c)])
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.
4630
+ var frames = [];
4631
+ var nextId = 1;
4632
+
4633
+ function arrayStart() {
4634
+ // A literal that threw before it was finished leaves its frame; they are small, and gone
4635
+ // with the next literal that finishes below them or once there are too many.
4636
+ if (frames.length > 1024) frames.length = 0;
4637
+ var frame = { id: nextId++, total: 0, largest: 0 };
4638
+ frames[frames.length] = frame;
4639
+ return frame.id;
4640
+ }
4641
+
4642
+ function spread(source) {
4643
+ var frame = frames.length > 0 ? frames[frames.length - 1] : null;
4644
+ if (ownArray(source) || typeof source === 'string') {
4645
+ // An array, or a text (which yields at most as many items as it has characters): its
4646
+ // size is known before it is spread
4647
+ var length = source.length;
4648
+ checkLength(length, 'Array spread');
4649
+ if (frame) {
4650
+ frame.total += length;
4651
+ if (typeof source !== 'string' && length > frame.largest) frame.largest = length;
4652
+ checkLength(frame.total, 'Array spread');
4653
+ }
4654
+ return source;
4655
+ }
4656
+ if (!limited || source === null || source === undefined) return source;
4657
+ // Anything else that is iterated yields as many items as it likes: it is spread through an
4658
+ // iterator that counts them as they come, so the literal is stopped at the limit and not
4659
+ // measured when it exists. The iterator is asked for once, and each step is read once.
4660
+ var iterate = source[iteratorSymbol];
4661
+ if (typeof iterate !== 'function') return source;
4662
+ var counted = {};
4663
+ counted[iteratorSymbol] = {
4664
+ value: function () {
4665
+ var iterator = apply(iterate, source, []);
4666
+ if (!isObject(iterator)) throw new TypeErrorCtor('Result of the Symbol.iterator method is not an object');
4667
+ var next = iterator.next;
4668
+ return {
4669
+ next: function () {
4670
+ var step = apply(next, iterator, []);
4671
+ if (!isObject(step)) throw new TypeErrorCtor('Iterator result is not an object');
4672
+ if (step.done) return { done: true, value: undefined };
4673
+ if (frame) {
4674
+ frame.total += 1;
4675
+ checkLength(frame.total, 'Array spread');
4676
+ }
4677
+ return { done: false, value: step.value };
4678
+ },
4679
+ return: function (value) {
4680
+ var close = iterator.return;
4681
+ return typeof close === 'function' ? apply(close, iterator, [value]) : { done: true, value: value };
4682
+ }
4683
+ };
4684
+ }
4685
+ };
4686
+ return objectCreate(null, counted);
4687
+ }
4688
+
4689
+ function arrayFinish(id, array) {
4690
+ var largest = 0;
4691
+ for (var i = id === 0 ? -1 : frames.length - 1; i >= 0; i--) {
4692
+ if (frames[i].id === id) {
4693
+ largest = frames[i].largest;
4694
+ frames.length = i;
4695
+ break;
2852
4696
  }
2853
- throw message;
2854
- },
2855
- writable: false,
2856
- configurable: false,
2857
- enumerable: false
2858
- });
2859
- })(${timeout})
4697
+ }
4698
+ if (isArray(array)) {
4699
+ checkLength(array.length, id === 0 ? 'Array literal' : 'Array spread');
4700
+ charge(array.length - largest);
4701
+ }
4702
+ return array;
4703
+ }
4704
+
4705
+ var helpers = [[${JSON.stringify(ARRAY_START_FN)}, arrayStart], [${JSON.stringify(ARRAY_SPREAD_FN)}, spread], [${JSON.stringify(
4706
+ ARRAY_FINISH_FN
4707
+ )}, arrayFinish], [${JSON.stringify(ARRAY_SET_FN)}, guardedSet], [${JSON.stringify(ARRAY_SLOT_FN)}, slot]];
4708
+ for (var h = 0; h < helpers.length; h++) {
4709
+ defineProperty(globalThis, helpers[h][0], {
4710
+ value: helpers[h][1],
4711
+ writable: false,
4712
+ configurable: false,
4713
+ enumerable: false
4714
+ });
4715
+ }
4716
+ })(${numericLiteral("memoryLimit", memoryLimit)}, (typeof __host_memory_track__ === 'function') ? __host_memory_track__ : null);
2860
4717
  `.trim();
2861
4718
  }
2862
4719
 
@@ -3148,24 +5005,6 @@ var REALM_RUNTIME_GLOBALS = [
3148
5005
  "TypeError",
3149
5006
  "RangeError"
3150
5007
  ];
3151
- var INNER_REALM_REGEX_BACKSTOP_SOURCE = `
3152
- (function () {
3153
- 'use strict';
3154
- var defineProperty = Object.defineProperty;
3155
- var freeze = Object.freeze;
3156
- var RealmTypeError = TypeError;
3157
- var proto = RegExp.prototype;
3158
- var refuse = () => {
3159
- throw new RealmTypeError('Regular expressions are not available in this sandbox');
3160
- };
3161
- freeze(refuse);
3162
- var keys = ['exec', 'test', 'compile', Symbol.match, Symbol.matchAll, Symbol.replace, Symbol.search, Symbol.split];
3163
- for (var i = 0; i < keys.length; i++) {
3164
- defineProperty(proto, keys[i], { value: refuse, writable: false, configurable: false, enumerable: false });
3165
- }
3166
- freeze(proto);
3167
- })()
3168
- `.trim();
3169
5008
  var REALM_LOCKDOWN_SOURCE = `
3170
5009
  (function () {
3171
5010
  'use strict';
@@ -3601,6 +5440,18 @@ function generateParentVmBootstrap(options) {
3601
5440
  toolNamespaces = [],
3602
5441
  realmGlobalAllowlist
3603
5442
  } = options;
5443
+ numericLiteral("innerTimeout", innerTimeout);
5444
+ numericLiteral("maxIterations", maxIterations);
5445
+ numericLiteral("maxToolCalls", maxToolCalls);
5446
+ numericLiteral("toolBridgeMaxPayloadBytes", toolBridgeMaxPayloadBytes);
5447
+ numericLiteral("memoryLimit", memoryLimit);
5448
+ numericLiteral("maxGlobalFunctionCalls", maxGlobalFunctionCalls);
5449
+ booleanLiteral("sanitizeStackTraces", sanitizeStackTraces);
5450
+ booleanLiteral("allowComposites", allowComposites);
5451
+ booleanLiteral("throwOnBlocked", throwOnBlocked);
5452
+ if (toolBridgeMode !== "string" && toolBridgeMode !== "direct") {
5453
+ throw new TypeError(`Invalid toolBridgeMode: ${String(toolBridgeMode)}`);
5454
+ }
3604
5455
  const hasRealmAllowlist = Array.isArray(realmGlobalAllowlist);
3605
5456
  const realmAllowedNames = hasRealmAllowlist ? [
3606
5457
  .../* @__PURE__ */ new Set([
@@ -3795,6 +5646,9 @@ function generateParentVmBootstrap(options) {
3795
5646
  // source with the sources of the same length it still holds, character by character.
3796
5647
  var userCode = ${asciiStringLiteral(userCode)};
3797
5648
 
5649
+ // This realm captures no stack traces (see ../realm-stack). First, before any error is made.
5650
+ ${STACK_CAPTURE_OFF_SOURCE}
5651
+
3798
5652
  // Get injected references from host
3799
5653
  const vm = __host_vm_module__;
3800
5654
  const hostCallTool = __host_callTool__;
@@ -3807,6 +5661,9 @@ function generateParentVmBootstrap(options) {
3807
5661
  const hostIsBuiltinMethod = typeof __host_isBuiltinMethod__ === 'function' ? __host_isBuiltinMethod__ : function() { return false; };
3808
5662
  // Fail closed without the classifier: every built-in method of host data counts as mutating.
3809
5663
  const hostIsMutatingBuiltin = typeof __host_isMutatingBuiltin__ === 'function' ? __host_isMutatingBuiltin__ : function() { return true; };
5664
+ // What a method of a host function answers in place of the function's source text, or
5665
+ // undefined for a method that does not answer with it.
5666
+ const hostFunctionText = typeof __host_functionText__ === 'function' ? __host_functionText__ : function() { return undefined; };
3810
5667
  const hostConsoleSink = typeof __host_consoleSink__ === 'function' ? __host_consoleSink__ : null;
3811
5668
  // Writes one line to the host console at a level. The host console OBJECT is never in this realm.
3812
5669
  const hostConsoleWrite = typeof __host_console_write__ === 'function' ? __host_console_write__ : function() {};
@@ -3825,6 +5682,7 @@ function generateParentVmBootstrap(options) {
3825
5682
  try { delete globalThis.__host_invokeGlobal__; } catch (e) { /* ignore */ }
3826
5683
  try { delete globalThis.__host_isBuiltinMethod__; } catch (e) { /* ignore */ }
3827
5684
  try { delete globalThis.__host_isMutatingBuiltin__; } catch (e) { /* ignore */ }
5685
+ try { delete globalThis.__host_functionText__; } catch (e) { /* ignore */ }
3828
5686
  try { delete globalThis.__host_consoleSink__; } catch (e) { /* ignore */ }
3829
5687
  try { delete globalThis.__host_console_write__; } catch (e) { /* ignore */ }
3830
5688
 
@@ -3863,6 +5721,7 @@ function generateParentVmBootstrap(options) {
3863
5721
  const __ag_defineProperties = Object.defineProperties;
3864
5722
  const __ag_setPrototypeOf = Object.setPrototypeOf;
3865
5723
  const __ag_objectCreate = Object.create;
5724
+ const __ag_ParentProxy = Proxy;
3866
5725
  const __ag_objectFreeze = Object.freeze;
3867
5726
  const __ag_ReflectGet = Reflect.get;
3868
5727
  const __ag_ReflectSet = Reflect.set;
@@ -3875,7 +5734,13 @@ function generateParentVmBootstrap(options) {
3875
5734
  const __ag_ReflectGetPrototypeOf = Reflect.getPrototypeOf;
3876
5735
  const __ag_ArrayIsArray = Array.isArray;
3877
5736
  const __ag_hasOwnProperty = Object.prototype.hasOwnProperty;
5737
+ const __ag_FunctionToString = Function.prototype.toString;
5738
+ const __ag_ObjectToLocaleString = Object.prototype.toLocaleString;
3878
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;
3879
5744
 
3880
5745
  /**
3881
5746
  * Creates a "safe" error object that cannot be used to escape the sandbox.
@@ -4093,6 +5958,11 @@ function generateParentVmBootstrap(options) {
4093
5958
  return forwarder;
4094
5959
  }
4095
5960
 
5961
+ /** A function of this realm that answers with a fixed text (see hostFunctionText). */
5962
+ function createTextAnswer(text) {
5963
+ return function toString() { return text; };
5964
+ }
5965
+
4096
5966
  /**
4097
5967
  * Settle a promise of this realm the way a HOST promise settles, so the sandbox never holds
4098
5968
  * the host promise (whose 'then', 'catch' and 'finally' are host functions). A rejection
@@ -4222,6 +6092,10 @@ function generateParentVmBootstrap(options) {
4222
6092
  if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {
4223
6093
  return value;
4224
6094
  }
6095
+ // An argument guard on its way back is the script's own value again.
6096
+ if (guardedHostArguments.has(value)) {
6097
+ return guardedHostArguments.get(value);
6098
+ }
4225
6099
  if (membraneProxies.has(value) || belongsToInnerRealm(value)) {
4226
6100
  return value;
4227
6101
  }
@@ -4229,18 +6103,30 @@ function generateParentVmBootstrap(options) {
4229
6103
  }
4230
6104
 
4231
6105
  /**
4232
- * Arguments for a built-in method of host data. Such a method (map, forEach, sort, find, ...)
4233
- * calls a script callback with the elements, the index and the collection itself, and those
4234
- * are raw host objects: each callback is replaced by one that receives them wrapped.
6106
+ * Arguments for a built-in method of host data. Such a method runs in the host's realm, and
6107
+ * whatever of the script it calls, it calls with the host's own values:
6108
+ *
6109
+ * - a callback (map, forEach, sort, find, ...) receives the elements, the index and the
6110
+ * collection itself: each callback is replaced by one that receives them wrapped;
6111
+ * - a method of an object argument (the set operations ask the other collection has(element)
6112
+ * for each element of the receiver): the object is replaced by a guard, see
6113
+ * guardObjectForHost.
4235
6114
  */
4236
6115
  function guardCallbacksForHost(args) {
4237
6116
  var guardedArgs = [];
4238
6117
  for (var i = 0; i < args.length; i++) {
4239
- guardedArgs[i] = typeof args[i] === 'function' ? guardCallbackForHost(args[i]) : args[i];
6118
+ guardedArgs[i] = guardArgumentForHost(args[i]);
4240
6119
  }
4241
6120
  return guardedArgs;
4242
6121
  }
4243
6122
 
6123
+ function guardArgumentForHost(value) {
6124
+ if (typeof value === 'function') {
6125
+ return guardedHostArguments.has(value) ? value : guardCallbackForHost(value);
6126
+ }
6127
+ return guardObjectForHost(value);
6128
+ }
6129
+
4244
6130
  function guardCallbackForHost(callback) {
4245
6131
  return (...hostArgs) => {
4246
6132
  for (var i = 0; i < hostArgs.length; i++) {
@@ -4250,6 +6136,133 @@ function generateParentVmBootstrap(options) {
4250
6136
  };
4251
6137
  }
4252
6138
 
6139
+ // The guard of an object of the script, and what each guard stands for (so that a guard a
6140
+ // built-in hands back, as an element of its result say, is the script's own value again).
6141
+ const hostArgumentGuards = new WeakMap();
6142
+ const guardedHostArguments = new WeakMap();
6143
+
6144
+ /**
6145
+ * An object of the script on its way into a built-in method of host data.
6146
+ *
6147
+ * The built-in may look up a method on it and call that method with host values. So it gets a
6148
+ * guard instead: an object of this realm that answers every property read from the script's
6149
+ * object, with a function member replaced by one that passes its arguments through
6150
+ * toSandboxValue (and keeps the script's object as its receiver), and an object member or
6151
+ * result guarded the same way. Its own properties are listed as they are, so a built-in that
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.
6154
+ */
6155
+ function guardObjectForHost(value) {
6156
+ if (value === null || typeof value !== 'object') {
6157
+ return value;
6158
+ }
6159
+ if (membraneProxies.has(value) || guardedHostArguments.has(value)) {
6160
+ return value;
6161
+ }
6162
+ var existing = hostArgumentGuards.get(value);
6163
+ if (existing) {
6164
+ return existing;
6165
+ }
6166
+ if (__ag_ArrayIsArray(value)) {
6167
+ return guardArrayForHost(value);
6168
+ }
6169
+ // Over an empty object of this realm, not over the script's object: a frozen member of the
6170
+ // target would have to be reported as it is (proxy invariant), unguarded.
6171
+ var guard = new __ag_ParentProxy(__ag_objectCreate(null), {
6172
+ get: function(_shell, property) {
6173
+ return guardMemberForHost(__ag_ReflectGet(value, property, value), value);
6174
+ },
6175
+ has: function(_shell, property) {
6176
+ return __ag_ReflectHas(value, property);
6177
+ },
6178
+ // A built-in that lists the object (to copy or to serialize it) sees the script's own
6179
+ // properties, each as a data property holding what a read of it gives.
6180
+ ownKeys: function() {
6181
+ return __ag_ReflectOwnKeys(value);
6182
+ },
6183
+ getOwnPropertyDescriptor: function(_shell, property) {
6184
+ var descriptor = __ag_ReflectGetOwnPropertyDescriptor(value, property);
6185
+ if (!descriptor) {
6186
+ return undefined;
6187
+ }
6188
+ return {
6189
+ value: guardMemberForHost(__ag_ReflectGet(value, property, value), value),
6190
+ writable: true,
6191
+ enumerable: descriptor.enumerable === true,
6192
+ configurable: true
6193
+ };
6194
+ },
6195
+ // What a built-in stores in the object is a host value like any other.
6196
+ set: function(_shell, property, stored) {
6197
+ return __ag_ReflectSet(value, property, toSandboxValue(stored), value);
6198
+ }
6199
+ });
6200
+ hostArgumentGuards.set(value, guard);
6201
+ guardedHostArguments.set(guard, value);
6202
+ return guard;
6203
+ }
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
+
6251
+ function guardMemberForHost(member, holder) {
6252
+ if (typeof member !== 'function') {
6253
+ return guardObjectForHost(member);
6254
+ }
6255
+ var method = function() {
6256
+ var hostArgs = [];
6257
+ for (var i = 0; i < arguments.length; i++) {
6258
+ hostArgs[i] = toSandboxValue(arguments[i]);
6259
+ }
6260
+ return guardArgumentForHost(__ag_ReflectApply(member, holder, hostArgs));
6261
+ };
6262
+ guardedHostArguments.set(method, member);
6263
+ return method;
6264
+ }
6265
+
4253
6266
  /**
4254
6267
  * A value of THIS realm on its way into script code. Objects created here (the arrays that
4255
6268
  * Object.keys and Object.entries build, a promise of this realm) are not the script's and not
@@ -4291,6 +6304,112 @@ function generateParentVmBootstrap(options) {
4291
6304
  };
4292
6305
  }
4293
6306
 
6307
+ // SECURITY (a function of the script on a value of this realm): a script can store a function
6308
+ // of its own on a value of THIS realm that it holds behind the membrane (a tool result, the
6309
+ // array a built-in made, a promise), as a property, a getter or a setter. Whoever finds the
6310
+ // function there calls it: the script through the membrane, but also a built-in of this realm
6311
+ // that works on the raw value (a conversion looks up toString, a read runs a getter), and that
6312
+ // built-in calls it with the raw value as its receiver. So what is stored on the raw value is
6313
+ // never the script's function but a guard of this realm that calls it with what the script may
6314
+ // hold (see guardCallbackForRealm), and a read through the membrane gives the script its own
6315
+ // function back.
6316
+ const scriptFunctionGuards = new WeakMap();
6317
+ const guardedScriptFunctions = new WeakMap();
6318
+
6319
+ function isScriptFunction(value) {
6320
+ return typeof value === 'function' && !membraneProxies.has(value) && belongsToInnerRealm(value);
6321
+ }
6322
+
6323
+ function guardScriptFunction(fn) {
6324
+ var existing = scriptFunctionGuards.get(fn);
6325
+ if (existing) {
6326
+ return existing;
6327
+ }
6328
+ var guard = guardCallbackForRealm(fn);
6329
+ scriptFunctionGuards.set(fn, guard);
6330
+ guardedScriptFunctions.set(guard, fn);
6331
+ return guard;
6332
+ }
6333
+
6334
+ /**
6335
+ * Whether a value is a raw object or function of this realm: not a primitive, not the script's
6336
+ * own, not a safe error and not behind the membrane already.
6337
+ */
6338
+ function isRawRealmReference(value) {
6339
+ if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {
6340
+ return false;
6341
+ }
6342
+ return !membraneProxies.has(value) && !safeErrors.has(value) && !belongsToInnerRealm(value);
6343
+ }
6344
+
6345
+ /**
6346
+ * The descriptor to apply when a script defines a property on a value of this realm.
6347
+ *
6348
+ * - A function of the script (the value, the getter or the setter) is stored as its guard.
6349
+ * - A data property that ends up neither configurable nor writable is pinned: the language
6350
+ * requires every later read through a Proxy to answer with exactly what is stored. What is
6351
+ * stored then is the membrane's own answer for the value (its proxy), so that freezing or
6352
+ * sealing a value does not turn its nested values into raw objects of this realm.
6353
+ */
6354
+ function descriptorForRealmValue(obj, property, descriptor, depth) {
6355
+ if (descriptor === null || typeof descriptor !== 'object') {
6356
+ return descriptor;
6357
+ }
6358
+ var next = {};
6359
+ var fields = ['value', 'get', 'set', 'writable', 'enumerable', 'configurable'];
6360
+ for (var f = 0; f < fields.length; f++) {
6361
+ if (fields[f] in descriptor) next[fields[f]] = descriptor[fields[f]];
6362
+ }
6363
+ if (isScriptFunction(next.value)) next.value = guardScriptFunction(next.value);
6364
+ if (isScriptFunction(next.get)) next.get = guardScriptFunction(next.get);
6365
+ if (isScriptFunction(next.set)) next.set = guardScriptFunction(next.set);
6366
+
6367
+ if ('get' in next || 'set' in next) {
6368
+ return next;
6369
+ }
6370
+ var current = __ag_getOwnPropertyDescriptor(obj, property);
6371
+ var currentIsData = !!current && 'value' in current;
6372
+ if (current && !currentIsData && !('value' in next) && !('writable' in next)) {
6373
+ // Stays an accessor
6374
+ return next;
6375
+ }
6376
+ if (currentIsData && !current.configurable && !current.writable) {
6377
+ // Pinned already: nothing can be stored in its place
6378
+ return next;
6379
+ }
6380
+ var configurable = 'configurable' in next ? next.configurable : (current ? current.configurable : false);
6381
+ var writable = 'writable' in next ? next.writable : (currentIsData ? current.writable : false);
6382
+ if (!configurable && !writable) {
6383
+ var pinned = 'value' in next ? next.value : (currentIsData ? current.value : undefined);
6384
+ if (isRawRealmReference(pinned)) {
6385
+ next.value = createSecureProxy(pinned, depth + 1, false);
6386
+ }
6387
+ }
6388
+ return next;
6389
+ }
6390
+
6391
+ /**
6392
+ * An object of this realm on its way behind the membrane: a function of the script that a
6393
+ * built-in of this realm stored in it by name (Object.fromEntries, Object.groupBy) is replaced
6394
+ * by its guard, as the membrane does for a function the script stores there itself. An array
6395
+ * holds its items by index, which no built-in calls as a method of the array.
6396
+ */
6397
+ function guardScriptFunctionsOf(obj) {
6398
+ var keys;
6399
+ try {
6400
+ keys = __ag_ReflectOwnKeys(obj);
6401
+ } catch (e) {
6402
+ return;
6403
+ }
6404
+ for (var k = 0; k < keys.length; k++) {
6405
+ var own = __ag_getOwnPropertyDescriptor(obj, keys[k]);
6406
+ if (!own || !('value' in own) || !own.writable || !isScriptFunction(own.value)) continue;
6407
+ try {
6408
+ obj[keys[k]] = guardScriptFunction(own.value);
6409
+ } catch (e) { /* left as it is */ }
6410
+ }
6411
+ }
6412
+
4294
6413
  /**
4295
6414
  * The result of a built-in method of host data. An array (map, filter, slice, concat, ...) is
4296
6415
  * copied into an array of this realm, so the script can sort or extend what it derived
@@ -4301,6 +6420,9 @@ function generateParentVmBootstrap(options) {
4301
6420
  if (result === null || (typeof result !== 'object' && typeof result !== 'function')) {
4302
6421
  return result;
4303
6422
  }
6423
+ if (guardedHostArguments.has(result)) {
6424
+ result = guardedHostArguments.get(result);
6425
+ }
4304
6426
  if (membraneProxies.has(result)) {
4305
6427
  return result;
4306
6428
  }
@@ -4394,6 +6516,12 @@ function generateParentVmBootstrap(options) {
4394
6516
  return obj;
4395
6517
  }
4396
6518
 
6519
+ // An argument guard (see guardObjectForHost) that a built-in of host data kept in what it
6520
+ // returned stands for a value of the script: that value is what the script gets back.
6521
+ if (guardedHostArguments.has(obj)) {
6522
+ return guardedHostArguments.get(obj);
6523
+ }
6524
+
4397
6525
  // Check cache
4398
6526
  var cache = host ? hostProxyCache : proxyCache;
4399
6527
  if (cache.has(obj)) {
@@ -4408,6 +6536,15 @@ function generateParentVmBootstrap(options) {
4408
6536
  var shelled = typeof obj === 'function' && !realmOwnedCallables.has(obj);
4409
6537
  var proxyTarget = shelled ? newCallableShell() : obj;
4410
6538
 
6539
+ // Whether obj is a value of THIS realm: neither the host's nor the script's own (an array a
6540
+ // built-in made, a tool result, a promise of this realm, a forwarder). Decided once, here:
6541
+ // the answer follows the prototype chain, which a script cannot change afterwards (see the
6542
+ // setPrototypeOf trap).
6543
+ var foreign = !host && !belongsToInnerRealm(obj);
6544
+ if (foreign && typeof obj === 'object' && !__ag_ArrayIsArray(obj)) {
6545
+ guardScriptFunctionsOf(obj);
6546
+ }
6547
+
4411
6548
  var handler = {
4412
6549
  get: function(_target, property, receiver) {
4413
6550
  var propName = String(property);
@@ -4435,6 +6572,15 @@ function generateParentVmBootstrap(options) {
4435
6572
  // A shelled callable is not the Proxy target, so no invariant pins its value: a
4436
6573
  // reference takes the blocking and wrapping path below like any other read.
4437
6574
  if (!shelled || !exactIsReference) {
6575
+ // A raw object of this realm that is pinned in a value of this realm (a member of
6576
+ // an intrinsic of this realm, which is frozen) can be neither handed over nor
6577
+ // wrapped. What a script pins itself is stored wrapped (descriptorForRealmValue).
6578
+ if (foreign && isRawRealmReference(exactValue)) {
6579
+ throw createSafeError(
6580
+ "Security violation: Access to '" + propName + "' is blocked. " +
6581
+ "This property cannot be exposed without breaking the sandbox barrier."
6582
+ );
6583
+ }
4438
6584
  return exactValue;
4439
6585
  }
4440
6586
  }
@@ -4474,6 +6620,29 @@ function generateParentVmBootstrap(options) {
4474
6620
  // block constructor access. It is a closure rather than value.bind(obj): a bound
4475
6621
  // function keeps the realm of its target (see realmOwnedCallables).
4476
6622
  if (typeof value === 'function') {
6623
+ // A function of the script that sits on a value of this realm is the script's own: it
6624
+ // gets it back as it is, and calls it on the value it holds (see guardScriptFunction).
6625
+ if (foreign) {
6626
+ if (guardedScriptFunctions.has(value)) {
6627
+ return guardedScriptFunctions.get(value);
6628
+ }
6629
+ if (isScriptFunction(value)) {
6630
+ return value;
6631
+ }
6632
+ }
6633
+ // The text of a host function is a fixed form, never its source: toString (and
6634
+ // toLocaleString, which calls it) read off a host function answer with that form. A
6635
+ // forwarder stands for the host method it calls, and its own methods are this realm's.
6636
+ if (host && typeof obj === 'function') {
6637
+ var ownTextMethod = value === __ag_FunctionToString || value === __ag_ObjectToLocaleString;
6638
+ var functionText = hostFunctionText(
6639
+ ownTextMethod ? null : value,
6640
+ forwardedMethods.has(obj) ? forwardedMethods.get(obj) : obj
6641
+ );
6642
+ if (typeof functionText === 'string') {
6643
+ return createSecureProxy(createTextAnswer(functionText), depth + 1, false);
6644
+ }
6645
+ }
4477
6646
  var hostBuiltin = host && hostIsBuiltinMethod(value);
4478
6647
  // push, sort, Map.prototype.set, ... called on host data would write to the host's
4479
6648
  // own object without ever reaching the set trap.
@@ -4484,7 +6653,7 @@ function generateParentVmBootstrap(options) {
4484
6653
  var method = createMethodForwarder(value, obj);
4485
6654
  if (hostBuiltin) {
4486
6655
  ungatedHostFunctions.add(method);
4487
- } else if (!host && typeof obj === 'object' && !belongsToInnerRealm(obj)) {
6656
+ } else if (foreign && typeof obj === 'object') {
4488
6657
  parentRealmMethods.add(method);
4489
6658
  }
4490
6659
  return createSecureProxy(method, depth + 1, host);
@@ -4535,7 +6704,11 @@ function generateParentVmBootstrap(options) {
4535
6704
  "Security violation: Defining non-configurable property '" + propName + "' on a function is blocked."
4536
6705
  );
4537
6706
  }
4538
- return __ag_ReflectDefineProperty(obj, property, descriptor);
6707
+ return __ag_ReflectDefineProperty(
6708
+ obj,
6709
+ property,
6710
+ foreign ? descriptorForRealmValue(obj, property, descriptor, depth) : descriptor
6711
+ );
4539
6712
  },
4540
6713
  deleteProperty: function(_target, property) {
4541
6714
  if (host) {
@@ -4600,6 +6773,23 @@ function generateParentVmBootstrap(options) {
4600
6773
  // path below, described as configurable.
4601
6774
  if (descriptor && !descriptor.configurable) {
4602
6775
  if (!shelled) {
6776
+ // On a value of this realm such a description would hand out a raw object of this
6777
+ // realm. A writable property may be described with another value (the wrapped one);
6778
+ // a pinned one may not, and is refused as the get trap refuses it.
6779
+ if (foreign && 'value' in descriptor && isRawRealmReference(descriptor.value)) {
6780
+ if (descriptor.writable === false) {
6781
+ throw createSafeError(
6782
+ "Security violation: Access to property descriptor for '" + propName + "' is blocked. " +
6783
+ "This property cannot be exposed without breaking the sandbox barrier."
6784
+ );
6785
+ }
6786
+ var described = {};
6787
+ for (var nk in descriptor) { if (__ag_hasOwnProperty.call(descriptor, nk)) described[nk] = descriptor[nk]; }
6788
+ described.value = guardedScriptFunctions.has(descriptor.value)
6789
+ ? guardedScriptFunctions.get(descriptor.value)
6790
+ : createSecureProxy(descriptor.value, depth + 1, false);
6791
+ return described;
6792
+ }
4603
6793
  return descriptor;
4604
6794
  }
4605
6795
  descriptor = reportable(descriptor);
@@ -4621,8 +6811,18 @@ function generateParentVmBootstrap(options) {
4621
6811
  if (descriptor && (typeof descriptor.get === 'function' || typeof descriptor.set === 'function')) {
4622
6812
  var accessorWrapped = {};
4623
6813
  for (var ak in descriptor) { if (__ag_hasOwnProperty.call(descriptor, ak)) accessorWrapped[ak] = descriptor[ak]; }
4624
- if (typeof descriptor.get === 'function') accessorWrapped.get = createSecureProxy(descriptor.get, depth + 1, host);
4625
- if (typeof descriptor.set === 'function') accessorWrapped.set = createSecureProxy(descriptor.set, depth + 1, host);
6814
+ // A getter or setter of the script is described as the script's function, not as the
6815
+ // guard that is stored for it (see guardScriptFunction).
6816
+ if (typeof descriptor.get === 'function') {
6817
+ accessorWrapped.get = guardedScriptFunctions.has(descriptor.get)
6818
+ ? guardedScriptFunctions.get(descriptor.get)
6819
+ : createSecureProxy(descriptor.get, depth + 1, host);
6820
+ }
6821
+ if (typeof descriptor.set === 'function') {
6822
+ accessorWrapped.set = guardedScriptFunctions.has(descriptor.set)
6823
+ ? guardedScriptFunctions.get(descriptor.set)
6824
+ : createSecureProxy(descriptor.set, depth + 1, host);
6825
+ }
4626
6826
  return accessorWrapped;
4627
6827
  }
4628
6828
 
@@ -4638,7 +6838,9 @@ function generateParentVmBootstrap(options) {
4638
6838
  var refusedValue = (host && typeof value === 'function' && hostIsBuiltinMethod(value))
4639
6839
  ? refusedHostBuiltin(value, propName, depth)
4640
6840
  : null;
4641
- wrapped.value = refusedValue || createSecureProxy(value, depth + 1, host);
6841
+ wrapped.value = refusedValue || (guardedScriptFunctions.has(value)
6842
+ ? guardedScriptFunctions.get(value)
6843
+ : createSecureProxy(value, depth + 1, host));
4642
6844
  return wrapped;
4643
6845
  }
4644
6846
  }
@@ -4669,9 +6871,10 @@ function generateParentVmBootstrap(options) {
4669
6871
  // Return null to hide prototype chain
4670
6872
  return null;
4671
6873
  },
4672
- // The default would change the prototype of the Proxy target: of the shell (pointless), or
4673
- // of a host-owned value (a write to the host).
4674
- setPrototypeOf: (host || shelled) ? function() {
6874
+ // The default would change the prototype of the Proxy target: of the shell (pointless), of
6875
+ // a host-owned value (a write to the host), or of a value of this realm, whose prototype
6876
+ // chain is how the membrane tells it from a value of the script (see 'foreign' above).
6877
+ setPrototypeOf: (host || shelled || foreign) ? function() {
4675
6878
  if (host) {
4676
6879
  return refuseHostWrite('Changing the prototype of the value', false);
4677
6880
  }
@@ -4744,7 +6947,10 @@ function generateParentVmBootstrap(options) {
4744
6947
  * Sliding one-second window; entries older than two seconds are dropped.
4745
6948
  */
4746
6949
  function enforceRateLimit(now) {
4747
- while (operationHistory.length > 0 && now - operationHistory[0].timestamp > 2000) {
6950
+ // Kept for as long as the longest look-back of a sequence detector (30 seconds for the
6951
+ // built-in ones, twice that here), not only for the rate window below: a detector that
6952
+ // asks for the last ten seconds has to find them.
6953
+ while (operationHistory.length > 0 && now - operationHistory[0].timestamp > 60000) {
4748
6954
  operationHistory.shift();
4749
6955
  }
4750
6956
  while (globalFunctionCallTimes.length > 0 && now - globalFunctionCallTimes[0] > 2000) {
@@ -4835,8 +7041,11 @@ function generateParentVmBootstrap(options) {
4835
7041
  throw createSafeError('Operation name must be a non-empty string', 'TypeError');
4836
7042
  }
4837
7043
 
4838
- // 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.
4839
7047
  if (validationConfig.validateOperationNames && typeof allowedOperationPattern !== 'undefined') {
7048
+ allowedOperationPattern.lastIndex = 0;
4840
7049
  if (!allowedOperationPattern.test(operationName)) {
4841
7050
  throw createSafeError('Operation "' + operationName + '" does not match allowed pattern');
4842
7051
  }
@@ -4845,6 +7054,7 @@ function generateParentVmBootstrap(options) {
4845
7054
  // Operation name pattern validation (blacklist)
4846
7055
  if (typeof blockedOperationPatterns !== 'undefined') {
4847
7056
  for (var i = 0; i < blockedOperationPatterns.length; i++) {
7057
+ blockedOperationPatterns[i].lastIndex = 0;
4848
7058
  if (blockedOperationPatterns[i].test(operationName)) {
4849
7059
  throw createSafeError('Operation "' + operationName + '" matches blocked pattern');
4850
7060
  }
@@ -4917,6 +7127,58 @@ function generateParentVmBootstrap(options) {
4917
7127
  return false;
4918
7128
  }
4919
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
+
4920
7182
  /**
4921
7183
  * Inner VM's callTool function
4922
7184
  * Proxies through parent VM with validation
@@ -4944,11 +7206,16 @@ function generateParentVmBootstrap(options) {
4944
7206
  throw createSafeError('Tool arguments must be an object', 'TypeError');
4945
7207
  }
4946
7208
 
4947
- // 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.
4948
7212
  var sanitizedArgs;
4949
7213
  try {
4950
- sanitizedArgs = JSON.parse(JSON.stringify(args));
7214
+ sanitizedArgs = JSON.parse(stringifyWithin(args, toolBridgeMaxPayloadBytes));
4951
7215
  } catch (e) {
7216
+ if (e === TOO_LARGE) {
7217
+ throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
7218
+ }
4952
7219
  throw createSafeError('Tool arguments must be JSON-serializable');
4953
7220
  }
4954
7221
 
@@ -5040,8 +7307,12 @@ function generateParentVmBootstrap(options) {
5040
7307
  throw createSafeError('Tool bridge returned invalid response');
5041
7308
  });
5042
7309
  } else {
5043
- // Direct mode: the rejection is mapped here rather than by launderThrown alone, which
5044
- // 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.
5045
7316
  promise = deferHostCall(function() {
5046
7317
  return hostCallTool(toolName, sanitizedArgs);
5047
7318
  }, function(error) {
@@ -5051,9 +7322,16 @@ function generateParentVmBootstrap(options) {
5051
7322
  code = error && error.code;
5052
7323
  message = error && error.message;
5053
7324
  } catch (e) { /* treated as an unmarked failure */ }
5054
- 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
+ ) {
5055
7333
  var text = typeof message === 'string' ? message : 'Tool call failed';
5056
- return markToolFailure(createSafeError(text), toolName, 'Error', text, 'TOOL_CALL_FAILED');
7334
+ return markToolFailure(createSafeError(text), toolName, 'Error', text, code);
5057
7335
  }
5058
7336
  return launderThrown(error);
5059
7337
  });
@@ -5313,8 +7591,9 @@ function generateParentVmBootstrap(options) {
5313
7591
  * Rate-limited console for inner VM
5314
7592
  */
5315
7593
  var consoleStats = { totalBytes: 0, callCount: 0 };
5316
- var maxConsoleBytes = hostConfig.maxConsoleOutputBytes || 65536;
5317
- 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;
5318
7597
 
5319
7598
  function createSafeConsoleMethod(level) {
5320
7599
  return function() {
@@ -5374,6 +7653,10 @@ function generateParentVmBootstrap(options) {
5374
7653
  codeGeneration: { strings: false, wasm: false }
5375
7654
  });
5376
7655
 
7656
+ // The inner realm captures no stack traces, at every security level (see ../realm-stack): the
7657
+ // first thing that runs there, while its Error is the intrinsic one.
7658
+ new vm.Script(${JSON.stringify(STACK_CAPTURE_OFF_SOURCE)}, { filename: 'inner-stack.js' }).runInContext(innerContext);
7659
+
5377
7660
  // The function that removes globals from the inner realm at the end of setup (see
5378
7661
  // INNER_REALM_SCRUB_SOURCE). Compiled before anything else runs there.
5379
7662
  var __ag_scrubInnerRealm = new vm.Script(${JSON.stringify(INNER_REALM_SCRUB_SOURCE)}, {
@@ -5425,7 +7708,9 @@ function generateParentVmBootstrap(options) {
5425
7708
  // The script's cooperative deadline (see ../deadline-guard): the inner realm's __safe_tick,
5426
7709
  // which the transformed script calls at every function entry and loop iteration. vm's timeout
5427
7710
  // below only covers the script up to its first await.
5428
- new vm.Script(${JSON.stringify(realmTickSource(innerTimeout))}, {
7711
+ // What that script evaluates to ends the checks: called when the script has settled, it makes
7712
+ // whatever the script left behind stop at its next function entry or loop iteration.
7713
+ var __ag_endDeadlineChecks = new vm.Script(${JSON.stringify(realmTickSource(innerTimeout))}, {
5429
7714
  filename: 'inner-deadline.js'
5430
7715
  }).runInContext(innerContext);
5431
7716
 
@@ -5491,6 +7776,9 @@ function generateParentVmBootstrap(options) {
5491
7776
  // Strict mode: an unbound call (const f = [].fill; f(0)) must fail on its undefined "this".
5492
7777
  // In sloppy mode "this" was coerced to the realm's global object, and fill RETURNED it.
5493
7778
  '"use strict";' +
7779
+ // The functions of Math, not the object: a script can assign to its members, and a
7780
+ // replaced Math.max would decide what a fill is charged.
7781
+ 'Math = { max: Math.max, min: Math.min, round: Math.round };' +
5494
7782
  'var memoryLimit = ' + memoryLimit + ';' +
5495
7783
  'var trackMemory = __host_memory_track__;' +
5496
7784
  // A size is only usable when it is a positive number. NaN (a missing or non-numeric count,
@@ -5562,31 +7850,21 @@ function generateParentVmBootstrap(options) {
5562
7850
  ' trackMemory(estimatedSize);' +
5563
7851
  ' return chargeActual(originalPadEnd.call(this, targetLength, padString), estimatedSize, "String.padEnd");' +
5564
7852
  '};' +
5565
- // Patch array fill - converts sparse arrays to dense (allocates memory)
5566
- // Vector 1110/1170: Array(dynamicSize).fill() can exhaust memory
5567
- 'var originalFill = arrayProto.fill;' +
5568
- 'arrayProto.fill = function(value, start, end) {' +
5569
- ' var len = this.length >>> 0;' +
5570
- ' var relativeStart = start === undefined ? 0 : (start >> 0);' +
5571
- ' var relativeEnd = end === undefined ? len : (end >> 0);' +
5572
- ' var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len);' +
5573
- ' var finalEnd = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len);' +
5574
- ' var fillCount = Math.max(0, finalEnd - k);' +
5575
- ' var estimatedSize = fillCount * 8;' +
5576
- ' if (estimatedSize > memoryLimit) {' +
5577
- ' throw new RangeError("Array.fill would exceed memory limit: " +' +
5578
- ' Math.round(estimatedSize / 1024 / 1024) + "MB > " +' +
5579
- ' Math.round(memoryLimit / 1024 / 1024) + "MB");' +
5580
- ' }' +
5581
- ' trackMemory(estimatedSize);' +
5582
- ' return originalFill.call(this, value, start, end);' +
5583
- '};' +
7853
+ // Array.prototype.fill is accounted for with the other array operations (see
7854
+ // ../realm-memory), where its range is worked out by the built-in's own rules.
5584
7855
  '})(Math, String, RangeError);';
5585
7856
  var patchScript = new vm.Script(patchCode);
5586
7857
  patchScript.runInContext(innerContext);
5587
7858
  }
5588
7859
  })();
5589
7860
 
7861
+ // Arrays that grow are accounted for like strings that grow (see ../realm-memory), and the
7862
+ // helpers the transformed code calls around an array literal with spreads are defined. Always:
7863
+ // without a memory limit the helpers count nothing.
7864
+ new vm.Script(${JSON.stringify(realmArrayAccountingSource(memoryLimit))}, {
7865
+ filename: 'inner-array-accounting.js'
7866
+ }).runInContext(innerContext);
7867
+
5590
7868
  // ============================================================
5591
7869
  // PHASE 2 HARDENING: CVE-2023-29017 Stack Overflow Escape Defense
5592
7870
  // ============================================================
@@ -5868,7 +8146,7 @@ function generateParentVmBootstrap(options) {
5868
8146
  // After inner-runtime.js, whose one trusted pattern has kept its own matcher. Not optional:
5869
8147
  // a failure here aborts the execution.
5870
8148
  if (__ag_realmAllowed && __ag_realmAllowed.RegExp !== true) {
5871
- new vm.Script(${JSON.stringify(INNER_REALM_REGEX_BACKSTOP_SOURCE)}, {
8149
+ new vm.Script(${JSON.stringify(REALM_REGEX_BACKSTOP_SOURCE)}, {
5872
8150
  filename: 'inner-regex-backstop.js'
5873
8151
  }).runInContext(innerContext);
5874
8152
  }
@@ -5930,6 +8208,7 @@ function generateParentVmBootstrap(options) {
5930
8208
  var getIntrinsicsCode =
5931
8209
  '({ ' +
5932
8210
  ' Array: Array, ' +
8211
+ ' objectAssign: Object.assign, ' +
5933
8212
  ' String: String, ' +
5934
8213
  ' Number: Number, ' +
5935
8214
  ' Boolean: Boolean, ' +
@@ -5954,6 +8233,13 @@ function generateParentVmBootstrap(options) {
5954
8233
  return script.runInContext(innerContext);
5955
8234
  })();
5956
8235
 
8236
+ // Object.assign is the inner realm's: where memory is accounted for, that one keeps an array
8237
+ // within what the limit holds (see ../realm-memory); this realm's own would write to an
8238
+ // array of the script unseen.
8239
+ if (typeof innerIntrinsics.objectAssign === 'function') {
8240
+ SafeObject.assign = innerIntrinsics.objectAssign;
8241
+ }
8242
+
5957
8243
  // The constructors the script uses with new and instanceof. They are proxied directly (see
5958
8244
  // realmOwnedCallables): each belongs to the inner realm, except SafeObject, which is a
5959
8245
  // function of this realm. Neither realm can generate code from strings.
@@ -6146,10 +8432,16 @@ function generateParentVmBootstrap(options) {
6146
8432
  __ag_lockdownParentRealm();
6147
8433
 
6148
8434
  // Note: codeGeneration is set in createContext(), not runInContext()
6149
- var result = await script.runInContext(innerContext, {
6150
- timeout: ${innerTimeout},
6151
- breakOnSigint: true
6152
- });
8435
+ var result;
8436
+ try {
8437
+ result = await script.runInContext(innerContext, {
8438
+ timeout: ${innerTimeout},
8439
+ breakOnSigint: true
8440
+ });
8441
+ } finally {
8442
+ // The execution is over, whichever way: nothing the script left behind runs on from here
8443
+ try { __ag_endDeadlineChecks(); } catch (e) { /* the realm is gone */ }
8444
+ }
6153
8445
 
6154
8446
  return result;
6155
8447
  })();
@@ -6180,7 +8472,8 @@ var RAPID_ENUMERATION = {
6180
8472
  if (localConfig) {
6181
8473
  const defaultThreshold = localConfig.rapidEnumerationThreshold ?? 30;
6182
8474
  const overrides = localConfig.rapidEnumerationOverrides ?? {};
6183
- threshold = overrides[operationName] ?? defaultThreshold;
8475
+ const override = Object.prototype.hasOwnProperty.call(overrides, operationName) ? overrides[operationName] : void 0;
8476
+ threshold = typeof override === "number" ? override : defaultThreshold;
6184
8477
  }
6185
8478
  } catch {
6186
8479
  threshold = 30;
@@ -6207,7 +8500,8 @@ var BULK_OPERATION = {
6207
8500
  if (typeof args === "object" && args !== null) {
6208
8501
  try {
6209
8502
  const argStr = JSON.stringify(args).toLowerCase();
6210
- const hasBulkArgs = /limit.*[0-9]{4,}|"\*"|no[_-]?limit/i.test(argStr);
8503
+ const firstLimit = argStr.indexOf("limit");
8504
+ const hasBulkArgs = firstLimit >= 0 && /[0-9]{4}/.test(argStr.slice(firstLimit + 5)) || argStr.indexOf('"*"') >= 0 || argStr.indexOf("nolimit") >= 0 || argStr.indexOf("no_limit") >= 0 || argStr.indexOf("no-limit") >= 0;
6211
8505
  if (hasBulkArgs) return true;
6212
8506
  } catch {
6213
8507
  }
@@ -6277,6 +8571,12 @@ function serializePatterns(patterns) {
6277
8571
  }
6278
8572
 
6279
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
+ }
6280
8580
  var DoubleVmWrapper = class {
6281
8581
  /**
6282
8582
  * @param config Double VM configuration
@@ -6375,17 +8675,18 @@ var DoubleVmWrapper = class {
6375
8675
  memSnapshot = memoryTracker.getSnapshot();
6376
8676
  stats.memoryUsage = memSnapshot.peakTrackedBytes;
6377
8677
  }
6378
- if (error instanceof MemoryLimitError || error && typeof error === "object" && error.code === "MEMORY_LIMIT_EXCEEDED") {
6379
- const payload = error;
6380
- const usedBytes = typeof payload.usedBytes === "number" ? payload.usedBytes : memSnapshot?.trackedBytes ?? 0;
6381
- const limitBytes = typeof payload.limitBytes === "number" ? payload.limitBytes : config.memoryLimit ?? 0;
8678
+ const thrown = describeThrown(error);
8679
+ if (error instanceof MemoryLimitError || memoryTracker?.hasExceededLimit() === true && isMemoryLimitPayload(error)) {
6382
8680
  return {
6383
8681
  success: false,
6384
8682
  error: {
6385
8683
  name: "MemoryLimitError",
6386
- message: typeof payload.message === "string" ? payload.message : "Memory limit exceeded",
8684
+ message: thrown.message ?? "Memory limit exceeded",
6387
8685
  code: "MEMORY_LIMIT_EXCEEDED",
6388
- data: { usedBytes, limitBytes }
8686
+ data: {
8687
+ usedBytes: error instanceof MemoryLimitError ? error.usedBytes : memSnapshot?.trackedBytes ?? 0,
8688
+ limitBytes: error instanceof MemoryLimitError ? error.limitBytes : config.memoryLimit ?? 0
8689
+ }
6389
8690
  },
6390
8691
  stats
6391
8692
  };
@@ -6396,19 +8697,18 @@ var DoubleVmWrapper = class {
6396
8697
  success: false,
6397
8698
  error: {
6398
8699
  name: "DoubleVMExecutionError",
6399
- message: error,
8700
+ message: thrown.message ?? "",
6400
8701
  code: "DOUBLE_VM_EXECUTION_ERROR"
6401
8702
  },
6402
8703
  stats
6403
8704
  };
6404
8705
  }
6405
- const err = error;
6406
8706
  return {
6407
8707
  success: false,
6408
8708
  error: {
6409
- name: err.name || "DoubleVMExecutionError",
6410
- message: err.message || "Unknown double VM execution error",
6411
- stack: sanitizeStackTrace(err.stack, shouldSanitize),
8709
+ name: thrown.name || "DoubleVMExecutionError",
8710
+ message: thrown.message || THROWN_WITHOUT_MESSAGE,
8711
+ stack: sanitizeStackTrace(thrown.stack, shouldSanitize),
6412
8712
  code: "DOUBLE_VM_EXECUTION_ERROR"
6413
8713
  },
6414
8714
  stats
@@ -6468,6 +8768,12 @@ var DoubleVmWrapper = class {
6468
8768
  configurable: true
6469
8769
  // Allow deletion after capture for defense-in-depth
6470
8770
  });
8771
+ Object.defineProperty(parentContext, "__host_functionText__", {
8772
+ value: (method, fn) => method === null || isFunctionTextMethod(method) ? hostFunctionText(fn) : void 0,
8773
+ writable: false,
8774
+ configurable: true
8775
+ // Allow deletion after capture for defense-in-depth
8776
+ });
6471
8777
  Object.defineProperty(parentContext, "__host_stats__", {
6472
8778
  value: stats,
6473
8779
  writable: false,
@@ -6594,33 +8900,72 @@ var DoubleVmWrapper = class {
6594
8900
  }
6595
8901
  resolvedArgs = resolver.resolve(args);
6596
8902
  }
8903
+ let handlerCompleted = false;
6597
8904
  try {
6598
8905
  const result = await toolHandler(toolName, resolvedArgs);
8906
+ handlerCompleted = true;
6599
8907
  const sanitized = sanitizeValue(result, {
6600
8908
  maxDepth: config.maxSanitizeDepth,
6601
8909
  maxProperties: config.maxSanitizeProperties,
6602
8910
  allowDates: true,
6603
8911
  allowErrors: true
6604
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;
6605
8931
  if (sidecar && referenceConfig && typeof sanitized === "string") {
6606
8932
  const size = Buffer.byteLength(sanitized, "utf-8");
6607
8933
  if (size >= referenceConfig.extractionThreshold) {
6608
8934
  try {
6609
- const refId = sidecar.store(sanitized, "tool-result", { origin: toolName });
6610
- return refId;
6611
- } catch (storageError) {
6612
- if (process.env["NODE_ENV"] !== "production") {
6613
- console.debug(
6614
- `[DoubleVmWrapper] Sidecar storage failed for tool "${toolName}": ${storageError.message}`
6615
- );
6616
- }
6617
- 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");
6618
8938
  }
6619
8939
  }
6620
8940
  }
6621
- 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;
6622
8962
  } catch (error) {
8963
+ if (handlerCompleted) executionContext.onToolBridgeFailure?.();
6623
8964
  const err = error;
8965
+ const refused = resultRefusals.get(error);
8966
+ if (refused) {
8967
+ throw createSafeError(err.message, "Error", refused);
8968
+ }
6624
8969
  throw createSafeError(
6625
8970
  `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`,
6626
8971
  "Error",
@@ -6822,10 +9167,17 @@ function createSafeRuntime(context, options) {
6822
9167
  const secureProxyConfig = options?.secureProxyConfig;
6823
9168
  const memoryTracker = options?.memoryTracker;
6824
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
+ };
6825
9176
  const proxyOptions = {
6826
9177
  ...secureProxyConfig ? { levelConfig: secureProxyConfig } : {},
6827
9178
  ...options?.exposeToSandbox ? { exposeToSandbox: options.exposeToSandbox } : {},
6828
- ...options?.ownedBySandbox ? { ownedBySandbox: options.ownedBySandbox } : {}
9179
+ ...options?.ownedBySandbox ? { ownedBySandbox: options.ownedBySandbox } : {},
9180
+ ...options?.heldBySandbox ? { heldBySandbox: options.heldBySandbox } : {}
6829
9181
  };
6830
9182
  async function __safe_callTool(toolName, args, options2) {
6831
9183
  const throwOnError = readThrowOnError(options2);
@@ -6847,6 +9199,21 @@ function createSafeRuntime(context, options) {
6847
9199
  if (!context.toolHandler) {
6848
9200
  throw createSafeError("No tool handler configured. Cannot execute tool calls.");
6849
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
+ }
6850
9217
  let resolvedArgs = args;
6851
9218
  if (resolver && resolver.containsReferences(args)) {
6852
9219
  if (resolver.wouldExceedLimit(args)) {
@@ -6866,12 +9233,34 @@ function createSafeRuntime(context, options) {
6866
9233
  }
6867
9234
  try {
6868
9235
  const result = await context.toolHandler(toolName, resolvedArgs);
6869
- const sanitized = sanitizeValue(result, {
6870
- maxDepth: 20,
6871
- maxProperties: 1e4,
6872
- allowDates: true,
6873
- allowErrors: true
6874
- });
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
+ }
6875
9264
  let value = sanitized;
6876
9265
  if (sidecar && referenceConfig && typeof sanitized === "string") {
6877
9266
  const size = Buffer.byteLength(sanitized, "utf-8");
@@ -6879,27 +9268,47 @@ function createSafeRuntime(context, options) {
6879
9268
  try {
6880
9269
  value = sidecar.store(sanitized, "tool-result", { origin: toolName });
6881
9270
  } catch {
6882
- value = sanitized;
9271
+ refuseToolResult("Tool result could not be stored in the reference sidecar", "TOOL_RESULT_NOT_STORED");
6883
9272
  }
6884
9273
  }
6885
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
+ }
6886
9294
  return throwOnError ? value : plainResult({ success: true, data: value });
6887
9295
  } catch (error) {
6888
9296
  const err = error;
6889
9297
  const message = `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`;
6890
9298
  if (!throwOnError) {
6891
- const code = error?.code;
9299
+ const code2 = error?.code;
6892
9300
  return plainResult({
6893
9301
  success: false,
6894
9302
  error: plainResult({
6895
9303
  name: "Error",
6896
9304
  message,
6897
- ...typeof code === "string" ? { code } : {},
9305
+ ...typeof code2 === "string" ? { code: code2 } : {},
6898
9306
  toolName
6899
9307
  })
6900
9308
  });
6901
9309
  }
6902
- throw createSafeError(message);
9310
+ const code = error?.code;
9311
+ throw createSafeError(message, "Error", typeof code === "string" ? code : void 0);
6903
9312
  }
6904
9313
  }
6905
9314
  function* __safe_forOf(iterable) {
@@ -7161,12 +9570,15 @@ ${errorMessages}`);
7161
9570
  }
7162
9571
 
7163
9572
  // libs/core/src/realm-airlock.ts
7164
- var ReflectGet5 = Reflect.get;
7165
- var ReflectHas = Reflect.has;
9573
+ var HostFunctionCall = Function.prototype.call;
9574
+ var HostFunctionApply = Function.prototype.apply;
9575
+ var HostFunctionBind = Function.prototype.bind;
9576
+ var ReflectGet6 = Reflect.get;
9577
+ var ReflectHas2 = Reflect.has;
7166
9578
  var ReflectOwnKeys3 = Reflect.ownKeys;
7167
9579
  var ReflectGetOwnPropertyDescriptor2 = Reflect.getOwnPropertyDescriptor;
7168
- var ReflectApply6 = Reflect.apply;
7169
- var ArrayIsArray4 = Array.isArray;
9580
+ var ReflectApply7 = Reflect.apply;
9581
+ var ArrayIsArray5 = Array.isArray;
7170
9582
  var ObjectGetPrototypeOf5 = Object.getPrototypeOf;
7171
9583
  function isReference(value) {
7172
9584
  return value !== null && (typeof value === "object" || typeof value === "function");
@@ -7179,6 +9591,23 @@ function createRealmAirlock(realm) {
7179
9591
  };
7180
9592
  const refusedMethod = realm.wrap(refuseWrite, false);
7181
9593
  const realmObjectPrototype = ObjectGetPrototypeOf5(realm.shell("object"));
9594
+ const realmFunction = realm.shell("function");
9595
+ const realmCounterparts = /* @__PURE__ */ new Map([
9596
+ [HostFunctionCall, ReflectGet6(realmFunction, "call")],
9597
+ [HostFunctionApply, ReflectGet6(realmFunction, "apply")],
9598
+ [
9599
+ HostFunctionBind,
9600
+ realm.wrap(() => {
9601
+ throw createSafeError(
9602
+ "A host function cannot be bound in the sandbox. Call it from a function of your own.",
9603
+ "TypeError"
9604
+ );
9605
+ }, false)
9606
+ ]
9607
+ ]);
9608
+ function isAirlockProxy(value) {
9609
+ return inward.has(value);
9610
+ }
7182
9611
  function isRealmValue(value) {
7183
9612
  if (!isReference(realmObjectPrototype) || inward.has(value)) {
7184
9613
  return false;
@@ -7222,14 +9651,25 @@ function createRealmAirlock(realm) {
7222
9651
  } else if (isSafeError(value)) {
7223
9652
  return value;
7224
9653
  } else if (isRawHostObject(value)) {
7225
- hostProxy = createSecureProxy(value, { exposeToSandbox: toRealm, ownedBySandbox: isRealmValue });
9654
+ hostProxy = createSecureProxy(value, {
9655
+ exposeToSandbox: toRealm,
9656
+ ownedBySandbox: isRealmValue,
9657
+ heldBySandbox: isAirlockProxy
9658
+ });
7226
9659
  } else {
7227
9660
  return value;
7228
9661
  }
7229
9662
  const callable = typeof hostProxy === "function";
7230
- const kind = callable ? "function" : ArrayIsArray4(hostProxy) ? "array" : "object";
9663
+ if (callable) {
9664
+ const counterpart = realmCounterparts.get(unwrapSecureProxy(hostProxy));
9665
+ if (counterpart !== void 0) {
9666
+ outward.set(hostProxy, counterpart);
9667
+ return counterpart;
9668
+ }
9669
+ }
9670
+ const kind = callable ? "function" : ArrayIsArray5(hostProxy) ? "array" : "object";
7231
9671
  const readValue = (key) => {
7232
- const value2 = ReflectGet5(hostProxy, key, hostProxy);
9672
+ const value2 = ReflectGet6(hostProxy, key, hostProxy);
7233
9673
  if (typeof value2 === "function") {
7234
9674
  const method = unwrapSecureProxy(value2);
7235
9675
  if (isMutatingBuiltinMethod(method)) {
@@ -7246,7 +9686,7 @@ function createRealmAirlock(realm) {
7246
9686
  return readValue(key);
7247
9687
  },
7248
9688
  has(_shell, key) {
7249
- return ReflectHas(hostProxy, key);
9689
+ return ReflectHas2(hostProxy, key);
7250
9690
  },
7251
9691
  ownKeys() {
7252
9692
  return ReflectOwnKeys3(hostProxy);
@@ -7278,11 +9718,11 @@ function createRealmAirlock(realm) {
7278
9718
  setPrototypeOf: refuseWrite,
7279
9719
  preventExtensions: refuseWrite,
7280
9720
  apply(_shell, thisArg, args) {
7281
- const hostArgs = [];
9721
+ const passed = [];
7282
9722
  for (let i = 0; i < args.length; i++) {
7283
- hostArgs[i] = toHost(args[i]);
9723
+ passed[i] = args[i];
7284
9724
  }
7285
- return toRealm(ReflectApply6(hostProxy, toHost(thisArg), hostArgs));
9725
+ return toRealm(ReflectApply7(hostProxy, toHost(thisArg), passed));
7286
9726
  },
7287
9727
  construct() {
7288
9728
  throw createSafeError("Host functions cannot be called with new", "TypeError");
@@ -7296,7 +9736,7 @@ function createRealmAirlock(realm) {
7296
9736
  inward.set(proxy, hostProxy);
7297
9737
  return proxy;
7298
9738
  }
7299
- return { toRealm, toHost, isRealmValue };
9739
+ return { toRealm, toHost, isRealmValue, isAirlockProxy };
7300
9740
  }
7301
9741
 
7302
9742
  // libs/core/src/sandbox-console.ts
@@ -7451,6 +9891,7 @@ var STACK_TRACE_HARDENING_CODE = `
7451
9891
  })();
7452
9892
  `.trim();
7453
9893
  var STACK_TRACE_HARDENING_SCRIPT = new ReusableSandboxScript(STACK_TRACE_HARDENING_CODE);
9894
+ var STACK_CAPTURE_OFF_SCRIPT = new ReusableSandboxScript(STACK_CAPTURE_OFF_SOURCE, { filename: "realm-stack.js" });
7454
9895
  var CODE_GENERATION_VIOLATION_DETECTOR_CODE = `
7455
9896
  (function() {
7456
9897
  var __ag_report = (typeof __ag_reportViolation__ === 'function') ? __ag_reportViolation__ : null;
@@ -7516,6 +9957,15 @@ var INTRINSIC_OBJECT_NEUTRALIZATION_CODE = `
7516
9957
  })();
7517
9958
  `;
7518
9959
  var INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new ReusableSandboxScript(INTRINSIC_OBJECT_NEUTRALIZATION_CODE);
9960
+ var CLOSE_OBJECT_PROTOTYPE_SCRIPT = new ReusableSandboxScript(
9961
+ `(function () {
9962
+ 'use strict';
9963
+ var root = Object.getPrototypeOf({});
9964
+ Object.preventExtensions(root);
9965
+ if (Object.isExtensible(root)) throw new TypeError('The prototype of plain objects could not be closed');
9966
+ })()`,
9967
+ { filename: "close-object-prototype.js" }
9968
+ );
7519
9969
  var DETACH_GLOBAL_PROTOTYPE_SCRIPT = new ReusableSandboxScript(
7520
9970
  `(function (global) {
7521
9971
  'use strict';
@@ -7957,10 +10407,12 @@ var VmAdapter = class {
7957
10407
  // Object tracking has higher overhead, skip for now
7958
10408
  }) : void 0;
7959
10409
  memoryTracker?.start();
10410
+ let endDeadlineChecks;
7960
10411
  try {
7961
10412
  const baseSandbox = vm3.createContext(/* @__PURE__ */ Object.create(null), {
7962
10413
  codeGeneration: { strings: false, wasm: false }
7963
10414
  });
10415
+ STACK_CAPTURE_OFF_SCRIPT.runInContext(baseSandbox);
7964
10416
  const realmMembrane = REALM_GUARD_SCRIPT.runInContext(baseSandbox);
7965
10417
  const airlock = createRealmAirlock(realmMembrane);
7966
10418
  REALM_SYMBOL_REGISTRY_SCRIPT.runInContext(baseSandbox);
@@ -7998,11 +10450,18 @@ var VmAdapter = class {
7998
10450
  enumerable: true
7999
10451
  });
8000
10452
  }
8001
- compileSandboxScript(realmTickSource(config.timeout), { filename: "deadline.js" }).runInContext(baseSandbox);
10453
+ endDeadlineChecks = compileSandboxScript(realmTickSource(config.timeout), {
10454
+ filename: "deadline.js"
10455
+ }).runInContext(baseSandbox);
8002
10456
  const installToolNamespaces = executionContext.toolNamespaces?.length ? TOOL_NAMESPACE_FACTORY_SCRIPT.runInContext(baseSandbox) : void 0;
8003
10457
  const handlerConsole = executionContext.consoleHandler ? createHandlerConsole(baseSandbox, realmMembrane, executionContext.consoleHandler, config) : void 0;
8004
10458
  const installConsole = handlerConsole ? void 0 : SANDBOX_CONSOLE_FACTORY_SCRIPT.runInContext(baseSandbox);
8005
- const globalFunctionGate = createGlobalFunctionGate(executionContext, realmBridge, unwrapHostValue);
10459
+ const globalFunctionGate = createGlobalFunctionGate(
10460
+ executionContext,
10461
+ realmBridge,
10462
+ unwrapHostValue,
10463
+ airlock.isRealmValue
10464
+ );
8006
10465
  const safeRuntime = createSafeRuntime(executionContext, {
8007
10466
  sidecar: executionContext.sidecar,
8008
10467
  referenceConfig: executionContext.referenceConfig,
@@ -8012,6 +10471,7 @@ var VmAdapter = class {
8012
10471
  globalFunctionGate,
8013
10472
  exposeToSandbox: airlock.toRealm,
8014
10473
  ownedBySandbox: airlock.isRealmValue,
10474
+ heldBySandbox: airlock.isAirlockProxy,
8015
10475
  hostObjects: false
8016
10476
  });
8017
10477
  if (memoryTracker && config.memoryLimit && config.memoryLimit > 0) {
@@ -8039,7 +10499,10 @@ var VmAdapter = class {
8039
10499
  // "this". In sloppy mode "this" was coerced to the realm's global object, and fill
8040
10500
  // RETURNED it.
8041
10501
  'use strict';
8042
- var memoryLimit = ${config.memoryLimit};
10502
+ // The functions of Math, not the object: a script can assign to its members, and a
10503
+ // replaced Math.max would decide what a fill is charged.
10504
+ var Math = (function (M) { return { max: M.max, min: M.min, round: M.round }; })(globalThis.Math);
10505
+ var memoryLimit = ${numericLiteral("memoryLimit", config.memoryLimit)};
8043
10506
  var trackMemory = __host_memory_track__;
8044
10507
 
8045
10508
  // A size is only usable when it is a positive number. NaN (a missing or non-numeric
@@ -8123,29 +10586,8 @@ var VmAdapter = class {
8123
10586
  return chargeActual(originalPadEnd.call(this, targetLength, padString), estimatedSize, 'String.padEnd');
8124
10587
  };
8125
10588
 
8126
- // Patch array fill - converts sparse arrays to dense (allocates memory)
8127
- // Vector 1110/1170: Array(dynamicSize).fill() can exhaust memory
8128
- // Estimate: each element uses ~8 bytes (pointer) for objects/primitives
8129
- var originalFill = arrayProto.fill;
8130
- arrayProto.fill = function(value, start, end) {
8131
- // Calculate actual fill range
8132
- var len = this.length >>> 0;
8133
- var relativeStart = start === undefined ? 0 : (start >> 0);
8134
- var relativeEnd = end === undefined ? len : (end >> 0);
8135
- var k = relativeStart < 0 ? Math.max(len + relativeStart, 0) : Math.min(relativeStart, len);
8136
- var finalEnd = relativeEnd < 0 ? Math.max(len + relativeEnd, 0) : Math.min(relativeEnd, len);
8137
- var fillCount = Math.max(0, finalEnd - k);
8138
-
8139
- // Estimate memory: 8 bytes per element (pointer size)
8140
- var estimatedSize = fillCount * 8;
8141
- if (estimatedSize > memoryLimit) {
8142
- throw new RangeError('Array.fill would exceed memory limit: ' +
8143
- Math.round(estimatedSize / 1024 / 1024) + 'MB > ' +
8144
- Math.round(memoryLimit / 1024 / 1024) + 'MB');
8145
- }
8146
- trackMemory(estimatedSize);
8147
- return originalFill.call(this, value, start, end);
8148
- };
10589
+ // Array.prototype.fill is accounted for with the other array operations (see
10590
+ // ../realm-memory), where its range is worked out by the built-in's own rules.
8149
10591
 
8150
10592
  // Array.from and Array.of build an array of any size in one call: charged for what
8151
10593
  // they built (8 bytes per element), on the realm's own Array, so that the constructor
@@ -8168,6 +10610,12 @@ var VmAdapter = class {
8168
10610
  `);
8169
10611
  patchScript.runInContext(baseSandbox);
8170
10612
  }
10613
+ compileSandboxScript(
10614
+ realmArrayAccountingSource(
10615
+ memoryTracker && config.memoryLimit && config.memoryLimit > 0 ? config.memoryLimit : 0
10616
+ ),
10617
+ { filename: "array-accounting.js" }
10618
+ ).runInContext(baseSandbox);
8171
10619
  const shouldHardenStacks = config.sanitizeStackTraces ?? true;
8172
10620
  const blockedProperties = executionContext.secureProxyConfig ? buildBlockedPropertiesFromConfig(executionContext.secureProxyConfig) : getBlockedPropertiesForLevel(this.securityLevel);
8173
10621
  compileSandboxScript(
@@ -8208,16 +10656,6 @@ var VmAdapter = class {
8208
10656
  } catch {
8209
10657
  }
8210
10658
  }
8211
- if (this.securityLevel !== "STRICT") {
8212
- Object.defineProperty(baseSandbox, "Reflect", {
8213
- value: realmRuntime.createSafeReflect(
8214
- this.securityLevel === "SECURE" ? "setPrototypeOf,apply,defineProperty" : "setPrototypeOf"
8215
- ),
8216
- writable: false,
8217
- configurable: false,
8218
- enumerable: true
8219
- });
8220
- }
8221
10659
  if (config.toolBridge?.mode === "string") {
8222
10660
  const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
8223
10661
  const hostToolBridge = createHostToolBridge(executionContext, { updateStats: false, limitChecked: true });
@@ -8266,7 +10704,11 @@ var VmAdapter = class {
8266
10704
  var promiseThen = Promise.prototype.then;
8267
10705
  var settled = Promise.resolve();
8268
10706
  var reflectApply = Reflect.apply;
8269
- var maxBytes = ${maxPayloadBytes};
10707
+ var isArray = Array.isArray;
10708
+ var StringOf = String;
10709
+ var stringValueOf = String.prototype.valueOf;
10710
+ var numberValueOf = Number.prototype.valueOf;
10711
+ var maxBytes = ${numericLiteral("toolBridge.maxPayloadBytes", maxPayloadBytes)};
8270
10712
  var limitMessage = ${JSON.stringify(limitMessage)};
8271
10713
 
8272
10714
  // Tool calls whose host bridge has not been started yet.
@@ -8334,6 +10776,56 @@ var VmAdapter = class {
8334
10776
  return err;
8335
10777
  }
8336
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
+
8337
10829
  return async function __safe_callTool(toolName, args, options) {
8338
10830
  // callTool options: only { throwOnError: false } changes behavior. Tool failures
8339
10831
  // then resolve to { success: false, error }; the enclave's own refusals still throw.
@@ -8354,11 +10846,23 @@ var VmAdapter = class {
8354
10846
  throw makeError('Tool bridge is not available', 'Error');
8355
10847
  }
8356
10848
 
8357
- // 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.
8358
10859
  var sanitizedArgs;
8359
10860
  try {
8360
- sanitizedArgs = parse(stringify(args));
10861
+ sanitizedArgs = parse(stringifyWithin(args, maxBytes));
8361
10862
  } catch (e) {
10863
+ if (e === TOO_LARGE) {
10864
+ throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
10865
+ }
8362
10866
  throw makeError('Tool arguments must be JSON-serializable', 'TypeError');
8363
10867
  }
8364
10868
 
@@ -8373,11 +10877,6 @@ var VmAdapter = class {
8373
10877
  throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
8374
10878
  }
8375
10879
 
8376
- // Counted here, where the call is made: the first maxToolCalls calls are the ones
8377
- // that run, also when several are made before any of them is started.
8378
- if (countCall() !== true) {
8379
- throw makeError(limitMessage, 'ToolLimitError');
8380
- }
8381
10880
  var responseJson = await callBridge(requestJson);
8382
10881
  if (typeof responseJson !== 'string') {
8383
10882
  throw makeError('Tool bridge returned invalid response', 'Error');
@@ -8433,12 +10932,14 @@ var VmAdapter = class {
8433
10932
  };
8434
10933
  })()
8435
10934
  `);
8436
- const vmSafeCallTool = bridgeInitScript.runInContext(baseSandbox);
8437
- const proxiedVmSafeCallTool = createSecureProxy(vmSafeCallTool, {
8438
- levelConfig: executionContext.secureProxyConfig
8439
- });
10935
+ const realmCallTool = realmMembrane.wrap(
10936
+ bridgeInitScript.runInContext(baseSandbox),
10937
+ true
10938
+ );
10939
+ Object.defineProperty(realmCallTool, "name", { value: "__safe_callTool", configurable: true });
10940
+ Object.defineProperty(realmCallTool, "length", { value: 3, configurable: true });
8440
10941
  Object.defineProperty(baseSandbox, "__safe_callTool", {
8441
- value: airlock.toRealm(proxiedVmSafeCallTool),
10942
+ value: Object.freeze(realmCallTool),
8442
10943
  writable: false,
8443
10944
  configurable: false,
8444
10945
  enumerable: true
@@ -8448,6 +10949,16 @@ var VmAdapter = class {
8448
10949
  } catch {
8449
10950
  }
8450
10951
  }
10952
+ if (this.securityLevel !== "STRICT") {
10953
+ Object.defineProperty(baseSandbox, "Reflect", {
10954
+ value: realmRuntime.createSafeReflect(
10955
+ this.securityLevel === "SECURE" ? "setPrototypeOf,apply,defineProperty" : "setPrototypeOf"
10956
+ ),
10957
+ writable: false,
10958
+ configurable: false,
10959
+ enumerable: true
10960
+ });
10961
+ }
8451
10962
  for (const [key, value2] of Object.entries(safeRuntime)) {
8452
10963
  if (key in baseSandbox) continue;
8453
10964
  Object.defineProperty(baseSandbox, key, {
@@ -8464,7 +10975,8 @@ var VmAdapter = class {
8464
10975
  levelConfig: executionContext.secureProxyConfig,
8465
10976
  callGate: globalFunctionGate,
8466
10977
  exposeToSandbox: airlock.toRealm,
8467
- ownedBySandbox: airlock.isRealmValue
10978
+ ownedBySandbox: airlock.isRealmValue,
10979
+ heldBySandbox: airlock.isAirlockProxy
8468
10980
  })
8469
10981
  ) : value2;
8470
10982
  for (const name of [key, `__safe_${key}`]) {
@@ -8518,10 +11030,17 @@ var VmAdapter = class {
8518
11030
  enumerable: false
8519
11031
  });
8520
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
+ }
8521
11039
  try {
8522
11040
  INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT.runInContext(baseSandbox);
8523
11041
  } catch {
8524
11042
  }
11043
+ CLOSE_OBJECT_PROTOTYPE_SCRIPT.runInContext(baseSandbox);
8525
11044
  detachGlobalPrototype();
8526
11045
  Object.defineProperty(baseSandbox, "Object", {
8527
11046
  value: realmRuntime.createSafeObject(),
@@ -8576,8 +11095,8 @@ var VmAdapter = class {
8576
11095
  }
8577
11096
  const depthDefaulted = config.maxSanitizeDepth ?? 20;
8578
11097
  const propsDefaulted = config.maxSanitizeProperties ?? 100;
8579
- const clampedDepth = Math.max(5, Math.min(50, depthDefaulted));
8580
- const clampedProperties = Math.max(50, Math.min(1e3, propsDefaulted));
11098
+ const clampedDepth = Math.min(50, depthDefaulted);
11099
+ const clampedProperties = Math.min(1e3, propsDefaulted);
8581
11100
  const sanitizedValue = sanitizeValue(value, {
8582
11101
  maxDepth: clampedDepth,
8583
11102
  maxProperties: clampedProperties,
@@ -8592,25 +11111,25 @@ var VmAdapter = class {
8592
11111
  stats
8593
11112
  };
8594
11113
  } catch (error) {
8595
- const err = error;
11114
+ const thrown = describeThrown(error);
8596
11115
  stats.duration = Date.now() - startTime;
8597
11116
  stats.endTime = Date.now();
8598
11117
  if (memoryTracker) {
8599
11118
  const memSnapshot = memoryTracker.getSnapshot();
8600
11119
  stats.memoryUsage = memSnapshot.peakTrackedBytes;
8601
11120
  }
8602
- const isMemoryLimit = err instanceof MemoryLimitError || typeof err === "object" && err !== null && err.code === "MEMORY_LIMIT_EXCEEDED";
11121
+ const isMemoryLimit = error instanceof MemoryLimitError || memoryTracker?.hasExceededLimit() === true && isMemoryLimitPayload(error);
8603
11122
  if (isMemoryLimit) {
8604
11123
  const snapshot = memoryTracker?.getSnapshot();
8605
11124
  return {
8606
11125
  success: false,
8607
11126
  error: {
8608
11127
  name: "MemoryLimitError",
8609
- message: typeof err.message === "string" ? err.message : "Memory limit exceeded",
11128
+ message: thrown.message ?? "Memory limit exceeded",
8610
11129
  code: "MEMORY_LIMIT_EXCEEDED",
8611
11130
  data: {
8612
- usedBytes: err instanceof MemoryLimitError ? err.usedBytes : snapshot?.trackedBytes ?? 0,
8613
- limitBytes: err instanceof MemoryLimitError ? err.limitBytes : config.memoryLimit ?? 0
11131
+ usedBytes: error instanceof MemoryLimitError ? error.usedBytes : snapshot?.trackedBytes ?? 0,
11132
+ limitBytes: error instanceof MemoryLimitError ? error.limitBytes : config.memoryLimit ?? 0
8614
11133
  }
8615
11134
  },
8616
11135
  stats
@@ -8621,7 +11140,7 @@ var VmAdapter = class {
8621
11140
  success: false,
8622
11141
  error: {
8623
11142
  name: "VMExecutionError",
8624
- message: error,
11143
+ message: thrown.message ?? "",
8625
11144
  code: "VM_EXECUTION_ERROR"
8626
11145
  },
8627
11146
  stats
@@ -8631,13 +11150,18 @@ var VmAdapter = class {
8631
11150
  return {
8632
11151
  success: false,
8633
11152
  error: {
8634
- name: err.name || "VMExecutionError",
8635
- message: err.message || "Unknown VM execution error",
8636
- stack: sanitizeStackTrace(err.stack, shouldSanitize),
11153
+ name: thrown.name || "VMExecutionError",
11154
+ message: thrown.message || THROWN_WITHOUT_MESSAGE,
11155
+ stack: sanitizeStackTrace(thrown.stack, shouldSanitize),
8637
11156
  code: "VM_EXECUTION_ERROR"
8638
11157
  },
8639
11158
  stats
8640
11159
  };
11160
+ } finally {
11161
+ try {
11162
+ endDeadlineChecks?.();
11163
+ } catch {
11164
+ }
8641
11165
  }
8642
11166
  }
8643
11167
  /**
@@ -8648,188 +11172,12 @@ var VmAdapter = class {
8648
11172
  }
8649
11173
  };
8650
11174
 
8651
- // libs/core/src/types.ts
8652
- var SECURITY_LEVEL_CONFIGS = {
8653
- /**
8654
- * STRICT: Maximum security for untrusted code
8655
- *
8656
- * Use for:
8657
- * - AI-generated code from external sources
8658
- * - User-submitted scripts
8659
- * - Untrusted third-party integrations
8660
- *
8661
- * Characteristics:
8662
- * - Short timeout (5s)
8663
- * - Low iteration limits (1000)
8664
- * - Limited tool calls (10)
8665
- * - Deep value sanitization
8666
- * - Full stack trace sanitization
8667
- * - Timing API blocking
8668
- * - No unbounded loops
8669
- * - Unicode security checks
8670
- */
8671
- STRICT: {
8672
- timeout: 5e3,
8673
- maxIterations: 1e3,
8674
- maxToolCalls: 10,
8675
- maxSanitizeDepth: 5,
8676
- maxSanitizeProperties: 50,
8677
- sanitizeStackTraces: true,
8678
- blockTimingAPIs: true,
8679
- allowUnboundedLoops: false,
8680
- unicodeSecurityCheck: true,
8681
- allowFunctionsInGlobals: false,
8682
- maxConsoleOutputBytes: 64 * 1024,
8683
- // 64KB - prevent I/O flood attacks
8684
- maxConsoleCalls: 100,
8685
- secureProxy: {
8686
- blockConstructor: true,
8687
- blockPrototype: true,
8688
- blockLegacyAccessors: true,
8689
- proxyMaxDepth: 5,
8690
- throwOnBlocked: true
8691
- }
8692
- },
8693
- /**
8694
- * SECURE: High security with more headroom
8695
- *
8696
- * Use for:
8697
- * - AI-generated code from trusted models
8698
- * - Internal automation scripts
8699
- * - Controlled multi-tenant environments
8700
- *
8701
- * Characteristics:
8702
- * - Moderate timeout (15s)
8703
- * - Moderate iteration limits (5000)
8704
- * - Moderate tool calls (50)
8705
- * - Standard value sanitization
8706
- * - Stack trace sanitization
8707
- * - No timing API blocking
8708
- * - No unbounded loops
8709
- */
8710
- SECURE: {
8711
- timeout: 15e3,
8712
- maxIterations: 5e3,
8713
- maxToolCalls: 50,
8714
- maxSanitizeDepth: 10,
8715
- maxSanitizeProperties: 100,
8716
- sanitizeStackTraces: true,
8717
- blockTimingAPIs: false,
8718
- allowUnboundedLoops: false,
8719
- unicodeSecurityCheck: true,
8720
- allowFunctionsInGlobals: false,
8721
- maxConsoleOutputBytes: 256 * 1024,
8722
- // 256KB
8723
- maxConsoleCalls: 500,
8724
- secureProxy: {
8725
- blockConstructor: true,
8726
- blockPrototype: true,
8727
- blockLegacyAccessors: true,
8728
- proxyMaxDepth: 10,
8729
- throwOnBlocked: true
8730
- }
8731
- },
8732
- /**
8733
- * STANDARD: Balanced security and functionality (DEFAULT)
8734
- *
8735
- * Use for:
8736
- * - Internal tools and scripts
8737
- * - Development and testing
8738
- * - Trusted environments
8739
- *
8740
- * Characteristics:
8741
- * - Standard timeout (30s)
8742
- * - Standard iteration limits (10000)
8743
- * - Standard tool calls (100)
8744
- * - Basic value sanitization
8745
- * - Minimal stack trace sanitization
8746
- * - Unbounded loops allowed
8747
- */
8748
- STANDARD: {
8749
- timeout: 3e4,
8750
- maxIterations: 1e4,
8751
- maxToolCalls: 100,
8752
- maxSanitizeDepth: 20,
8753
- maxSanitizeProperties: 500,
8754
- sanitizeStackTraces: false,
8755
- blockTimingAPIs: false,
8756
- allowUnboundedLoops: true,
8757
- unicodeSecurityCheck: false,
8758
- allowFunctionsInGlobals: false,
8759
- maxConsoleOutputBytes: 1024 * 1024,
8760
- // 1MB
8761
- maxConsoleCalls: 1e3,
8762
- secureProxy: {
8763
- blockConstructor: true,
8764
- blockPrototype: true,
8765
- blockLegacyAccessors: true,
8766
- proxyMaxDepth: 15,
8767
- throwOnBlocked: true
8768
- }
8769
- },
8770
- /**
8771
- * PERMISSIVE: Minimal restrictions
8772
- *
8773
- * Use for:
8774
- * - Local development only
8775
- * - Debugging
8776
- * - Performance testing
8777
- *
8778
- * WARNING: Not recommended for production use with untrusted code
8779
- *
8780
- * Characteristics:
8781
- * - Long timeout (60s)
8782
- * - High iteration limits (100000)
8783
- * - High tool calls (1000)
8784
- * - Minimal sanitization
8785
- * - No stack trace sanitization
8786
- * - All features enabled
8787
- */
8788
- PERMISSIVE: {
8789
- timeout: 6e4,
8790
- maxIterations: 1e5,
8791
- maxToolCalls: 1e3,
8792
- maxSanitizeDepth: 50,
8793
- maxSanitizeProperties: 1e3,
8794
- sanitizeStackTraces: false,
8795
- blockTimingAPIs: false,
8796
- allowUnboundedLoops: true,
8797
- unicodeSecurityCheck: false,
8798
- allowFunctionsInGlobals: true,
8799
- maxConsoleOutputBytes: 10 * 1024 * 1024,
8800
- // 10MB
8801
- maxConsoleCalls: 1e4,
8802
- secureProxy: {
8803
- blockConstructor: false,
8804
- // Allow constructor access for development/debugging
8805
- blockPrototype: true,
8806
- // Still block prototype for safety
8807
- blockLegacyAccessors: true,
8808
- proxyMaxDepth: 20,
8809
- throwOnBlocked: false
8810
- // Return undefined instead of throwing for development
8811
- }
8812
- }
8813
- };
8814
- var DEFAULT_DOUBLE_VM_CONFIG = {
8815
- enabled: true,
8816
- parentTimeoutBuffer: 1e3,
8817
- parentValidation: {
8818
- validateOperationNames: true,
8819
- maxOperationsPerSecond: 100,
8820
- blockSuspiciousSequences: true,
8821
- rapidEnumerationThreshold: 30,
8822
- rapidEnumerationOverrides: {},
8823
- suspiciousPatterns: []
8824
- // Default patterns added at runtime
8825
- }
8826
- };
8827
-
8828
11175
  // libs/core/src/adapters/worker-pool/worker-script.ts
8829
11176
  var port = import_worker_threads.parentPort;
8830
11177
  if (!port) {
8831
11178
  throw new Error("worker-script.ts must run inside a worker thread");
8832
11179
  }
11180
+ var nextEventLoopTurn = setImmediate;
8833
11181
  var DANGEROUS_GLOBALS = [
8834
11182
  "parentPort",
8835
11183
  "workerData",
@@ -8909,6 +11257,16 @@ port.on("message", async (raw) => {
8909
11257
  });
8910
11258
  async function handleExecute(msg) {
8911
11259
  const startTime = Date.now();
11260
+ if (currentExecution) {
11261
+ sendMessage({
11262
+ type: "result",
11263
+ requestId: msg.requestId,
11264
+ success: false,
11265
+ error: { name: "WorkerBusyError", message: "The worker is still running another execution" },
11266
+ stats: resultStats({ duration: 0, toolCallCount: 0, iterationCount: 0, startTime, endTime: startTime })
11267
+ });
11268
+ return;
11269
+ }
8912
11270
  const config = msg.config;
8913
11271
  const stats = {
8914
11272
  duration: 0,
@@ -8944,7 +11302,10 @@ async function handleExecute(msg) {
8944
11302
  execution.aborted = value;
8945
11303
  },
8946
11304
  hostToolBridge: (requestJson) => relayToolRequest(execution, requestJson),
8947
- consoleHandler: config.hasConsoleHandler ? (level, text) => sendMessage({ type: "console", requestId: execution.id, level, args: [text] }) : void 0,
11305
+ consoleHandler: config.hasConsoleHandler ? (level, text) => {
11306
+ if (currentExecution !== execution) return;
11307
+ sendMessage({ type: "console", requestId: execution.id, level, args: [text] });
11308
+ } : void 0,
8948
11309
  secureProxyConfig: config.secureProxyConfig,
8949
11310
  toolNamespaces: config.toolNamespaces,
8950
11311
  realmGlobalAllowlist: config.realmGlobalAllowlist,
@@ -9001,8 +11362,17 @@ async function handleExecute(msg) {
9001
11362
  if (currentExecution === execution) {
9002
11363
  currentExecution = null;
9003
11364
  }
11365
+ confirmIdle(msg.requestId);
9004
11366
  }
9005
11367
  }
11368
+ function confirmIdle(requestId) {
11369
+ nextEventLoopTurn(() => {
11370
+ try {
11371
+ sendMessage({ type: "idle", requestId });
11372
+ } catch {
11373
+ }
11374
+ });
11375
+ }
9006
11376
  function createSandboxAdapter(config) {
9007
11377
  const doubleVm = config.doubleVm;
9008
11378
  if (doubleVm && doubleVm.enabled === false) {