@enclave-vm/core 2.19.0 → 2.19.2

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 (48) hide show
  1. package/README.md +262 -105
  2. package/adapters/interpreter-adapter.d.ts +10 -1
  3. package/adapters/worker-pool/config.d.ts +15 -5
  4. package/adapters/worker-pool/protocol.d.ts +27 -1
  5. package/adapters/worker-pool/worker-pool-adapter.d.ts +24 -0
  6. package/adapters/worker-pool/worker-slot.d.ts +35 -6
  7. package/async-context.d.ts +34 -0
  8. package/babel/babel-wrapper.d.ts +21 -12
  9. package/babel/multi-file-transform.d.ts +3 -0
  10. package/babel/text-scan.d.ts +54 -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 +31 -7
  15. package/esm/index.mjs +4796 -852
  16. package/esm/worker.mjs +1236 -165
  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 +4836 -892
  21. package/interpreter/interpreter.d.ts +247 -8
  22. package/memory-tracker.d.ts +7 -0
  23. package/package.json +3 -3
  24. package/realm-airlock.d.ts +6 -1
  25. package/realm-memory.d.ts +89 -0
  26. package/realm-stack.d.ts +25 -0
  27. package/safe-runtime.d.ts +2 -0
  28. package/sandbox-rejections.d.ts +3 -1
  29. package/scoring/feature-extractor.d.ts +52 -1
  30. package/scoring/index.d.ts +2 -1
  31. package/scoring/scorers/index.d.ts +2 -1
  32. package/scoring/scorers/local-llm.scorer.d.ts +9 -3
  33. package/scoring/scorers/progressive.scorer.d.ts +28 -1
  34. package/scoring/scorers/rule-based.scorer.d.ts +11 -1
  35. package/scoring/types.d.ts +36 -8
  36. package/secure-proxy.d.ts +17 -3
  37. package/session/session.d.ts +8 -1
  38. package/session-types.d.ts +6 -4
  39. package/sidecar/index.d.ts +1 -1
  40. package/sidecar/reference-config.d.ts +18 -1
  41. package/sidecar/reference-resolver.d.ts +19 -1
  42. package/sidecar/reference-sidecar.d.ts +37 -0
  43. package/src/adapters/worker-pool/package.json +3 -3
  44. package/src/adapters/worker-pool/worker-script.js +2250 -428
  45. package/thrown-value.d.ts +59 -0
  46. package/types.d.ts +75 -19
  47. package/value-sanitizer.d.ts +6 -1
  48. package/worker.js +1236 -165
@@ -240,8 +240,6 @@ function isPlainObject(value) {
240
240
  function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
241
241
  const maxDepth = options.maxDepth ?? 20;
242
242
  const maxProperties = options.maxProperties ?? 1e4;
243
- const allowDates = options.allowDates ?? true;
244
- const allowErrors = options.allowErrors ?? true;
245
243
  if (depth > maxDepth) {
246
244
  throw new Error(
247
245
  `Tool handler return value exceeds maximum depth (${maxDepth}). This limit prevents deeply nested objects that could cause stack overflow.`
@@ -277,7 +275,19 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
277
275
  return "[Circular]";
278
276
  }
279
277
  context.visited.add(value);
278
+ try {
279
+ return sanitizeObjectValue(value, options, depth, context);
280
+ } finally {
281
+ context.visited.delete(value);
282
+ }
280
283
  }
284
+ return String(value);
285
+ }
286
+ function sanitizeObjectValue(value, options, depth, context) {
287
+ const maxProperties = options.maxProperties ?? 1e4;
288
+ const allowDates = options.allowDates ?? true;
289
+ const allowErrors = options.allowErrors ?? true;
290
+ const type = typeof value;
281
291
  if (ArrayIsArray2(value)) {
282
292
  const rawLen = ReflectGet2(value, "length");
283
293
  const len = typeof rawLen === "number" && NumberIsFinite2(rawLen) && rawLen >= 0 ? MathFloor2(rawLen) : 0;
@@ -687,21 +697,29 @@ var BUILTIN_PROTOTYPES = (() => {
687
697
  return prototypes.filter((prototype) => prototype !== null && typeof prototype === "object");
688
698
  })();
689
699
  var BUILTIN_PROTOTYPE_SET = new WeakSet(BUILTIN_PROTOTYPES);
690
- var BUILTIN_METHODS = (() => {
691
- const methods = /* @__PURE__ */ new WeakSet();
700
+ var BUILTIN_METHOD_HOMES = (() => {
701
+ const homes = /* @__PURE__ */ new WeakMap();
692
702
  for (const prototype of BUILTIN_PROTOTYPES) {
693
703
  for (const key of ReflectOwnKeys(prototype)) {
694
704
  if (key === "constructor") continue;
695
705
  const descriptor = ObjectGetOwnPropertyDescriptor(prototype, key);
696
706
  if (descriptor && typeof descriptor.value === "function") {
697
- methods.add(descriptor.value);
707
+ const known = homes.get(descriptor.value);
708
+ if (!known) {
709
+ homes.set(descriptor.value, [prototype]);
710
+ } else if (!known.includes(prototype)) {
711
+ known.push(prototype);
712
+ }
698
713
  }
699
714
  }
700
715
  }
701
- return methods;
716
+ return homes;
702
717
  })();
703
718
  function isBuiltinMethod(fn) {
704
- return (typeof fn === "function" || typeof fn === "object" && fn !== null) && BUILTIN_METHODS.has(fn);
719
+ return (typeof fn === "function" || typeof fn === "object" && fn !== null) && BUILTIN_METHOD_HOMES.has(fn);
720
+ }
721
+ function builtinMethodHomes(fn) {
722
+ return typeof fn === "function" || typeof fn === "object" && fn !== null ? BUILTIN_METHOD_HOMES.get(fn) : void 0;
705
723
  }
706
724
  var MUTATING_BUILTIN_METHODS = (() => {
707
725
  const methods = /* @__PURE__ */ new WeakSet();
@@ -747,6 +765,46 @@ var REGEXP_MATCH_METHODS = (() => {
747
765
  function isRegExpMatchMethod(fn) {
748
766
  return (typeof fn === "function" || typeof fn === "object" && fn !== null) && REGEXP_MATCH_METHODS.has(fn);
749
767
  }
768
+ var FunctionPrototypeToString = Function.prototype.toString;
769
+ var ObjectPrototypeToLocaleString = Object.prototype.toLocaleString;
770
+ function isFunctionTextMethod(fn) {
771
+ return fn === FunctionPrototypeToString || fn === ObjectPrototypeToLocaleString;
772
+ }
773
+ var MAX_FUNCTION_NAME_LENGTH = 64;
774
+ function isPlainIdentifier(name) {
775
+ if (name.length === 0 || name.length > MAX_FUNCTION_NAME_LENGTH) return false;
776
+ for (let i = 0; i < name.length; i++) {
777
+ const c = name.charCodeAt(i);
778
+ const letter = c >= 65 && c <= 90 || c >= 97 && c <= 122 || c === 95 || c === 36;
779
+ const digit = c >= 48 && c <= 57;
780
+ if (!letter && !(digit && i > 0)) return false;
781
+ }
782
+ return true;
783
+ }
784
+ function hostFunctionText(fn) {
785
+ let name = "";
786
+ try {
787
+ if (typeof fn === "function") {
788
+ const descriptor = ObjectGetOwnPropertyDescriptor(fn, "name");
789
+ const value = descriptor && "value" in descriptor ? descriptor.value : void 0;
790
+ if (typeof value === "string" && isPlainIdentifier(value)) {
791
+ name = value;
792
+ }
793
+ }
794
+ } catch {
795
+ }
796
+ return `function ${name}() { [native code] }`;
797
+ }
798
+ function withoutFunctionSource(text, fn) {
799
+ if (typeof fn !== "function") return text;
800
+ let source;
801
+ try {
802
+ source = ReflectApply3(FunctionPrototypeToString, fn, []);
803
+ } catch {
804
+ return text;
805
+ }
806
+ return source.length > 0 && text.includes(source) ? text.split(source).join(hostFunctionText(fn)) : text;
807
+ }
750
808
  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
809
  var DEFAULT_GLOBAL_FUNCTION_CALLS_PER_TOOL_CALL = 10;
752
810
  var DEFAULT_MAX_PAYLOAD_BYTES = 5 * 1024 * 1024;
@@ -776,7 +834,7 @@ function resultLimits(context) {
776
834
  function truncate(value, max) {
777
835
  return value.length <= max ? value : `${value.slice(0, max)}\u2026`;
778
836
  }
779
- function failure(error) {
837
+ function failure(error, receiver) {
780
838
  let name = "Error";
781
839
  let message = "Global function call failed";
782
840
  try {
@@ -792,8 +850,8 @@ function failure(error) {
792
850
  }
793
851
  return {
794
852
  ok: false,
795
- name: truncate(name, MAX_ERROR_NAME_LENGTH),
796
- message: truncate(message, MAX_ERROR_MESSAGE_LENGTH)
853
+ name: truncate(withoutFunctionSource(name, receiver), MAX_ERROR_NAME_LENGTH),
854
+ message: truncate(withoutFunctionSource(message, receiver), MAX_ERROR_MESSAGE_LENGTH)
797
855
  };
798
856
  }
799
857
  function jsonReplacer(_key, value) {
@@ -867,9 +925,9 @@ function invokeGlobalFunction(fn, thisArg, args, limits, unwrap, activity) {
867
925
  }
868
926
  let result;
869
927
  try {
870
- result = ReflectApply3(fn, thisArg, safeArgs);
928
+ result = activity?.inHostContext ? activity.inHostContext(() => ReflectApply3(fn, thisArg, safeArgs)) : ReflectApply3(fn, thisArg, safeArgs);
871
929
  } catch (error) {
872
- return failure(error);
930
+ return failure(error, thisArg);
873
931
  }
874
932
  if (isThenable(result)) {
875
933
  const end = activity?.begin();
@@ -880,7 +938,7 @@ function invokeGlobalFunction(fn, thisArg, args, limits, unwrap, activity) {
880
938
  },
881
939
  (error) => {
882
940
  end?.();
883
- return failure(error);
941
+ return failure(error, thisArg);
884
942
  }
885
943
  );
886
944
  }
@@ -899,7 +957,7 @@ function createHostGlobalFunctionInvoker(context) {
899
957
  return outcome instanceof Promise ? outcome.then(toEnvelope) : toEnvelope(outcome);
900
958
  };
901
959
  }
902
- function createGlobalFunctionGate(context, realm, unwrap) {
960
+ function createGlobalFunctionGate(context, realm, unwrap, ownedBySandbox) {
903
961
  const limits = resultLimits(context);
904
962
  const max = resolveMaxGlobalFunctionCalls(context.config);
905
963
  let calls = 0;
@@ -910,7 +968,7 @@ function createGlobalFunctionGate(context, realm, unwrap) {
910
968
  return outcome.json === void 0 ? void 0 : realm.parseJson(outcome.json);
911
969
  };
912
970
  return {
913
- gates: (target) => !isBuiltinMethod(target),
971
+ gates: (target) => !isBuiltinMethod(target) && !(ownedBySandbox !== void 0 && typeof target === "function" && ownedBySandbox(target)),
914
972
  call: (target, thisArg, args) => {
915
973
  if (context.aborted) {
916
974
  throw createSafeError("Execution aborted");
@@ -938,6 +996,7 @@ var ReflectDefineProperty = Reflect.defineProperty;
938
996
  var ReflectGetOwnPropertyDescriptor = Reflect.getOwnPropertyDescriptor;
939
997
  var ReflectOwnKeys2 = Reflect.ownKeys;
940
998
  var ReflectApply4 = Reflect.apply;
999
+ var ReflectHas = Reflect.has;
941
1000
  var ReflectConstruct = Reflect.construct;
942
1001
  var ObjectGetPrototypeOf3 = Object.getPrototypeOf;
943
1002
  var HostObjectPrototype = Object.prototype;
@@ -1167,10 +1226,43 @@ var INTERNAL_SLOT_BUILTINS = /* @__PURE__ */ new Set([
1167
1226
  ]);
1168
1227
  var INTERNAL_SLOT_TYPES = /* @__PURE__ */ new Set(["[object Promise]"]);
1169
1228
  var boundBuiltinMethods = /* @__PURE__ */ new WeakSet();
1229
+ var argumentGuards = /* @__PURE__ */ new WeakMap();
1230
+ var gatedArgumentGuards = /* @__PURE__ */ new WeakMap();
1231
+ function gatedArgumentGuardCache(gate) {
1232
+ let cache = gatedArgumentGuards.get(gate);
1233
+ if (!cache) {
1234
+ cache = /* @__PURE__ */ new WeakMap();
1235
+ gatedArgumentGuards.set(gate, cache);
1236
+ }
1237
+ return cache;
1238
+ }
1239
+ var guardedArguments = /* @__PURE__ */ new WeakMap();
1170
1240
  var JsonParse = JSON.parse;
1171
1241
  var JsonStringify2 = JSON.stringify;
1172
- function passesHostValuesToCallbacks(fn) {
1173
- return isBuiltinMethod(fn) || fn === JsonParse || fn === JsonStringify2 || typeof fn === "function" && boundBuiltinMethods.has(fn);
1242
+ 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.";
1243
+ 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).";
1244
+ function isOfBuiltinKind(receiver, homes) {
1245
+ for (let h = 0; h < homes.length; h++) {
1246
+ const home = homes[h];
1247
+ if (home === HostObjectPrototype) {
1248
+ return true;
1249
+ }
1250
+ try {
1251
+ let proto = ObjectGetPrototypeOf3(receiver);
1252
+ for (let depth = 0; depth < 32 && proto !== null; depth++) {
1253
+ if (proto === home) {
1254
+ return true;
1255
+ }
1256
+ proto = ObjectGetPrototypeOf3(proto);
1257
+ }
1258
+ } catch {
1259
+ return false;
1260
+ }
1261
+ }
1262
+ return false;
1263
+ }
1264
+ function passesHostValuesToCallbacks(fn, builtinMethod) {
1265
+ return builtinMethod || fn === JsonParse || fn === JsonStringify2 || typeof fn === "function" && boundBuiltinMethods.has(fn);
1174
1266
  }
1175
1267
  function isProxyable(value) {
1176
1268
  return value !== null && (typeof value === "object" || typeof value === "function");
@@ -1189,6 +1281,20 @@ function createSecureProxy(target, options = {}) {
1189
1281
  const cacheKey = getFullCacheKey(options);
1190
1282
  const gateCache = options.callGate ? gatedProxyCache(options.callGate) : void 0;
1191
1283
  const lookupCached = (obj) => gateCache ? gateCache.get(obj) : proxyCache.get(obj)?.get(cacheKey);
1284
+ const gateGuards = options.callGate ? gatedArgumentGuardCache(options.callGate) : void 0;
1285
+ const lookupGuard = (obj) => gateGuards ? gateGuards.get(obj) : argumentGuards.get(obj)?.get(cacheKey);
1286
+ const storeGuard = (obj, guard) => {
1287
+ if (gateGuards) {
1288
+ gateGuards.set(obj, guard);
1289
+ return;
1290
+ }
1291
+ let guards = argumentGuards.get(obj);
1292
+ if (!guards) {
1293
+ guards = /* @__PURE__ */ new Map();
1294
+ argumentGuards.set(obj, guards);
1295
+ }
1296
+ guards.set(cacheKey, guard);
1297
+ };
1192
1298
  const cached = lookupCached(target);
1193
1299
  if (cached) {
1194
1300
  return cached;
@@ -1198,14 +1304,27 @@ function createSecureProxy(target, options = {}) {
1198
1304
  const configuredMaxDepth = options.maxDepth ?? options.levelConfig?.proxyMaxDepth ?? 10;
1199
1305
  const maxDepth = Number.isFinite(configuredMaxDepth) ? Math.max(configuredMaxDepth, MIN_MEMBRANE_RECURSION_DEPTH) : MIN_MEMBRANE_RECURSION_DEPTH;
1200
1306
  const throwOnBlocked = options.throwOnBlocked ?? options.levelConfig?.throwOnBlocked ?? false;
1307
+ const { ownedBySandbox, heldBySandbox } = options;
1308
+ const classifiesValues = ownedBySandbox !== void 0 || heldBySandbox !== void 0;
1309
+ const passesAsItIs = (value) => heldBySandbox !== void 0 && heldBySandbox(value) || ownedBySandbox !== void 0 && !proxySet.has(value) && ownedBySandbox(value);
1201
1310
  function proxyWithDepth(obj, depth) {
1202
1311
  if (!isProxyable(obj)) {
1203
1312
  return obj;
1204
1313
  }
1314
+ if (guardedArguments.has(obj)) {
1315
+ const guarded = guardedArguments.get(obj);
1316
+ if (!classifiesValues || !isProxyable(guarded)) {
1317
+ return guarded;
1318
+ }
1319
+ obj = guarded;
1320
+ }
1205
1321
  const cachedProxy = lookupCached(obj);
1206
1322
  if (cachedProxy) {
1207
1323
  return cachedProxy;
1208
1324
  }
1325
+ if (depth > 0 && passesAsItIs(obj)) {
1326
+ return obj;
1327
+ }
1209
1328
  if (depth > maxDepth) {
1210
1329
  throw createSafeError(
1211
1330
  `Security violation: secure-proxy recursion depth (${maxDepth}) exceeded. The value cannot be exposed without breaking the sandbox barrier.`,
@@ -1213,21 +1332,69 @@ function createSecureProxy(target, options = {}) {
1213
1332
  );
1214
1333
  }
1215
1334
  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;
1335
+ const toSandbox = (value) => {
1336
+ if (!isProxyable(value)) {
1337
+ return value;
1338
+ }
1339
+ if (heldBySandbox && heldBySandbox(value)) {
1340
+ return value;
1341
+ }
1342
+ const laundered = launderHostError(value);
1343
+ const wrapped = isProxyable(laundered) && !isSafeError(laundered) ? proxyWithDepth(laundered, depth + 1) : laundered;
1344
+ return options.exposeToSandbox ? options.exposeToSandbox(wrapped) : wrapped;
1345
+ };
1346
+ const guardObjectArgument = (value) => {
1347
+ if (value === null || typeof value !== "object") return value;
1348
+ if (proxySet.has(value) || guardedArguments.has(value) || Array.isArray(value)) return value;
1349
+ if (heldBySandbox && heldBySandbox(value)) return value;
1350
+ const existing = lookupGuard(value);
1351
+ if (existing) return existing;
1352
+ const original = value;
1353
+ const guard = new Proxy(/* @__PURE__ */ Object.create(null), {
1354
+ get: (_shell, property) => guardMember(ReflectGet3(original, property, original), original),
1355
+ has: (_shell, property) => ReflectHas(original, property),
1356
+ // A function that lists the object (to copy or to serialize it, as JSON.stringify does)
1357
+ // sees the script's own properties, each as a data property holding what a read gives.
1358
+ ownKeys: () => ReflectOwnKeys2(original),
1359
+ getOwnPropertyDescriptor: (_shell, property) => {
1360
+ const descriptor = ReflectGetOwnPropertyDescriptor(original, property);
1361
+ if (!descriptor) return void 0;
1362
+ return {
1363
+ value: guardMember(ReflectGet3(original, property, original), original),
1364
+ writable: true,
1365
+ enumerable: descriptor.enumerable === true,
1366
+ configurable: true
1367
+ };
1368
+ },
1369
+ // What a host function stores in the object is a host value like any other
1370
+ set: (_shell, property, stored) => ReflectSet(original, property, toSandbox(stored), original)
1371
+ });
1372
+ storeGuard(original, guard);
1373
+ guardedArguments.set(guard, original);
1374
+ return guard;
1375
+ };
1376
+ const guardMember = (member, holder) => {
1377
+ if (typeof member !== "function") return guardObjectArgument(member);
1378
+ const method = function guardedMethod(...hostArgs) {
1379
+ return guardArgument(ReflectApply4(member, holder, hostArgs.map(toSandbox)));
1226
1380
  };
1227
- return function guardedCallback(...hostArgs) {
1381
+ guardedArguments.set(method, member);
1382
+ return method;
1383
+ };
1384
+ const guardCallback = (callback) => {
1385
+ const guarded = function guardedCallback(...hostArgs) {
1228
1386
  return ReflectApply4(callback, toSandbox(this), hostArgs.map(toSandbox));
1229
1387
  };
1230
- });
1388
+ guardedArguments.set(guarded, callback);
1389
+ return guarded;
1390
+ };
1391
+ const guardArgument = (arg) => {
1392
+ if (typeof arg === "function") {
1393
+ return proxySet.has(arg) || guardedArguments.has(arg) || heldBySandbox && heldBySandbox(arg) ? arg : guardCallback(arg);
1394
+ }
1395
+ return guardObjectArgument(arg);
1396
+ };
1397
+ const guardCallbackArguments = (args) => args.map(guardArgument);
1231
1398
  const proxy = new Proxy(obj, {
1232
1399
  get(target2, property, receiver) {
1233
1400
  const propName = typeof property === "symbol" ? property.toString() : property;
@@ -1394,17 +1561,32 @@ function createSecureProxy(target, options = {}) {
1394
1561
  // Intercept function calls to proxy return values
1395
1562
  // eslint-disable-next-line @typescript-eslint/no-explicit-any -- Proxy handler signature requires any for compatibility
1396
1563
  apply(target2, thisArg, argArray) {
1397
- const unwrappedThis = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function") && proxyToTarget.has(thisArg) ? proxyToTarget.get(thisArg) : thisArg;
1564
+ const receiverIsReference = thisArg !== null && (typeof thisArg === "object" || typeof thisArg === "function");
1565
+ const wrappedReceiver = receiverIsReference ? proxyToTarget.get(thisArg) : void 0;
1566
+ const unwrappedThis = wrappedReceiver !== void 0 ? wrappedReceiver : thisArg;
1567
+ if (classifiesValues && typeof wrappedReceiver === "function" && isFunctionTextMethod(target2)) {
1568
+ return hostFunctionText(wrappedReceiver);
1569
+ }
1398
1570
  if (options.callGate && options.callGate.gates(target2)) {
1399
1571
  const hostReceiver = unwrappedThis !== thisArg ? unwrappedThis : void 0;
1400
1572
  return options.callGate.call(target2, hostReceiver, argArray);
1401
1573
  }
1574
+ const homes = builtinMethodHomes(target2);
1575
+ const builtinMethod = homes !== void 0;
1576
+ if (builtinMethod && heldBySandbox !== void 0 && receiverIsReference) {
1577
+ if (wrappedReceiver === void 0) {
1578
+ throw createSafeError(HOST_RECEIVER_MESSAGE, "TypeError");
1579
+ }
1580
+ if (!isOfBuiltinKind(wrappedReceiver, homes)) {
1581
+ throw createSafeError(HOST_RECEIVER_KIND_MESSAGE, "TypeError");
1582
+ }
1583
+ }
1402
1584
  let result;
1403
1585
  try {
1404
1586
  result = ReflectApply4(
1405
1587
  target2,
1406
1588
  unwrappedThis,
1407
- passesHostValuesToCallbacks(target2) ? guardCallbackArguments(argArray) : argArray
1589
+ passesHostValuesToCallbacks(target2, builtinMethod) ? guardCallbackArguments(argArray) : argArray
1408
1590
  );
1409
1591
  } catch (error) {
1410
1592
  throw launderHostError(error);
@@ -1594,6 +1776,18 @@ function isReferenceId(value) {
1594
1776
  return typeof value === "string" && REF_ID_PATTERN.test(value);
1595
1777
  }
1596
1778
 
1779
+ // libs/core/src/sidecar/reference-sidecar.ts
1780
+ var SidecarLimitError = class _SidecarLimitError extends Error {
1781
+ constructor(message, code, limit, current) {
1782
+ super(message);
1783
+ this.code = code;
1784
+ this.limit = limit;
1785
+ this.current = current;
1786
+ this.name = "SidecarLimitError";
1787
+ Object.setPrototypeOf(this, _SidecarLimitError.prototype);
1788
+ }
1789
+ };
1790
+
1597
1791
  // libs/core/src/sidecar/reference-resolver.ts
1598
1792
  var ReflectGet4 = Reflect.get;
1599
1793
  var NumberIsFinite3 = Number.isFinite;
@@ -1701,17 +1895,88 @@ var ReferenceResolver = class {
1701
1895
  /**
1702
1896
  * Check if resolution would exceed size limits
1703
1897
  *
1898
+ * Two limits apply: `maxResolvedSize` to what this value expands to, and
1899
+ * `maxTotalResolvedSize` to what the execution has had resolved so far plus what resolving
1900
+ * this value would add (see `predictAddedSize`).
1901
+ *
1704
1902
  * @param value - The value to check
1705
- * @returns true if resolution would exceed maxResolvedSize
1903
+ * @returns true if resolution would exceed maxResolvedSize or the execution's total
1706
1904
  */
1707
1905
  wouldExceedLimit(value) {
1708
1906
  try {
1709
1907
  const size = this.predictExpandedSize(value);
1710
- return size > this.config.maxResolvedSize;
1908
+ if (size > this.config.maxResolvedSize) {
1909
+ return true;
1910
+ }
1911
+ return !this.sidecar.canResolve(this.predictAddedSize(value, 0, /* @__PURE__ */ new Set()));
1711
1912
  } catch {
1712
1913
  return true;
1713
1914
  }
1714
1915
  }
1916
+ /**
1917
+ * Predict what resolving a value would add to the execution's total of resolved data,
1918
+ * WITHOUT allocating memory
1919
+ *
1920
+ * A stored value adds its size the first time it is resolved in the execution and nothing
1921
+ * afterwards (`counted` holds the ones this walk has seen). A composite adds the size of the
1922
+ * string it is joined into, every time, besides what its parts add.
1923
+ */
1924
+ predictAddedSize(value, depth, counted) {
1925
+ if (depth > this.config.maxResolutionDepth) {
1926
+ throw new ResolutionLimitError(
1927
+ `Maximum resolution depth exceeded (${this.config.maxResolutionDepth})`,
1928
+ "MAX_RESOLUTION_DEPTH",
1929
+ this.config.maxResolutionDepth,
1930
+ depth
1931
+ );
1932
+ }
1933
+ if (isReferenceId(value)) {
1934
+ if (counted.has(value) || this.sidecar.isResolved(value)) {
1935
+ return 0;
1936
+ }
1937
+ counted.add(value);
1938
+ return this.sidecar.getSize(value) ?? 0;
1939
+ }
1940
+ if (isCompositeHandle(value)) {
1941
+ const parts = value.__parts;
1942
+ const len = untrustedLength(parts);
1943
+ let sum = this.predictExpandedSize(value, depth);
1944
+ for (let i = 0; i < len; i++) {
1945
+ sum += this.predictAddedSize(untrustedAt(parts, i), depth + 1, counted);
1946
+ }
1947
+ return sum;
1948
+ }
1949
+ if (Array.isArray(value)) {
1950
+ const len = untrustedLength(value);
1951
+ let sum = 0;
1952
+ for (let i = 0; i < len; i++) {
1953
+ sum += this.predictAddedSize(untrustedAt(value, i), depth + 1, counted);
1954
+ }
1955
+ return sum;
1956
+ }
1957
+ if (value !== null && typeof value === "object") {
1958
+ let sum = 0;
1959
+ for (const val of Object.values(value)) {
1960
+ sum += this.predictAddedSize(val, depth + 1, counted);
1961
+ }
1962
+ return sum;
1963
+ }
1964
+ return 0;
1965
+ }
1966
+ /**
1967
+ * Run a step that counts resolved data against the execution's total; when the sidecar
1968
+ * refuses it, the refusal is thrown as the resolution error callers of `resolve` handle
1969
+ */
1970
+ withinTotal(count) {
1971
+ try {
1972
+ count();
1973
+ } catch (error) {
1974
+ if (error instanceof SidecarLimitError) {
1975
+ throw new ResolutionLimitError(error.message, error.code, error.limit, error.current);
1976
+ }
1977
+ throw error;
1978
+ }
1979
+ }
1715
1980
  /**
1716
1981
  * Resolve all reference IDs in a value tree
1717
1982
  *
@@ -1734,7 +1999,10 @@ var ReferenceResolver = class {
1734
1999
  );
1735
2000
  }
1736
2001
  if (isReferenceId(value)) {
1737
- const data = this.sidecar.retrieveString(value);
2002
+ let data;
2003
+ this.withinTotal(() => {
2004
+ data = this.sidecar.resolveString(value);
2005
+ });
1738
2006
  if (data === void 0) {
1739
2007
  throw new Error(`Unknown reference: ${value}`);
1740
2008
  }
@@ -1772,6 +2040,8 @@ var ReferenceResolver = class {
1772
2040
  * Resolve a composite handle by concatenating its parts
1773
2041
  */
1774
2042
  resolveComposite(handle, depth) {
2043
+ const joinedSize = this.predictExpandedSize(handle, depth);
2044
+ this.withinTotal(() => this.sidecar.countResolved(joinedSize));
1775
2045
  const out = [];
1776
2046
  const source = handle.__parts;
1777
2047
  const len = untrustedLength(source);
@@ -1881,6 +2151,8 @@ var MemoryTracker = class {
1881
2151
  trackedBytes = 0;
1882
2152
  peakTrackedBytes = 0;
1883
2153
  allocationCount = 0;
2154
+ /** Whether this tracker has refused an allocation since it was started */
2155
+ limitExceeded = false;
1884
2156
  config;
1885
2157
  constructor(config = {}) {
1886
2158
  this.config = {
@@ -1897,6 +2169,14 @@ var MemoryTracker = class {
1897
2169
  this.trackedBytes = 0;
1898
2170
  this.peakTrackedBytes = 0;
1899
2171
  this.allocationCount = 0;
2172
+ this.limitExceeded = false;
2173
+ }
2174
+ /**
2175
+ * Whether the limit was exceeded since tracking started: the tracker itself refused an
2176
+ * allocation. An error that only says so about itself is not evidence of that.
2177
+ */
2178
+ hasExceededLimit() {
2179
+ return this.limitExceeded;
1900
2180
  }
1901
2181
  /**
1902
2182
  * Track an allocation
@@ -1907,6 +2187,7 @@ var MemoryTracker = class {
1907
2187
  track(bytes) {
1908
2188
  if (typeof bytes !== "number" || Number.isNaN(bytes)) {
1909
2189
  if (this.config.memoryLimit > 0) {
2190
+ this.limitExceeded = true;
1910
2191
  throw new MemoryLimitError(
1911
2192
  "Memory limit exceeded: allocation size is not a number",
1912
2193
  this.trackedBytes,
@@ -1922,6 +2203,7 @@ var MemoryTracker = class {
1922
2203
  this.peakTrackedBytes = this.trackedBytes;
1923
2204
  }
1924
2205
  if (this.config.memoryLimit > 0 && this.trackedBytes > this.config.memoryLimit) {
2206
+ this.limitExceeded = true;
1925
2207
  throw new MemoryLimitError(
1926
2208
  `Memory limit exceeded: ${this.formatBytes(this.trackedBytes)} used > ${this.formatBytes(
1927
2209
  this.config.memoryLimit
@@ -2565,8 +2847,8 @@ function redactLine(line) {
2565
2847
  }
2566
2848
  function sanitizeStackTrace(stack, sanitize = true) {
2567
2849
  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");
2850
+ const bounded2 = stack.length > MAX_STACK_LENGTH ? stack.slice(0, MAX_STACK_LENGTH) : stack;
2851
+ return bounded2.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
2570
2852
  }
2571
2853
 
2572
2854
  // libs/core/src/console-handler.ts
@@ -2715,9 +2997,11 @@ var SandboxScript = api.SandboxScript;
2715
2997
  var ReusableSandboxScript = api.ReusableSandboxScript;
2716
2998
 
2717
2999
  // libs/core/src/sandbox-rejections.ts
3000
+ var import_util = require("util");
2718
3001
  var HostPromisePrototype = Promise.prototype;
2719
3002
  var ObjectGetPrototypeOf4 = Object.getPrototypeOf;
2720
3003
  var ReflectApply5 = Reflect.apply;
3004
+ var isEnginePromise = import_util.types.isPromise;
2721
3005
  var MAX_PROTOTYPE_CHAIN = 32;
2722
3006
  var MAX_INSTALLS = 8;
2723
3007
  function isHostPromise(promise) {
@@ -2737,6 +3021,9 @@ function isHostPromise(promise) {
2737
3021
  }
2738
3022
  return false;
2739
3023
  }
3024
+ function isSandboxPromise(value) {
3025
+ return isEnginePromise(value) && !isHostPromise(value);
3026
+ }
2740
3027
  var PROBE_EVENT = `enclave-vm:rejection-guard:${Math.random().toString(36).slice(2)}`;
2741
3028
  var active = false;
2742
3029
  var optedOut = false;
@@ -2749,10 +3036,10 @@ function wrapEmit(previous) {
2749
3036
  return false;
2750
3037
  }
2751
3038
  if (active) {
2752
- if (event === "unhandledRejection" && !isHostPromise(args[1])) {
3039
+ if (event === "unhandledRejection" && isSandboxPromise(args[1])) {
2753
3040
  return true;
2754
3041
  }
2755
- if (event === "rejectionHandled" && !isHostPromise(args[0])) {
3042
+ if (event === "rejectionHandled" && isSandboxPromise(args[0])) {
2756
3043
  return true;
2757
3044
  }
2758
3045
  }
@@ -2776,6 +3063,54 @@ function guardSandboxRejections() {
2776
3063
  process.emit = wrapEmit(process.emit);
2777
3064
  }
2778
3065
 
3066
+ // libs/core/src/thrown-value.ts
3067
+ var MAX_THROWN_NAME_LENGTH = 256;
3068
+ var MAX_THROWN_MESSAGE_LENGTH = 16 * 1024;
3069
+ var MAX_THROWN_STACK_LENGTH = 64 * 1024;
3070
+ var ReflectGet5 = Reflect.get;
3071
+ function bounded(text, max) {
3072
+ return text.length > max ? text.slice(0, max) : text;
3073
+ }
3074
+ function stringMember(value, key, max) {
3075
+ try {
3076
+ const member = ReflectGet5(value, key);
3077
+ return typeof member === "string" ? bounded(member, max) : void 0;
3078
+ } catch {
3079
+ return void 0;
3080
+ }
3081
+ }
3082
+ function describeThrown(thrown) {
3083
+ if (typeof thrown === "string") {
3084
+ return { message: bounded(thrown, MAX_THROWN_MESSAGE_LENGTH) };
3085
+ }
3086
+ if (thrown === null || thrown === void 0) {
3087
+ return { message: `The script threw ${String(thrown)}` };
3088
+ }
3089
+ if (typeof thrown === "symbol") {
3090
+ return { message: "The script threw a symbol" };
3091
+ }
3092
+ if (typeof thrown !== "object" && typeof thrown !== "function") {
3093
+ return { message: bounded(`The script threw the ${typeof thrown} ${String(thrown)}`, MAX_THROWN_MESSAGE_LENGTH) };
3094
+ }
3095
+ const name = stringMember(thrown, "name", MAX_THROWN_NAME_LENGTH);
3096
+ const message = stringMember(thrown, "message", MAX_THROWN_MESSAGE_LENGTH);
3097
+ const stack = stringMember(thrown, "stack", MAX_THROWN_STACK_LENGTH);
3098
+ return {
3099
+ ...name !== void 0 ? { name } : {},
3100
+ ...message !== void 0 ? { message } : {},
3101
+ ...stack !== void 0 ? { stack } : {}
3102
+ };
3103
+ }
3104
+ function isMemoryLimitPayload(thrown) {
3105
+ if (thrown === null || typeof thrown !== "object" && typeof thrown !== "function") return false;
3106
+ try {
3107
+ return ReflectGet5(thrown, "code") === "MEMORY_LIMIT_EXCEEDED";
3108
+ } catch {
3109
+ return false;
3110
+ }
3111
+ }
3112
+ var THROWN_WITHOUT_MESSAGE = "The script threw a value that is not an error";
3113
+
2779
3114
  // libs/core/src/tool-namespaces.ts
2780
3115
  var TOOL_NAMESPACE_FACTORY_SOURCE = `
2781
3116
  (function () {
@@ -2832,6 +3167,8 @@ function buildToolNamespaceBindings(install, callTool, namespaces) {
2832
3167
  var walk = __toESM(require("acorn-walk"));
2833
3168
  var REALM_TICK_FN = "__safe_tick";
2834
3169
  var TICKS_PER_CLOCK_CHECK = 256;
3170
+ var TICKS_AFTER_END = 1024;
3171
+ var EXECUTION_ENDED_MESSAGE = "Script execution has ended";
2835
3172
  function realmTickSource(timeoutMs) {
2836
3173
  const timeout = Number.isFinite(timeoutMs) && timeoutMs > 0 ? Math.floor(timeoutMs) : 0;
2837
3174
  return `
@@ -2842,12 +3179,20 @@ function realmTickSource(timeoutMs) {
2842
3179
  var deadline = timeoutMs > 0 ? now() + timeoutMs : Infinity;
2843
3180
  var expired = false;
2844
3181
  var count = 0;
3182
+ // Set when the execution has ended; what the script left behind then gets graceLeft more
3183
+ // checks to settle in.
3184
+ var ended = false;
3185
+ var graceLeft = ${TICKS_AFTER_END};
2845
3186
  var message = 'Script execution timed out after ' + timeoutMs + 'ms';
2846
3187
  Object.defineProperty(globalThis, ${JSON.stringify(REALM_TICK_FN)}, {
2847
3188
  value: function () {
2848
3189
  if (!expired) {
2849
- count++;
2850
- if (count % ${TICKS_PER_CLOCK_CHECK} !== 0 || now() < deadline) return;
3190
+ if (ended) {
3191
+ if (graceLeft-- > 0) return;
3192
+ } else {
3193
+ count++;
3194
+ if (count % ${TICKS_PER_CLOCK_CHECK} !== 0 || now() < deadline) return;
3195
+ }
2851
3196
  expired = true;
2852
3197
  }
2853
3198
  throw message;
@@ -2856,109 +3201,1357 @@ function realmTickSource(timeoutMs) {
2856
3201
  configurable: false,
2857
3202
  enumerable: false
2858
3203
  });
3204
+ return function () {
3205
+ if (!expired && !ended) {
3206
+ ended = true;
3207
+ message = ${JSON.stringify(EXECUTION_ENDED_MESSAGE)};
3208
+ }
3209
+ };
2859
3210
  })(${timeout})
2860
3211
  `.trim();
2861
3212
  }
2862
3213
 
2863
- // libs/core/src/double-vm/parent-vm-bootstrap.ts
2864
- var MEMBRANE_MAX_RECURSION_DEPTH = 256;
2865
- var NODEJS_24_DANGEROUS_GLOBALS = {
2866
- STRICT: [
2867
- // Code execution - CRITICAL
2868
- "Function",
2869
- // Constructor for functions - primary escape vector
2870
- "eval",
2871
- // Direct code execution
2872
- "globalThis",
2873
- // Indirect access to all globals
2874
- // Metaprogramming - sandbox escape vectors
2875
- "Proxy",
2876
- // Can intercept all operations
2877
- "Reflect",
2878
- // Metaprogramming primitive
2879
- // Memory/timing attacks
2880
- "SharedArrayBuffer",
2881
- // Spectre/timing attacks
2882
- "Atomics",
2883
- // Shared memory operations
2884
- "gc",
2885
- // Force garbage collection (shouldn't be exposed)
2886
- // Future/experimental APIs
2887
- "Iterator",
2888
- // Iterator helpers
2889
- "AsyncIterator",
2890
- // Async iterator helpers
2891
- "ShadowRealm",
2892
- // New realm creation (major escape risk)
2893
- "WeakRef",
2894
- // Can observe GC behavior
2895
- "FinalizationRegistry",
2896
- // Can observe GC behavior
2897
- "performance",
2898
- // Timing information
2899
- "Temporal"
2900
- // New date/time API
2901
- ],
2902
- SECURE: [
2903
- // Code execution - CRITICAL
2904
- "Function",
2905
- "eval",
2906
- "globalThis",
2907
- // Most dangerous metaprogramming
2908
- "Proxy",
2909
- // Memory/timing attacks
2910
- "SharedArrayBuffer",
2911
- "Atomics",
2912
- "gc",
2913
- // Future APIs
2914
- "Iterator",
2915
- "AsyncIterator",
2916
- "ShadowRealm",
2917
- "WeakRef",
2918
- "FinalizationRegistry"
2919
- ],
2920
- STANDARD: [
2921
- // Code execution - always block these
2922
- "Function",
2923
- "eval",
2924
- // Memory/timing attacks
2925
- "SharedArrayBuffer",
2926
- "Atomics",
2927
- "gc",
2928
- // Definitely dangerous
2929
- "ShadowRealm",
2930
- "WeakRef",
2931
- "FinalizationRegistry"
2932
- ],
2933
- PERMISSIVE: [
2934
- // Even PERMISSIVE should block the most dangerous
2935
- "ShadowRealm",
2936
- // Too dangerous to allow
2937
- "gc",
2938
- // Shouldn't be exposed at all
2939
- "SharedArrayBuffer",
2940
- // Spectre risk
2941
- "Atomics"
2942
- // Goes with SharedArrayBuffer
2943
- ]
2944
- };
2945
- var INNER_REALM_SCRUB_SOURCE = `
2946
- (function () {
2947
- 'use strict';
2948
- var global = globalThis;
2949
- var getOwnPropertyNames = Object.getOwnPropertyNames;
2950
- var getOwnPropertySymbols = Object.getOwnPropertySymbols;
2951
- var getPrototypeOf = Object.getPrototypeOf;
2952
- var setPrototypeOf = Object.setPrototypeOf;
2953
-
2954
- return function scrub(remove, keep) {
2955
- var kept = { __proto__: null };
2956
- var i;
2957
- var j;
2958
- for (i = 0; i < keep.length; i++) kept[keep[i]] = true;
2959
-
2960
- var targets = [];
2961
- if (remove) {
3214
+ // libs/core/src/types.ts
3215
+ var SECURITY_LEVEL_CONFIGS = {
3216
+ /**
3217
+ * STRICT: Maximum security for untrusted code
3218
+ *
3219
+ * Use for:
3220
+ * - AI-generated code from external sources
3221
+ * - User-submitted scripts
3222
+ * - Untrusted third-party integrations
3223
+ *
3224
+ * Characteristics:
3225
+ * - Short timeout (5s)
3226
+ * - Low iteration limits (1000)
3227
+ * - Limited tool calls (10)
3228
+ * - Deep value sanitization
3229
+ * - Full stack trace sanitization
3230
+ */
3231
+ STRICT: {
3232
+ timeout: 5e3,
3233
+ maxIterations: 1e3,
3234
+ maxToolCalls: 10,
3235
+ maxSanitizeDepth: 5,
3236
+ maxSanitizeProperties: 50,
3237
+ sanitizeStackTraces: true,
3238
+ blockTimingAPIs: true,
3239
+ allowUnboundedLoops: false,
3240
+ unicodeSecurityCheck: true,
3241
+ allowFunctionsInGlobals: false,
3242
+ maxConsoleOutputBytes: 64 * 1024,
3243
+ // 64KB - prevent I/O flood attacks
3244
+ maxConsoleCalls: 100,
3245
+ secureProxy: {
3246
+ blockConstructor: true,
3247
+ blockPrototype: true,
3248
+ blockLegacyAccessors: true,
3249
+ proxyMaxDepth: 5,
3250
+ throwOnBlocked: true
3251
+ }
3252
+ },
3253
+ /**
3254
+ * SECURE: High security with more headroom
3255
+ *
3256
+ * Use for:
3257
+ * - AI-generated code from trusted models
3258
+ * - Internal automation scripts
3259
+ * - Controlled multi-tenant environments
3260
+ *
3261
+ * Characteristics:
3262
+ * - Moderate timeout (15s)
3263
+ * - Moderate iteration limits (5000)
3264
+ * - Moderate tool calls (50)
3265
+ * - Standard value sanitization
3266
+ * - Stack trace sanitization
3267
+ */
3268
+ SECURE: {
3269
+ timeout: 15e3,
3270
+ maxIterations: 5e3,
3271
+ maxToolCalls: 50,
3272
+ maxSanitizeDepth: 10,
3273
+ maxSanitizeProperties: 100,
3274
+ sanitizeStackTraces: true,
3275
+ blockTimingAPIs: false,
3276
+ allowUnboundedLoops: false,
3277
+ unicodeSecurityCheck: true,
3278
+ allowFunctionsInGlobals: false,
3279
+ maxConsoleOutputBytes: 256 * 1024,
3280
+ // 256KB
3281
+ maxConsoleCalls: 500,
3282
+ secureProxy: {
3283
+ blockConstructor: true,
3284
+ blockPrototype: true,
3285
+ blockLegacyAccessors: true,
3286
+ proxyMaxDepth: 10,
3287
+ throwOnBlocked: true
3288
+ }
3289
+ },
3290
+ /**
3291
+ * STANDARD: Balanced security and functionality (DEFAULT)
3292
+ *
3293
+ * Use for:
3294
+ * - Internal tools and scripts
3295
+ * - Development and testing
3296
+ * - Trusted environments
3297
+ *
3298
+ * Characteristics:
3299
+ * - Standard timeout (30s)
3300
+ * - Standard iteration limits (10000)
3301
+ * - Standard tool calls (100)
3302
+ * - Basic value sanitization
3303
+ * - Minimal stack trace sanitization
3304
+ */
3305
+ STANDARD: {
3306
+ timeout: 3e4,
3307
+ maxIterations: 1e4,
3308
+ maxToolCalls: 100,
3309
+ maxSanitizeDepth: 20,
3310
+ maxSanitizeProperties: 500,
3311
+ sanitizeStackTraces: false,
3312
+ blockTimingAPIs: false,
3313
+ allowUnboundedLoops: true,
3314
+ unicodeSecurityCheck: false,
3315
+ allowFunctionsInGlobals: false,
3316
+ maxConsoleOutputBytes: 1024 * 1024,
3317
+ // 1MB
3318
+ maxConsoleCalls: 1e3,
3319
+ secureProxy: {
3320
+ blockConstructor: true,
3321
+ blockPrototype: true,
3322
+ blockLegacyAccessors: true,
3323
+ proxyMaxDepth: 15,
3324
+ throwOnBlocked: true
3325
+ }
3326
+ },
3327
+ /**
3328
+ * PERMISSIVE: Minimal restrictions
3329
+ *
3330
+ * Use for:
3331
+ * - Local development only
3332
+ * - Debugging
3333
+ * - Performance testing
3334
+ *
3335
+ * WARNING: Not recommended for production use with untrusted code
3336
+ *
3337
+ * Characteristics:
3338
+ * - Long timeout (60s)
3339
+ * - High iteration limits (100000)
3340
+ * - High tool calls (1000)
3341
+ * - Minimal sanitization
3342
+ * - No stack trace sanitization
3343
+ * - All features enabled
3344
+ */
3345
+ PERMISSIVE: {
3346
+ timeout: 6e4,
3347
+ maxIterations: 1e5,
3348
+ maxToolCalls: 1e3,
3349
+ maxSanitizeDepth: 50,
3350
+ maxSanitizeProperties: 1e3,
3351
+ sanitizeStackTraces: false,
3352
+ blockTimingAPIs: false,
3353
+ allowUnboundedLoops: true,
3354
+ unicodeSecurityCheck: false,
3355
+ allowFunctionsInGlobals: true,
3356
+ maxConsoleOutputBytes: 10 * 1024 * 1024,
3357
+ // 10MB
3358
+ maxConsoleCalls: 1e4,
3359
+ secureProxy: {
3360
+ blockConstructor: false,
3361
+ // Allow constructor access for development/debugging
3362
+ blockPrototype: true,
3363
+ // Still block prototype for safety
3364
+ blockLegacyAccessors: true,
3365
+ proxyMaxDepth: 20,
3366
+ throwOnBlocked: false
3367
+ // Return undefined instead of throwing for development
3368
+ }
3369
+ }
3370
+ };
3371
+ var DEFAULT_DOUBLE_VM_CONFIG = {
3372
+ enabled: true,
3373
+ parentTimeoutBuffer: 1e3,
3374
+ parentValidation: {
3375
+ validateOperationNames: true,
3376
+ maxOperationsPerSecond: 100,
3377
+ blockSuspiciousSequences: true,
3378
+ rapidEnumerationThreshold: 30,
3379
+ rapidEnumerationOverrides: {},
3380
+ suspiciousPatterns: []
3381
+ // Default patterns added at runtime
3382
+ }
3383
+ };
3384
+
3385
+ // libs/core/src/enclave-options.ts
3386
+ function describe(value) {
3387
+ if (value === null) return "null";
3388
+ if (typeof value === "number") return String(value);
3389
+ if (Array.isArray(value)) return "an array";
3390
+ if (typeof value === "string") return "a string";
3391
+ return `a value of type ${typeof value}`;
3392
+ }
3393
+ function numericLiteral(name, value) {
3394
+ if (typeof value !== "number" || !Number.isFinite(value)) {
3395
+ throw new TypeError(`${name} must be a finite number, got ${describe(value)}`);
3396
+ }
3397
+ return String(value);
3398
+ }
3399
+ function booleanLiteral(name, value) {
3400
+ if (typeof value !== "boolean") {
3401
+ throw new TypeError(`${name} must be true or false, got ${describe(value)}`);
3402
+ }
3403
+ return value ? "true" : "false";
3404
+ }
3405
+
3406
+ // libs/core/src/realm-stack.ts
3407
+ var STACK_CAPTURE_OFF_SOURCE = `
3408
+ (function () {
3409
+ 'use strict';
3410
+ try {
3411
+ Object.defineProperty(Error, 'stackTraceLimit', {
3412
+ value: undefined,
3413
+ writable: false,
3414
+ configurable: false,
3415
+ enumerable: false
3416
+ });
3417
+ } catch (e) { /* defined already */ }
3418
+ })();
3419
+ `.trim();
3420
+
3421
+ // libs/core/src/realm-memory.ts
3422
+ var ARRAY_ELEMENT_BYTES = 8;
3423
+ var ARRAY_START_FN = "__safe_arrayStart";
3424
+ var ARRAY_SPREAD_FN = "__safe_spread";
3425
+ var ARRAY_FINISH_FN = "__safe_array";
3426
+ var ARRAY_SET_FN = "__safe_set";
3427
+ var ARRAY_SLOT_FN = "__safe_slot";
3428
+ function realmArrayAccountingSource(memoryLimit) {
3429
+ return `
3430
+ (function (memoryLimit, track) {
3431
+ 'use strict';
3432
+ // Everything the patched functions use is taken now: none of it is looked up again on an
3433
+ // object a script can write to.
3434
+ var apply = Reflect.apply;
3435
+ var isArray = Array.isArray;
3436
+ var defineProperty = Object.defineProperty;
3437
+ var objectCreate = Object.create;
3438
+ var ObjectCtor = Object;
3439
+ var construct = Reflect.construct;
3440
+ var ownKeys = Reflect.ownKeys;
3441
+ var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
3442
+ var ProxyCtor = typeof Proxy === 'function' ? Proxy : undefined;
3443
+ var RangeErrorCtor = RangeError;
3444
+ var TypeErrorCtor = TypeError;
3445
+ var StringCtor = String;
3446
+ var arrayProto = Array.prototype;
3447
+ var stringProto = String.prototype;
3448
+ var ArrayCtor = Array;
3449
+ var iteratorSymbol = Symbol.iterator;
3450
+ var speciesSymbol = Symbol.species;
3451
+ var spreadableSymbol = Symbol.isConcatSpreadable;
3452
+ var asyncIteratorSymbol = Symbol.asyncIterator;
3453
+ var MAX_SAFE_INTEGER = 9007199254740991;
3454
+ var limited = memoryLimit > 0 && typeof track === 'function';
3455
+ var BYTES = ${ARRAY_ELEMENT_BYTES};
3456
+ // Charged to the tracker in batches: a call into the host for every pushed element is not
3457
+ // affordable, and what is pending is at most this much.
3458
+ var BATCH = 4096;
3459
+ var pending = 0;
3460
+
3461
+ // A refusal goes through the tracker, which answers an amount over the limit with the
3462
+ // execution's memory-limit error; the RangeError is for a tracker that did not.
3463
+ function refuse(label, bytes) {
3464
+ // A finite amount: a length a script made up can be anything
3465
+ if (!(bytes <= MAX_SAFE_INTEGER)) bytes = MAX_SAFE_INTEGER;
3466
+ track(bytes > memoryLimit ? bytes : memoryLimit + 1);
3467
+ throw new RangeErrorCtor(label + ' would exceed memory limit');
3468
+ }
3469
+
3470
+ /** Rule 1: an array of that many elements is not made. */
3471
+ function checkLength(length, label) {
3472
+ if (limited && typeof length === 'number' && length * BYTES > memoryLimit) refuse(label, length * BYTES);
3473
+ }
3474
+
3475
+ /** Rule 2: that many elements were added. */
3476
+ function charge(elements) {
3477
+ if (!limited || !(elements > 0)) return;
3478
+ pending += elements * BYTES;
3479
+ if (pending >= BATCH) {
3480
+ var bytes = pending;
3481
+ pending = 0;
3482
+ track(bytes);
3483
+ }
3484
+ }
3485
+
3486
+ function lengthOf(value) {
3487
+ return isArray(value) ? value.length : 0;
3488
+ }
3489
+
3490
+ // Rule 3: the conversions of the language, done once. Each throws where the built-in would
3491
+ // (a Symbol, a BigInt), and may run code of the script (valueOf, toString): once.
3492
+
3493
+ /** ToIntegerOrInfinity */
3494
+ function toInteger(value) {
3495
+ var number = +value;
3496
+ if (number !== number) return 0;
3497
+ if (number === Infinity || number === -Infinity) return number;
3498
+ return number < 0 ? -((-number) - ((-number) % 1)) : number - (number % 1);
3499
+ }
3500
+
3501
+ /** ToLength */
3502
+ function toLength(value) {
3503
+ var integer = toInteger(value);
3504
+ if (integer <= 0) return 0;
3505
+ return integer > MAX_SAFE_INTEGER ? MAX_SAFE_INTEGER : integer;
3506
+ }
3507
+
3508
+ /** A start or end argument relative to a length, as fill, slice and the like read it. */
3509
+ function relativeIndex(value, length, whenUndefined) {
3510
+ if (value === undefined) return whenUndefined;
3511
+ var relative = toInteger(value);
3512
+ if (relative < 0) {
3513
+ var fromEnd = length + relative;
3514
+ return fromEnd > 0 ? fromEnd : 0;
3515
+ }
3516
+ return relative < length ? relative : length;
3517
+ }
3518
+
3519
+ /** ToString, for a value that is not null or undefined */
3520
+ function toText(value) {
3521
+ if (typeof value === 'string') return value;
3522
+ if (typeof value === 'symbol') throw new TypeErrorCtor('Cannot convert a Symbol value to a string');
3523
+ return StringCtor(value);
3524
+ }
3525
+
3526
+ function isObject(value) {
3527
+ return value !== null && (typeof value === 'object' || typeof value === 'function');
3528
+ }
3529
+
3530
+ /** ToObject: what a built-in works on. Null for a receiver the built-in refuses. */
3531
+ function toObject(value) {
3532
+ if (value === null || value === undefined) return null;
3533
+ return isObject(value) ? value : ObjectCtor(value);
3534
+ }
3535
+
3536
+ /**
3537
+ * A plain array of what a source answers for its first slots. Each slot is asked once, with
3538
+ * the source itself as the receiver of the read; with \`holes\`, a slot the source does not
3539
+ * have stays empty. The caller has checked the length: this makes an array of it.
3540
+ */
3541
+ function snapshot(source, length, holes) {
3542
+ var copy = [];
3543
+ for (var i = 0; i < length; i++) {
3544
+ if (!holes || i in source) copy[i] = source[i];
3545
+ }
3546
+ if (copy.length !== length) copy.length = length;
3547
+ return copy;
3548
+ }
3549
+
3550
+ /**
3551
+ * What a built-in is given to read a source by its length: the length that was checked, and
3552
+ * each slot when the built-in asks for it, read from the source itself. Nothing else (no
3553
+ * prototype, no iterator), so the built-in can only read it that way, and it reads a slot
3554
+ * when it gets to it, as it does on the source: what a mapping function changed in between
3555
+ * is what it finds. The handler has no prototype either: what a proxy looks up on its
3556
+ * handler is not looked up on an object a script can write to.
3557
+ */
3558
+ function slotsOf(source, length) {
3559
+ var handler = objectCreate(null);
3560
+ handler.get = function (target, key) {
3561
+ if (key === 'length') return length;
3562
+ return typeof key === 'string' ? source[key] : undefined;
3563
+ };
3564
+ return new ProxyCtor(objectCreate(null), handler);
3565
+ }
3566
+
3567
+ /**
3568
+ * The empty array a built-in would make for a result of the receiver's kind
3569
+ * (ArraySpeciesCreate): null for a plain array, which the caller makes itself.
3570
+ */
3571
+ function emptyOfKind(receiver) {
3572
+ if (!isArray(receiver)) return null;
3573
+ var kind = receiver.constructor;
3574
+ if (kind === ArrayCtor) return null;
3575
+ if (isObject(kind)) {
3576
+ kind = kind[speciesSymbol];
3577
+ if (kind === null) kind = undefined;
3578
+ }
3579
+ if (kind === undefined || kind === ArrayCtor) return null;
3580
+ return construct(kind, [0]);
3581
+ }
3582
+
3583
+ // The accounting is installed in full or the realm is not set up. A part of it that cannot
3584
+ // be put in place (a global or a method that cannot be replaced any more) is not skipped:
3585
+ // the checks that rest on it would be off, and nothing would say so.
3586
+ function cannotInstall(what) {
3587
+ throw new TypeErrorCtor('Array accounting: ' + what + ' of the realm cannot be replaced');
3588
+ }
3589
+
3590
+ // A proxy a script makes answers for its length and its slots as its handler likes, and
3591
+ // \`Array.isArray\` says yes to a proxy of an array. Where a realm leaves a script the Proxy
3592
+ // constructor (the double VM at STANDARD and PERMISSIVE), the script gets a stand-in for it
3593
+ // that makes the same proxy and remembers it. A remembered proxy is not handed to a built-in
3594
+ // as an array: it is read once, like any object that states a length.
3595
+ var scriptProxies = null;
3596
+ var proxyMade = false;
3597
+ if (limited && ProxyCtor !== undefined) {
3598
+ if (typeof WeakSet !== 'function') cannotInstall('Proxy');
3599
+ var remember = WeakSet.prototype.add;
3600
+ var remembered = WeakSet.prototype.has;
3601
+ var makeRevocable = ProxyCtor.revocable;
3602
+ scriptProxies = new WeakSet();
3603
+ var ProxyStandIn = function Proxy(target, handler) {
3604
+ if (new.target === undefined) throw new TypeErrorCtor("Constructor Proxy requires 'new'");
3605
+ var made = new ProxyCtor(target, handler);
3606
+ apply(remember, scriptProxies, [made]);
3607
+ proxyMade = true;
3608
+ return made;
3609
+ };
3610
+ // Like the built-in, it has no prototype of its own to give
3611
+ ProxyStandIn.prototype = undefined;
3612
+ defineProperty(ProxyStandIn, 'revocable', {
3613
+ value: function revocable(target, handler) {
3614
+ var pair = apply(makeRevocable, ProxyCtor, [target, handler]);
3615
+ apply(remember, scriptProxies, [pair.proxy]);
3616
+ proxyMade = true;
3617
+ return pair;
3618
+ },
3619
+ writable: true,
3620
+ enumerable: false,
3621
+ configurable: true
3622
+ });
3623
+ try {
3624
+ defineProperty(globalThis, 'Proxy', { value: ProxyStandIn, writable: true, enumerable: false, configurable: true });
3625
+ } catch (e) {
3626
+ cannotInstall('Proxy');
3627
+ }
3628
+ }
3629
+
3630
+ function isScriptProxy(value) {
3631
+ return proxyMade && isObject(value) && apply(remembered, scriptProxies, [value]);
3632
+ }
3633
+
3634
+ /** An array that answers for itself: not one behind a proxy a script made. */
3635
+ function ownArray(value) {
3636
+ return isArray(value) && !isScriptProxy(value);
3637
+ }
3638
+
3639
+ // Rule 4: no array has more slots than the limit holds, and no built-in walks more.
3640
+
3641
+ /** The index a property key is on an array, or -1. */
3642
+ function arrayIndex(key) {
3643
+ if (typeof key === 'number') return (key >>> 0) === key && key !== 4294967295 ? key : -1;
3644
+ if (typeof key !== 'string') return -1;
3645
+ var number = +key;
3646
+ return (number >>> 0) === number && number !== 4294967295 && StringCtor(number) === key ? number : -1;
3647
+ }
3648
+
3649
+ /** ToPropertyKey, done once: what a member access makes of the key. */
3650
+ function propertyKey(key) {
3651
+ var type = typeof key;
3652
+ return type === 'string' || type === 'symbol' || type === 'number' ? key : StringCtor(key);
3653
+ }
3654
+
3655
+ /**
3656
+ * A write to an array through its length or through an index beyond its end: refused when it
3657
+ * would give the array more slots than the limit holds, and charged for the slots it adds
3658
+ * (the slots between the old end and the new one are part of what a built-in walks).
3659
+ * Returns the value to write: for the length, the number it was converted to, once.
3660
+ */
3661
+ function growing(target, key, value) {
3662
+ // The bound is checked whatever the array says its length is now: behind a proxy that is
3663
+ // not the array's own answer
3664
+ if (key === 'length') {
3665
+ var wanted = +value;
3666
+ checkLength(wanted, 'Array length');
3667
+ var before = target.length;
3668
+ if (wanted > before) charge(wanted - before);
3669
+ return wanted;
3670
+ }
3671
+ var index = arrayIndex(key);
3672
+ if (index >= 0) {
3673
+ checkLength(index + 1, 'Array index');
3674
+ var length = target.length;
3675
+ if (index >= length) charge(index + 1 - length);
3676
+ }
3677
+ return value;
3678
+ }
3679
+
3680
+ /** \`target[key] = value\`, with the key converted once and an array kept within the limit. */
3681
+ function guardedSet(target, key, value) {
3682
+ // The common write: a number that is inside the array. Nothing grows, nothing to convert.
3683
+ // (Not for an array behind a proxy a script made: the length it states is not the array's.)
3684
+ if (typeof key === 'number' && key >= 0 && isArray(target) && !(proxyMade && isScriptProxy(target)) && key < target.length) {
3685
+ target[key] = value;
3686
+ return value;
3687
+ }
3688
+ var k = propertyKey(key);
3689
+ if (limited && isArray(target)) {
3690
+ target[k] = growing(target, k, value);
3691
+ } else {
3692
+ target[k] = value;
3693
+ }
3694
+ return value;
3695
+ }
3696
+
3697
+ /**
3698
+ * What stands in for \`X[K]\` where it is written in another way than \`X[K] = V\` (a compound
3699
+ * assignment, \`++\`, a target in a destructuring pattern or in the head of a loop): an object
3700
+ * whose one member \`v\` reads and writes that slot, so the write is the guarded one.
3701
+ */
3702
+ function Slot(target, key) {
3703
+ this.t = target;
3704
+ this.k = propertyKey(key);
3705
+ }
3706
+ Slot.prototype = ObjectCtor.freeze(objectCreate(null, {
3707
+ v: {
3708
+ get: function () { return this.t[this.k]; },
3709
+ set: function (value) { guardedSet(this.t, this.k, value); },
3710
+ enumerable: false,
3711
+ configurable: false
3712
+ }
3713
+ }));
3714
+ function slot(target, key) {
3715
+ return new Slot(target, key);
3716
+ }
3717
+
3718
+ /**
3719
+ * The receiver of a built-in that reads its receiver by its length. An array is itself: its
3720
+ * length is its own, and it has no more slots than a script could give it. Anything else is
3721
+ * read here, once, into a plain array of the length it states, which is checked first. Null
3722
+ * for a receiver the built-in refuses by itself.
3723
+ */
3724
+ function walked(self, label) {
3725
+ if (isArray(self) && !(proxyMade && isScriptProxy(self))) return self;
3726
+ var receiver = toObject(self);
3727
+ if (receiver === null) return null;
3728
+ var length = toLength(receiver.length);
3729
+ checkLength(length, label);
3730
+ return snapshot(receiver, length, true);
3731
+ }
3732
+
3733
+ /**
3734
+ * Whether a built-in that moves the slots of its receiver can be given the receiver itself:
3735
+ * an array, or an object whose length is a number it holds (checked here) or that has none.
3736
+ * The built-in reads the length again, and such a length answers the same.
3737
+ */
3738
+ function movable(self, label) {
3739
+ if (!isObject(self) || ownArray(self)) return true;
3740
+ if (isScriptProxy(self)) return false;
3741
+ var held = getOwnPropertyDescriptor(self, 'length');
3742
+ if (held === undefined) return !('length' in self);
3743
+ if (!('value' in held) || typeof held.value !== 'number') return false;
3744
+ checkLength(toLength(held.value), label);
3745
+ return true;
3746
+ }
3747
+
3748
+ /**
3749
+ * A built-in that moves the slots of its receiver, applied to a receiver whose length is
3750
+ * computed (an accessor, an inherited length, a proxy a script made): the receiver is read
3751
+ * once into a plain array, the built-in works on that, and the result is written back.
3752
+ */
3753
+ function moveThroughCopy(original, self, given, label) {
3754
+ var length = toLength(self.length);
3755
+ checkLength(length, label);
3756
+ var copy = snapshot(self, length, true);
3757
+ var result = apply(original, copy, given);
3758
+ var after = copy.length;
3759
+ for (var i = 0; i < after; i++) {
3760
+ if (i in copy) guardedSet(self, i, copy[i]);
3761
+ else delete self[i];
3762
+ }
3763
+ for (var gone = after; gone < length; gone++) delete self[gone];
3764
+ guardedSet(self, 'length', after);
3765
+ return result === copy ? self : result;
3766
+ }
3767
+
3768
+ /** Rule 1, for a text: that many characters are not made. */
3769
+ function checkText(characters, label) {
3770
+ if (limited && characters * 2 > memoryLimit) refuse(label, characters * 2);
3771
+ }
3772
+
3773
+ function patch(holder, name, make) {
3774
+ var original = holder[name];
3775
+ if (typeof original !== 'function') return;
3776
+ var replacement = make(original);
3777
+ // The replacement answers for its name and its number of parameters like the built-in
3778
+ try {
3779
+ defineProperty(replacement, 'name', { value: name, writable: false, enumerable: false, configurable: true });
3780
+ defineProperty(replacement, 'length', { value: original.length, writable: false, enumerable: false, configurable: true });
3781
+ } catch (e) { /* left as it is */ }
3782
+ try {
3783
+ defineProperty(holder, name, { value: replacement, writable: true, enumerable: false, configurable: true });
3784
+ } catch (e) {
3785
+ cannotInstall(name);
3786
+ }
3787
+ }
3788
+
3789
+ if (limited) {
3790
+ // push, unshift: every argument is a new element
3791
+ patch(arrayProto, 'push', function (original) {
3792
+ return function push() {
3793
+ charge(arguments.length);
3794
+ return apply(original, this, arguments);
3795
+ };
3796
+ });
3797
+ // The global Array, once it is the guarded one (see the end of this block)
3798
+ var guardedArray = null;
3799
+ patch(arrayProto, 'unshift', function (original) {
3800
+ return function unshift() {
3801
+ charge(arguments.length);
3802
+ if (!movable(this, 'Array.unshift')) return moveThroughCopy(original, this, arguments, 'Array.unshift');
3803
+ return apply(original, this, arguments);
3804
+ };
3805
+ });
3806
+ // splice: the arguments after the first two are inserted
3807
+ patch(arrayProto, 'splice', function (original) {
3808
+ return function splice() {
3809
+ if (arguments.length > 2) charge(arguments.length - 2);
3810
+ if (!movable(this, 'Array.splice')) return moveThroughCopy(original, this, arguments, 'Array.splice');
3811
+ return apply(original, this, arguments);
3812
+ };
3813
+ });
3814
+ // concat: the result has, for the receiver and each argument, its elements or itself. It
3815
+ // is built here, in the pass that counts it and in the order the built-in works: each value
3816
+ // is asked once whether it is spread (the language's symbol for it, otherwise whether it
3817
+ // is an array), a value that is spread is asked once for its length and once for each
3818
+ // slot, and the count is checked before the slots are copied. The built-in does not run.
3819
+ // It would ask every value again, and what answers can be code of the script (an accessor
3820
+ // on an array, the constructor of the receiver's kind): an array that was counted could
3821
+ // hold more by the time the built-in copies it, as often as it is named.
3822
+ function copySlots(target, at, source, length) {
3823
+ // A slot that is not there stays empty in the result
3824
+ for (var k = 0; k < length; k++) {
3825
+ if (k in source) target[at + k] = source[k];
3826
+ }
3827
+ }
3828
+ patch(arrayProto, 'concat', function (original) {
3829
+ return function concat() {
3830
+ var receiver = toObject(this);
3831
+ if (receiver === null) return apply(original, this, arguments);
3832
+ // The result is of the receiver's kind, and is made first, as in the built-in
3833
+ var ofKind = emptyOfKind(receiver);
3834
+ var plain = ofKind === null;
3835
+ var target = plain ? [] : ofKind;
3836
+ if (plain) {
3837
+ // A first size for the result, so that it is not made in steps: what the arrays
3838
+ // among the values hold now. It decides nothing. Every value is asked and counted
3839
+ // below, and the result ends with the length that was counted.
3840
+ var expected = 0;
3841
+ for (var e = -1; e < arguments.length; e++) {
3842
+ var one = e < 0 ? receiver : arguments[e];
3843
+ expected += ownArray(one) ? one.length : 1;
3844
+ }
3845
+ if (expected * BYTES <= memoryLimit) target.length = expected;
3846
+ }
3847
+ var count = 0;
3848
+ var own = 0;
3849
+ for (var i = -1; i < arguments.length; i++) {
3850
+ var item = i < 0 ? receiver : arguments[i];
3851
+ var spread = false;
3852
+ if (isObject(item)) {
3853
+ var flag = item[spreadableSymbol];
3854
+ spread = flag === undefined ? isArray(item) : !!flag;
3855
+ }
3856
+ if (!spread) {
3857
+ checkLength(count + 1, 'Array.concat');
3858
+ if (plain) {
3859
+ target[count] = item;
3860
+ } else {
3861
+ defineProperty(target, count, { value: item, writable: true, enumerable: true, configurable: true });
3862
+ }
3863
+ count++;
3864
+ continue;
3865
+ }
3866
+ var length = toLength(item.length);
3867
+ checkLength(count + length, 'Array.concat');
3868
+ if (i < 0 && ownArray(item)) own = length;
3869
+ if (plain) {
3870
+ copySlots(target, count, item, length);
3871
+ } else {
3872
+ for (var k = 0; k < length; k++) {
3873
+ if (!(k in item)) continue;
3874
+ defineProperty(target, count + k, { value: item[k], writable: true, enumerable: true, configurable: true });
3875
+ }
3876
+ }
3877
+ count += length;
3878
+ }
3879
+ target.length = count;
3880
+ charge(count - own);
3881
+ return target;
3882
+ };
3883
+ });
3884
+
3885
+ // flat: the result is built here, in the pass that counts it, to the depth the built-in
3886
+ // flattens. Each slot is asked once (is it there, what is it) and each nested array for its
3887
+ // length once, so what is counted is what the result is made of. The pass walks the nesting
3888
+ // with a list of its own, so the depth of the nesting is not the depth of a call stack, and
3889
+ // it stops at the limit: by the slots counted so far, and by the arrays entered (an array
3890
+ // of empty arrays has nothing to count and everything to visit).
3891
+ function flatten(root, rootLength, levels, target, plain) {
3892
+ var budget = memoryLimit / BYTES;
3893
+ var slots = rootLength;
3894
+ var entered = 0;
3895
+ if (slots > budget) refuse('Array.flat', slots * BYTES);
3896
+ var sources = [root];
3897
+ var lengths = [rootLength];
3898
+ var depths = [levels];
3899
+ var next = [0];
3900
+ var top = 0;
3901
+ var count = 0;
3902
+ while (top >= 0) {
3903
+ var index = next[top];
3904
+ if (index >= lengths[top]) {
3905
+ top--;
3906
+ continue;
3907
+ }
3908
+ next[top] = index + 1;
3909
+ var source = sources[top];
3910
+ // A slot that is not there is left out, as in the built-in
3911
+ if (!(index in source)) continue;
3912
+ var item = source[index];
3913
+ if (depths[top] >= 1 && isArray(item)) {
3914
+ // The slot gives way to what the array holds
3915
+ var length = toLength(item.length);
3916
+ slots += length - 1;
3917
+ entered++;
3918
+ if (slots > budget || entered > budget) {
3919
+ refuse('Array.flat', (slots > entered ? slots : entered) * BYTES);
3920
+ }
3921
+ top++;
3922
+ sources[top] = item;
3923
+ lengths[top] = length;
3924
+ depths[top] = depths[top - 1] - 1;
3925
+ next[top] = 0;
3926
+ continue;
3927
+ }
3928
+ if (plain) {
3929
+ target[count] = item;
3930
+ } else {
3931
+ defineProperty(target, count, { value: item, writable: true, enumerable: true, configurable: true });
3932
+ }
3933
+ count++;
3934
+ }
3935
+ return count;
3936
+ }
3937
+ patch(arrayProto, 'flat', function (original) {
3938
+ return function flat(depth) {
3939
+ var receiver = toObject(this);
3940
+ if (receiver === null) return apply(original, this, arguments);
3941
+ var length = toLength(receiver.length);
3942
+ var levels = depth === undefined ? 1 : toInteger(depth);
3943
+ if (levels < 0) levels = 0;
3944
+ var ofKind = emptyOfKind(receiver);
3945
+ var target = ofKind === null ? [] : ofKind;
3946
+ var count = flatten(receiver, length, levels, target, ofKind === null);
3947
+ charge(count - (isArray(receiver) ? length : 0));
3948
+ return target;
3949
+ };
3950
+ });
3951
+ // flatMap: what the callback hands back is counted as it comes
3952
+ patch(arrayProto, 'flatMap', function (original) {
3953
+ return function flatMap(callback, thisArg) {
3954
+ if (typeof callback !== 'function') return apply(original, this, arguments);
3955
+ var receiver = walked(this, 'Array.flatMap');
3956
+ if (receiver === null) return apply(original, this, arguments);
3957
+ var produced = 0;
3958
+ var result = apply(original, receiver, [function (value, index, array) {
3959
+ var item = apply(callback, this, [value, index, array]);
3960
+ if (isScriptProxy(item) && isArray(item)) {
3961
+ // An array behind a proxy a script made: the built-in gets what was counted
3962
+ var length = toLength(item.length);
3963
+ produced += length;
3964
+ checkLength(produced, 'Array.flatMap');
3965
+ return snapshot(item, length, true);
3966
+ }
3967
+ produced += isArray(item) ? item.length : 1;
3968
+ checkLength(produced, 'Array.flatMap');
3969
+ return item;
3970
+ }, thisArg]);
3971
+ charge(lengthOf(result) - lengthOf(this));
3972
+ return result;
3973
+ };
3974
+ });
3975
+ // The copying methods turn every slot of the receiver into an element, holes included.
3976
+ // Of something that is not an array they get a plain copy, of the length that was checked.
3977
+ var copying = ['toSorted', 'toReversed', 'toSpliced', 'with'];
3978
+ for (var c = 0; c < copying.length; c++) {
3979
+ (function (name) {
3980
+ patch(arrayProto, name, function (original) {
3981
+ return function () {
3982
+ var receiver = toObject(this);
3983
+ if (receiver === null) return apply(original, this, arguments);
3984
+ var length = toLength(receiver.length);
3985
+ var array = ownArray(receiver);
3986
+ // The copy that is made of something that is not an array has its length
3987
+ if (!array) checkLength(length, 'Array.' + name);
3988
+ var given = arguments;
3989
+ if (name === 'toSpliced') {
3990
+ // The result has the receiver's slots, less the ones skipped, plus the ones
3991
+ // inserted: worked out here by the built-in's rules, and the built-in gets the
3992
+ // two numbers
3993
+ var start = relativeIndex(arguments[0], length, 0);
3994
+ var skip = arguments.length === 0 ? 0 : arguments.length === 1 ? length - start : toInteger(arguments[1]);
3995
+ if (skip < 0) skip = 0;
3996
+ if (skip > length - start) skip = length - start;
3997
+ var inserted = arguments.length > 2 ? arguments.length - 2 : 0;
3998
+ checkLength(length + inserted - skip, 'Array.toSpliced');
3999
+ given = [start, skip];
4000
+ for (var g = 2; g < arguments.length; g++) given[g] = arguments[g];
4001
+ } else {
4002
+ checkLength(length, 'Array.' + name);
4003
+ }
4004
+ return apply(original, array ? receiver : snapshot(receiver, length, false), given);
4005
+ };
4006
+ });
4007
+ })(copying[c]);
4008
+ }
4009
+ // Array.from. Of something with a length: that many elements, whatever is behind it. Of
4010
+ // something that is iterated: as many as it yields, so the built-in is stopped at the
4011
+ // limit by the mapping function it calls for each element. Which of the two it is, is
4012
+ // decided here, once, for an array as for anything else: the built-in is given a source
4013
+ // that can only be read that way.
4014
+ patch(ArrayCtor, 'from', function (original) {
4015
+ return function from(items, mapFn, thisArg) {
4016
+ // What the built-in refuses by itself, it refuses before it makes anything
4017
+ if (items === null || items === undefined) return apply(original, this, arguments);
4018
+ if (mapFn !== undefined && typeof mapFn !== 'function') return apply(original, this, arguments);
4019
+
4020
+ var source = items;
4021
+ var iterate = items[iteratorSymbol];
4022
+ if (iterate === undefined || iterate === null) {
4023
+ var receiver = toObject(items);
4024
+ var length = toLength(receiver.length);
4025
+ checkLength(length, 'Array.from');
4026
+ source = slotsOf(receiver, length);
4027
+ } else if (typeof iterate !== 'function') {
4028
+ // What the built-in answers for an iterator that cannot be called: answered here, so
4029
+ // that it is not asked a second time
4030
+ throw new TypeErrorCtor('Array.from: the iterator of the source is not a function');
4031
+ } else if (isObject(items)) {
4032
+ var held = {};
4033
+ held[iteratorSymbol] = { value: function () { return apply(iterate, items, []); } };
4034
+ source = objectCreate(null, held);
4035
+ }
4036
+
4037
+ var produced = 0;
4038
+ var mapped = mapFn !== undefined;
4039
+ // The guarded Array stands for the built-in one: what is made here is counted here
4040
+ var result = apply(original, this === guardedArray ? ArrayCtor : this, [source, function (value, index) {
4041
+ produced++;
4042
+ if (produced * BYTES > memoryLimit) refuse('Array.from', produced * BYTES);
4043
+ return mapped ? apply(mapFn, this, [value, index]) : value;
4044
+ }, thisArg]);
4045
+ checkLength(lengthOf(result), 'Array.from');
4046
+ if (!isArray(items)) charge(lengthOf(result));
4047
+ return result;
4048
+ };
4049
+ });
4050
+
4051
+ // fill: the range is worked out here, by the built-in's rules, checked and charged, and
4052
+ // the built-in gets the range as two numbers. Something that is not an array is filled
4053
+ // here: the built-in would read its length again.
4054
+ patch(arrayProto, 'fill', function (original) {
4055
+ return function fill(value, start, end) {
4056
+ if (!isObject(this)) return apply(original, this, arguments);
4057
+ var array = ownArray(this);
4058
+ var length = array ? this.length : toLength(this.length);
4059
+ var from = relativeIndex(start, length, 0);
4060
+ var to = relativeIndex(end, length, length);
4061
+ var count = to > from ? to - from : 0;
4062
+ checkLength(count, 'Array.fill');
4063
+ if (array) {
4064
+ // The slots of an array were charged when it got them
4065
+ return apply(original, this, [value, from, to]);
4066
+ }
4067
+ charge(count);
4068
+ for (var i = from; i < to; i++) {
4069
+ this[i] = value;
4070
+ }
4071
+ return this;
4072
+ };
4073
+ });
4074
+
4075
+ // Every other built-in that works through its receiver by its length. One call into such a
4076
+ // built-in is finished by the engine, however long the length says the receiver is: the
4077
+ // deadline is not looked at inside it. So none of them is given a length above what an
4078
+ // array may have, whether the receiver is an array with that many slots (most of them
4079
+ // empty) or an object that states the length.
4080
+ var reading = [
4081
+ 'indexOf', 'lastIndexOf', 'includes', 'forEach', 'map', 'filter', 'some', 'every', 'reduce',
4082
+ 'reduceRight', 'find', 'findIndex', 'findLast', 'findLastIndex', 'slice', 'keys', 'values', 'entries'
4083
+ ];
4084
+ for (var r = 0; r < reading.length; r++) {
4085
+ (function (name) {
4086
+ var label = 'Array.' + name;
4087
+ patch(arrayProto, name, function (original) {
4088
+ return function () {
4089
+ var receiver = walked(this, label);
4090
+ return apply(original, receiver === null ? this : receiver, arguments);
4091
+ };
4092
+ });
4093
+ })(reading[r]);
4094
+ }
4095
+ var moving = ['reverse', 'sort', 'copyWithin', 'shift'];
4096
+ for (var m = 0; m < moving.length; m++) {
4097
+ (function (name) {
4098
+ var label = 'Array.' + name;
4099
+ patch(arrayProto, name, function (original) {
4100
+ return function () {
4101
+ if (!movable(this, label)) return moveThroughCopy(original, this, arguments, label);
4102
+ return apply(original, this, arguments);
4103
+ };
4104
+ });
4105
+ })(moving[m]);
4106
+ }
4107
+
4108
+ // The other ways to write to an array. Each is the guarded write, or checked like it.
4109
+ patch(ObjectCtor, 'assign', function (original) {
4110
+ return function assign(target) {
4111
+ if (!isArray(target)) return apply(original, this, arguments);
4112
+ for (var s = 1; s < arguments.length; s++) {
4113
+ var source = arguments[s];
4114
+ if (source === null || source === undefined) continue;
4115
+ var from = ObjectCtor(source);
4116
+ var keys = ownKeys(from);
4117
+ for (var i = 0; i < keys.length; i++) {
4118
+ var held = getOwnPropertyDescriptor(from, keys[i]);
4119
+ if (held !== undefined && held.enumerable) guardedSet(target, keys[i], from[keys[i]]);
4120
+ }
4121
+ }
4122
+ return target;
4123
+ };
4124
+ });
4125
+ // A descriptor, read once: the built-in reads its members again
4126
+ var descriptorMembers = ['enumerable', 'configurable', 'value', 'writable', 'get', 'set'];
4127
+ function pinned(descriptor) {
4128
+ if (!isObject(descriptor)) return descriptor;
4129
+ var copy = objectCreate(null);
4130
+ for (var d = 0; d < descriptorMembers.length; d++) {
4131
+ if (descriptorMembers[d] in descriptor) copy[descriptorMembers[d]] = descriptor[descriptorMembers[d]];
4132
+ }
4133
+ return copy;
4134
+ }
4135
+ // The key and the descriptor a definition on an array is made with
4136
+ function definition(target, key, descriptor) {
4137
+ var k = propertyKey(key);
4138
+ var copy = pinned(descriptor);
4139
+ if (isObject(copy)) {
4140
+ if (k !== 'length') growing(target, k, undefined);
4141
+ else if ('value' in copy) copy.value = growing(target, k, copy.value);
4142
+ }
4143
+ return [target, k, copy];
4144
+ }
4145
+ var defineOne = ObjectCtor.defineProperty;
4146
+ patch(ObjectCtor, 'defineProperty', function (original) {
4147
+ return function defineProperty(target, key, descriptor) {
4148
+ if (!isArray(target)) return apply(original, this, arguments);
4149
+ return apply(original, this, definition(target, key, descriptor));
4150
+ };
4151
+ });
4152
+ patch(ObjectCtor, 'defineProperties', function (original) {
4153
+ return function defineProperties(target, properties) {
4154
+ if (!isArray(target) || properties === null || properties === undefined) return apply(original, this, arguments);
4155
+ var from = ObjectCtor(properties);
4156
+ var keys = ownKeys(from);
4157
+ for (var i = 0; i < keys.length; i++) {
4158
+ var held = getOwnPropertyDescriptor(from, keys[i]);
4159
+ if (held !== undefined && held.enumerable) apply(defineOne, ObjectCtor, definition(target, keys[i], from[keys[i]]));
4160
+ }
4161
+ return target;
4162
+ };
4163
+ });
4164
+ if (typeof Reflect === 'object' && Reflect !== null) {
4165
+ patch(Reflect, 'defineProperty', function (original) {
4166
+ return function defineProperty(target, key, descriptor) {
4167
+ if (!isArray(target)) return apply(original, this, arguments);
4168
+ return apply(original, this, definition(target, key, descriptor));
4169
+ };
4170
+ });
4171
+ patch(Reflect, 'set', function (original) {
4172
+ return function set(target, key, value, receiver) {
4173
+ // The write lands on the receiver, which is the target unless one is given
4174
+ var landing = arguments.length > 3 ? receiver : target;
4175
+ if (!isArray(landing)) return apply(original, this, arguments);
4176
+ var k = propertyKey(key);
4177
+ var written = growing(landing, k, value);
4178
+ return apply(original, this, arguments.length > 3 ? [target, k, written, receiver] : [target, k, written]);
4179
+ };
4180
+ });
4181
+ }
4182
+ var legacy = ['__defineGetter__', '__defineSetter__'];
4183
+ for (var l = 0; l < legacy.length; l++) {
4184
+ (function (name) {
4185
+ patch(ObjectCtor.prototype, name, function (original) {
4186
+ return function (key, accessor) {
4187
+ if (!isArray(this)) return apply(original, this, arguments);
4188
+ var k = propertyKey(key);
4189
+ growing(this, k, undefined);
4190
+ return apply(original, this, [k, accessor]);
4191
+ };
4192
+ });
4193
+ })(legacy[l]);
4194
+ }
4195
+
4196
+ // Array(n) and new Array(n) make n slots: checked and charged like every other way to get
4197
+ // them. The global is put behind a proxy for that (made here, while the realm still has
4198
+ // the means), so it holds for every way to call it; \`Array.prototype.constructor\` stays the
4199
+ // built-in, which the results of the built-ins are made with.
4200
+ patch(ArrayCtor, 'of', function (original) {
4201
+ return function of() {
4202
+ return apply(original, this === guardedArray ? ArrayCtor : this, arguments);
4203
+ };
4204
+ });
4205
+ // (Without a Proxy constructor in the realm there is nothing to put the global behind.)
4206
+ if (ProxyCtor === undefined) cannotInstall('Array');
4207
+ {
4208
+ var slotsFor = function (given) {
4209
+ if (given.length === 1 && typeof given[0] === 'number') {
4210
+ checkLength(given[0], 'Array');
4211
+ charge(given[0]);
4212
+ } else {
4213
+ checkLength(given.length, 'Array');
4214
+ }
4215
+ };
4216
+ // (A handler without a prototype: the traps of the stand-in are these two and no other)
4217
+ var arrayTraps = objectCreate(null);
4218
+ arrayTraps.apply = function (target, self, given) {
4219
+ slotsFor(given);
4220
+ return apply(target, self, given);
4221
+ };
4222
+ arrayTraps.construct = function (target, given, newTarget) {
4223
+ slotsFor(given);
4224
+ return construct(target, given, newTarget);
4225
+ };
4226
+ guardedArray = new ProxyCtor(ArrayCtor, arrayTraps);
4227
+ try {
4228
+ defineProperty(globalThis, 'Array', { value: guardedArray, writable: true, enumerable: false, configurable: true });
4229
+ } catch (e) {
4230
+ cannotInstall('Array');
4231
+ }
4232
+ }
4233
+
4234
+ // Array.fromAsync: like Array.from. How the source is read is decided here, once, and what
4235
+ // it yields is counted as it comes. The built-in answers every failure with a promise that
4236
+ // is rejected, never with an error at the call. So an iterator that cannot be called is
4237
+ // handed on as the value it is, and an error the source raises while it is read here is
4238
+ // kept and raised again by the source the built-in is given: the answer is the built-in's
4239
+ // own, and the source is not asked a second time. The limit's refusal is not an answer of
4240
+ // the built-in: it ends the call.
4241
+ patch(ArrayCtor, 'fromAsync', function (original) {
4242
+ return function fromAsync(items, mapFn, thisArg) {
4243
+ if (items === null || items === undefined) return apply(original, this, arguments);
4244
+ if (mapFn !== undefined && typeof mapFn !== 'function') return apply(original, this, arguments);
4245
+ var source;
4246
+ var receiver;
4247
+ var length = -1;
4248
+ var failed = false;
4249
+ var failure;
4250
+ try {
4251
+ var iterate = asyncIteratorSymbol === undefined ? undefined : items[asyncIteratorSymbol];
4252
+ var symbol = asyncIteratorSymbol;
4253
+ if (iterate === undefined || iterate === null) {
4254
+ iterate = items[iteratorSymbol];
4255
+ symbol = iteratorSymbol;
4256
+ }
4257
+ if (iterate === undefined || iterate === null) {
4258
+ receiver = toObject(items);
4259
+ length = toLength(receiver.length);
4260
+ } else {
4261
+ var held = {};
4262
+ held[symbol] = {
4263
+ value: typeof iterate === 'function' ? function () { return apply(iterate, items, []); } : iterate
4264
+ };
4265
+ source = objectCreate(null, held);
4266
+ }
4267
+ } catch (error) {
4268
+ failed = true;
4269
+ failure = error;
4270
+ }
4271
+ if (!failed && length >= 0) {
4272
+ checkLength(length, 'Array.fromAsync');
4273
+ source = slotsOf(receiver, length);
4274
+ }
4275
+ if (failed) {
4276
+ var raising = {};
4277
+ raising[asyncIteratorSymbol === undefined ? iteratorSymbol : asyncIteratorSymbol] = {
4278
+ get: function () { throw failure; }
4279
+ };
4280
+ source = objectCreate(null, raising);
4281
+ }
4282
+ var produced = 0;
4283
+ var mapped = mapFn !== undefined;
4284
+ return apply(original, this === guardedArray ? ArrayCtor : this, [source, function (value, index) {
4285
+ produced++;
4286
+ if (produced * BYTES > memoryLimit) refuse('Array.fromAsync', produced * BYTES);
4287
+ charge(1);
4288
+ return mapped ? apply(mapFn, this, [value, index]) : value;
4289
+ }, thisArg]);
4290
+ };
4291
+ });
4292
+
4293
+ // join and toLocaleString: each item is converted to its text here, once, the texts are
4294
+ // counted as they come, and the built-in joins the texts.
4295
+ var joining = [];
4296
+ function textsOf(receiver, length, separatorLength, label, convert) {
4297
+ // The list of the texts is an array of that length
4298
+ checkLength(length, label);
4299
+ var texts = [];
4300
+ var characters = 0;
4301
+ for (var i = 0; i < length; i++) {
4302
+ var item = receiver[i];
4303
+ var text = (item === undefined || item === null) ? '' : convert(item);
4304
+ texts[i] = text;
4305
+ characters += text.length + (i > 0 ? separatorLength : 0);
4306
+ checkText(characters, label);
4307
+ }
4308
+ return texts;
4309
+ }
4310
+ function joined(receiver, label, separator, convert, join) {
4311
+ var array = isArray(receiver);
4312
+ var length = array ? receiver.length : toLength(receiver.length);
4313
+ // An array that contains itself contributes nothing the second time, as in the built-in
4314
+ for (var j = 0; j < joining.length; j++) {
4315
+ if (joining[j] === receiver) return '';
4316
+ }
4317
+ joining[joining.length] = receiver;
4318
+ var texts;
4319
+ try {
4320
+ texts = textsOf(receiver, length, separator.length, label, convert);
4321
+ } finally {
4322
+ joining.length = joining.length - 1;
4323
+ }
4324
+ return apply(join, texts, [separator]);
4325
+ }
4326
+ var joinBefore = arrayProto.join;
4327
+ patch(arrayProto, 'join', function (previous) {
4328
+ return function join(separator) {
4329
+ if (!isObject(this)) return apply(previous, this, arguments);
4330
+ var between = separator === undefined ? ',' : toText(separator);
4331
+ return joined(this, 'Array.join', between, toText, previous);
4332
+ };
4333
+ });
4334
+ patch(arrayProto, 'toLocaleString', function (previous) {
4335
+ return function toLocaleString(locales, options) {
4336
+ if (!isObject(this) || typeof joinBefore !== 'function') return apply(previous, this, arguments);
4337
+ return joined(this, 'Array.toLocaleString', ',', function (item) {
4338
+ return toText(item.toLocaleString(locales, options));
4339
+ }, joinBefore);
4340
+ };
4341
+ });
4342
+
4343
+ // repeat, padStart, padEnd: the receiver and the count are converted here, once
4344
+ patch(stringProto, 'repeat', function (previous) {
4345
+ return function repeat(count) {
4346
+ if (this === null || this === undefined) return apply(previous, this, arguments);
4347
+ return apply(previous, toText(this), [toInteger(count)]);
4348
+ };
4349
+ });
4350
+ var padding = ['padStart', 'padEnd'];
4351
+ for (var p = 0; p < padding.length; p++) {
4352
+ (function (name) {
4353
+ patch(stringProto, name, function (previous) {
4354
+ return function (targetLength, padString) {
4355
+ if (this === null || this === undefined) return apply(previous, this, arguments);
4356
+ return apply(previous, toText(this), [toLength(targetLength), padString === undefined ? undefined : toText(padString)]);
4357
+ };
4358
+ });
4359
+ })(padding[p]);
4360
+ }
4361
+ }
4362
+
4363
+ // An array literal with spreads: [a, ...b, ...c] is compiled to
4364
+ // __safe_array(__safe_arrayStart(), [a, ...__safe_spread(b), ...__safe_spread(c)])
4365
+ // so that each source is seen before it is spread and the result when it exists.
4366
+ var frames = [];
4367
+ var nextId = 1;
4368
+
4369
+ function arrayStart() {
4370
+ // A literal that threw before it was finished leaves its frame; they are small, and gone
4371
+ // with the next literal that finishes below them or once there are too many.
4372
+ if (frames.length > 1024) frames.length = 0;
4373
+ var frame = { id: nextId++, total: 0, largest: 0 };
4374
+ frames[frames.length] = frame;
4375
+ return frame.id;
4376
+ }
4377
+
4378
+ function spread(source) {
4379
+ var frame = frames.length > 0 ? frames[frames.length - 1] : null;
4380
+ if (ownArray(source) || typeof source === 'string') {
4381
+ // An array, or a text (which yields at most as many items as it has characters): its
4382
+ // size is known before it is spread
4383
+ var length = source.length;
4384
+ checkLength(length, 'Array spread');
4385
+ if (frame) {
4386
+ frame.total += length;
4387
+ if (typeof source !== 'string' && length > frame.largest) frame.largest = length;
4388
+ checkLength(frame.total, 'Array spread');
4389
+ }
4390
+ return source;
4391
+ }
4392
+ if (!limited || source === null || source === undefined) return source;
4393
+ // Anything else that is iterated yields as many items as it likes: it is spread through an
4394
+ // iterator that counts them as they come, so the literal is stopped at the limit and not
4395
+ // measured when it exists. The iterator is asked for once, and each step is read once.
4396
+ var iterate = source[iteratorSymbol];
4397
+ if (typeof iterate !== 'function') return source;
4398
+ var counted = {};
4399
+ counted[iteratorSymbol] = {
4400
+ value: function () {
4401
+ var iterator = apply(iterate, source, []);
4402
+ if (!isObject(iterator)) throw new TypeErrorCtor('Result of the Symbol.iterator method is not an object');
4403
+ var next = iterator.next;
4404
+ return {
4405
+ next: function () {
4406
+ var step = apply(next, iterator, []);
4407
+ if (!isObject(step)) throw new TypeErrorCtor('Iterator result is not an object');
4408
+ if (step.done) return { done: true, value: undefined };
4409
+ if (frame) {
4410
+ frame.total += 1;
4411
+ checkLength(frame.total, 'Array spread');
4412
+ }
4413
+ return { done: false, value: step.value };
4414
+ },
4415
+ return: function (value) {
4416
+ var close = iterator.return;
4417
+ return typeof close === 'function' ? apply(close, iterator, [value]) : { done: true, value: value };
4418
+ }
4419
+ };
4420
+ }
4421
+ };
4422
+ return objectCreate(null, counted);
4423
+ }
4424
+
4425
+ function arrayFinish(id, array) {
4426
+ var largest = 0;
4427
+ for (var i = frames.length - 1; i >= 0; i--) {
4428
+ if (frames[i].id === id) {
4429
+ largest = frames[i].largest;
4430
+ frames.length = i;
4431
+ break;
4432
+ }
4433
+ }
4434
+ if (isArray(array)) {
4435
+ checkLength(array.length, 'Array spread');
4436
+ charge(array.length - largest);
4437
+ }
4438
+ return array;
4439
+ }
4440
+
4441
+ var helpers = [[${JSON.stringify(ARRAY_START_FN)}, arrayStart], [${JSON.stringify(ARRAY_SPREAD_FN)}, spread], [${JSON.stringify(
4442
+ ARRAY_FINISH_FN
4443
+ )}, arrayFinish], [${JSON.stringify(ARRAY_SET_FN)}, guardedSet], [${JSON.stringify(ARRAY_SLOT_FN)}, slot]];
4444
+ for (var h = 0; h < helpers.length; h++) {
4445
+ defineProperty(globalThis, helpers[h][0], {
4446
+ value: helpers[h][1],
4447
+ writable: false,
4448
+ configurable: false,
4449
+ enumerable: false
4450
+ });
4451
+ }
4452
+ })(${numericLiteral("memoryLimit", memoryLimit)}, (typeof __host_memory_track__ === 'function') ? __host_memory_track__ : null);
4453
+ `.trim();
4454
+ }
4455
+
4456
+ // libs/core/src/double-vm/parent-vm-bootstrap.ts
4457
+ var MEMBRANE_MAX_RECURSION_DEPTH = 256;
4458
+ var NODEJS_24_DANGEROUS_GLOBALS = {
4459
+ STRICT: [
4460
+ // Code execution - CRITICAL
4461
+ "Function",
4462
+ // Constructor for functions - primary escape vector
4463
+ "eval",
4464
+ // Direct code execution
4465
+ "globalThis",
4466
+ // Indirect access to all globals
4467
+ // Metaprogramming - sandbox escape vectors
4468
+ "Proxy",
4469
+ // Can intercept all operations
4470
+ "Reflect",
4471
+ // Metaprogramming primitive
4472
+ // Memory/timing attacks
4473
+ "SharedArrayBuffer",
4474
+ // Spectre/timing attacks
4475
+ "Atomics",
4476
+ // Shared memory operations
4477
+ "gc",
4478
+ // Force garbage collection (shouldn't be exposed)
4479
+ // Future/experimental APIs
4480
+ "Iterator",
4481
+ // Iterator helpers
4482
+ "AsyncIterator",
4483
+ // Async iterator helpers
4484
+ "ShadowRealm",
4485
+ // New realm creation (major escape risk)
4486
+ "WeakRef",
4487
+ // Can observe GC behavior
4488
+ "FinalizationRegistry",
4489
+ // Can observe GC behavior
4490
+ "performance",
4491
+ // Timing information
4492
+ "Temporal"
4493
+ // New date/time API
4494
+ ],
4495
+ SECURE: [
4496
+ // Code execution - CRITICAL
4497
+ "Function",
4498
+ "eval",
4499
+ "globalThis",
4500
+ // Most dangerous metaprogramming
4501
+ "Proxy",
4502
+ // Memory/timing attacks
4503
+ "SharedArrayBuffer",
4504
+ "Atomics",
4505
+ "gc",
4506
+ // Future APIs
4507
+ "Iterator",
4508
+ "AsyncIterator",
4509
+ "ShadowRealm",
4510
+ "WeakRef",
4511
+ "FinalizationRegistry"
4512
+ ],
4513
+ STANDARD: [
4514
+ // Code execution - always block these
4515
+ "Function",
4516
+ "eval",
4517
+ // Memory/timing attacks
4518
+ "SharedArrayBuffer",
4519
+ "Atomics",
4520
+ "gc",
4521
+ // Definitely dangerous
4522
+ "ShadowRealm",
4523
+ "WeakRef",
4524
+ "FinalizationRegistry"
4525
+ ],
4526
+ PERMISSIVE: [
4527
+ // Even PERMISSIVE should block the most dangerous
4528
+ "ShadowRealm",
4529
+ // Too dangerous to allow
4530
+ "gc",
4531
+ // Shouldn't be exposed at all
4532
+ "SharedArrayBuffer",
4533
+ // Spectre risk
4534
+ "Atomics"
4535
+ // Goes with SharedArrayBuffer
4536
+ ]
4537
+ };
4538
+ var INNER_REALM_SCRUB_SOURCE = `
4539
+ (function () {
4540
+ 'use strict';
4541
+ var global = globalThis;
4542
+ var getOwnPropertyNames = Object.getOwnPropertyNames;
4543
+ var getOwnPropertySymbols = Object.getOwnPropertySymbols;
4544
+ var getPrototypeOf = Object.getPrototypeOf;
4545
+ var setPrototypeOf = Object.setPrototypeOf;
4546
+
4547
+ return function scrub(remove, keep) {
4548
+ var kept = { __proto__: null };
4549
+ var i;
4550
+ var j;
4551
+ for (i = 0; i < keep.length; i++) kept[keep[i]] = true;
4552
+
4553
+ var targets = [];
4554
+ if (remove) {
2962
4555
  for (i = 0; i < remove.length; i++) targets[targets.length] = remove[i];
2963
4556
  } else {
2964
4557
  var names = getOwnPropertyNames(global);
@@ -3601,6 +5194,18 @@ function generateParentVmBootstrap(options) {
3601
5194
  toolNamespaces = [],
3602
5195
  realmGlobalAllowlist
3603
5196
  } = options;
5197
+ numericLiteral("innerTimeout", innerTimeout);
5198
+ numericLiteral("maxIterations", maxIterations);
5199
+ numericLiteral("maxToolCalls", maxToolCalls);
5200
+ numericLiteral("toolBridgeMaxPayloadBytes", toolBridgeMaxPayloadBytes);
5201
+ numericLiteral("memoryLimit", memoryLimit);
5202
+ numericLiteral("maxGlobalFunctionCalls", maxGlobalFunctionCalls);
5203
+ booleanLiteral("sanitizeStackTraces", sanitizeStackTraces);
5204
+ booleanLiteral("allowComposites", allowComposites);
5205
+ booleanLiteral("throwOnBlocked", throwOnBlocked);
5206
+ if (toolBridgeMode !== "string" && toolBridgeMode !== "direct") {
5207
+ throw new TypeError(`Invalid toolBridgeMode: ${String(toolBridgeMode)}`);
5208
+ }
3604
5209
  const hasRealmAllowlist = Array.isArray(realmGlobalAllowlist);
3605
5210
  const realmAllowedNames = hasRealmAllowlist ? [
3606
5211
  .../* @__PURE__ */ new Set([
@@ -3795,6 +5400,9 @@ function generateParentVmBootstrap(options) {
3795
5400
  // source with the sources of the same length it still holds, character by character.
3796
5401
  var userCode = ${asciiStringLiteral(userCode)};
3797
5402
 
5403
+ // This realm captures no stack traces (see ../realm-stack). First, before any error is made.
5404
+ ${STACK_CAPTURE_OFF_SOURCE}
5405
+
3798
5406
  // Get injected references from host
3799
5407
  const vm = __host_vm_module__;
3800
5408
  const hostCallTool = __host_callTool__;
@@ -3807,6 +5415,9 @@ function generateParentVmBootstrap(options) {
3807
5415
  const hostIsBuiltinMethod = typeof __host_isBuiltinMethod__ === 'function' ? __host_isBuiltinMethod__ : function() { return false; };
3808
5416
  // Fail closed without the classifier: every built-in method of host data counts as mutating.
3809
5417
  const hostIsMutatingBuiltin = typeof __host_isMutatingBuiltin__ === 'function' ? __host_isMutatingBuiltin__ : function() { return true; };
5418
+ // What a method of a host function answers in place of the function's source text, or
5419
+ // undefined for a method that does not answer with it.
5420
+ const hostFunctionText = typeof __host_functionText__ === 'function' ? __host_functionText__ : function() { return undefined; };
3810
5421
  const hostConsoleSink = typeof __host_consoleSink__ === 'function' ? __host_consoleSink__ : null;
3811
5422
  // Writes one line to the host console at a level. The host console OBJECT is never in this realm.
3812
5423
  const hostConsoleWrite = typeof __host_console_write__ === 'function' ? __host_console_write__ : function() {};
@@ -3825,6 +5436,7 @@ function generateParentVmBootstrap(options) {
3825
5436
  try { delete globalThis.__host_invokeGlobal__; } catch (e) { /* ignore */ }
3826
5437
  try { delete globalThis.__host_isBuiltinMethod__; } catch (e) { /* ignore */ }
3827
5438
  try { delete globalThis.__host_isMutatingBuiltin__; } catch (e) { /* ignore */ }
5439
+ try { delete globalThis.__host_functionText__; } catch (e) { /* ignore */ }
3828
5440
  try { delete globalThis.__host_consoleSink__; } catch (e) { /* ignore */ }
3829
5441
  try { delete globalThis.__host_console_write__; } catch (e) { /* ignore */ }
3830
5442
 
@@ -3863,6 +5475,7 @@ function generateParentVmBootstrap(options) {
3863
5475
  const __ag_defineProperties = Object.defineProperties;
3864
5476
  const __ag_setPrototypeOf = Object.setPrototypeOf;
3865
5477
  const __ag_objectCreate = Object.create;
5478
+ const __ag_ParentProxy = Proxy;
3866
5479
  const __ag_objectFreeze = Object.freeze;
3867
5480
  const __ag_ReflectGet = Reflect.get;
3868
5481
  const __ag_ReflectSet = Reflect.set;
@@ -3875,6 +5488,8 @@ function generateParentVmBootstrap(options) {
3875
5488
  const __ag_ReflectGetPrototypeOf = Reflect.getPrototypeOf;
3876
5489
  const __ag_ArrayIsArray = Array.isArray;
3877
5490
  const __ag_hasOwnProperty = Object.prototype.hasOwnProperty;
5491
+ const __ag_FunctionToString = Function.prototype.toString;
5492
+ const __ag_ObjectToLocaleString = Object.prototype.toLocaleString;
3878
5493
  const __ag_Promise = Promise;
3879
5494
 
3880
5495
  /**
@@ -4093,6 +5708,11 @@ function generateParentVmBootstrap(options) {
4093
5708
  return forwarder;
4094
5709
  }
4095
5710
 
5711
+ /** A function of this realm that answers with a fixed text (see hostFunctionText). */
5712
+ function createTextAnswer(text) {
5713
+ return function toString() { return text; };
5714
+ }
5715
+
4096
5716
  /**
4097
5717
  * Settle a promise of this realm the way a HOST promise settles, so the sandbox never holds
4098
5718
  * the host promise (whose 'then', 'catch' and 'finally' are host functions). A rejection
@@ -4222,6 +5842,10 @@ function generateParentVmBootstrap(options) {
4222
5842
  if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {
4223
5843
  return value;
4224
5844
  }
5845
+ // An argument guard on its way back is the script's own value again.
5846
+ if (guardedHostArguments.has(value)) {
5847
+ return guardedHostArguments.get(value);
5848
+ }
4225
5849
  if (membraneProxies.has(value) || belongsToInnerRealm(value)) {
4226
5850
  return value;
4227
5851
  }
@@ -4229,18 +5853,30 @@ function generateParentVmBootstrap(options) {
4229
5853
  }
4230
5854
 
4231
5855
  /**
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.
5856
+ * Arguments for a built-in method of host data. Such a method runs in the host's realm, and
5857
+ * whatever of the script it calls, it calls with the host's own values:
5858
+ *
5859
+ * - a callback (map, forEach, sort, find, ...) receives the elements, the index and the
5860
+ * collection itself: each callback is replaced by one that receives them wrapped;
5861
+ * - a method of an object argument (the set operations ask the other collection has(element)
5862
+ * for each element of the receiver): the object is replaced by a guard, see
5863
+ * guardObjectForHost.
4235
5864
  */
4236
5865
  function guardCallbacksForHost(args) {
4237
5866
  var guardedArgs = [];
4238
5867
  for (var i = 0; i < args.length; i++) {
4239
- guardedArgs[i] = typeof args[i] === 'function' ? guardCallbackForHost(args[i]) : args[i];
5868
+ guardedArgs[i] = guardArgumentForHost(args[i]);
4240
5869
  }
4241
5870
  return guardedArgs;
4242
5871
  }
4243
5872
 
5873
+ function guardArgumentForHost(value) {
5874
+ if (typeof value === 'function') {
5875
+ return guardedHostArguments.has(value) ? value : guardCallbackForHost(value);
5876
+ }
5877
+ return guardObjectForHost(value);
5878
+ }
5879
+
4244
5880
  function guardCallbackForHost(callback) {
4245
5881
  return (...hostArgs) => {
4246
5882
  for (var i = 0; i < hostArgs.length; i++) {
@@ -4250,6 +5886,84 @@ function generateParentVmBootstrap(options) {
4250
5886
  };
4251
5887
  }
4252
5888
 
5889
+ // The guard of an object of the script, and what each guard stands for (so that a guard a
5890
+ // built-in hands back, as an element of its result say, is the script's own value again).
5891
+ const hostArgumentGuards = new WeakMap();
5892
+ const guardedHostArguments = new WeakMap();
5893
+
5894
+ /**
5895
+ * An object of the script on its way into a built-in method of host data.
5896
+ *
5897
+ * The built-in may look up a method on it and call that method with host values. So it gets a
5898
+ * guard instead: an object of this realm that answers every property read from the script's
5899
+ * object, with a function member replaced by one that passes its arguments through
5900
+ * toSandboxValue (and keeps the script's object as its receiver), and an object member or
5901
+ * result guarded the same way. Its own properties are listed as they are, so a built-in that
5902
+ * copies or serializes the object sees the same data. An array is data to every built-in and
5903
+ * is passed as it is, as is a value that is behind the membrane already.
5904
+ */
5905
+ function guardObjectForHost(value) {
5906
+ if (value === null || typeof value !== 'object') {
5907
+ return value;
5908
+ }
5909
+ if (membraneProxies.has(value) || guardedHostArguments.has(value) || __ag_ArrayIsArray(value)) {
5910
+ return value;
5911
+ }
5912
+ var existing = hostArgumentGuards.get(value);
5913
+ if (existing) {
5914
+ return existing;
5915
+ }
5916
+ // Over an empty object of this realm, not over the script's object: a frozen member of the
5917
+ // target would have to be reported as it is (proxy invariant), unguarded.
5918
+ var guard = new __ag_ParentProxy(__ag_objectCreate(null), {
5919
+ get: function(_shell, property) {
5920
+ return guardMemberForHost(__ag_ReflectGet(value, property, value), value);
5921
+ },
5922
+ has: function(_shell, property) {
5923
+ return __ag_ReflectHas(value, property);
5924
+ },
5925
+ // A built-in that lists the object (to copy or to serialize it) sees the script's own
5926
+ // properties, each as a data property holding what a read of it gives.
5927
+ ownKeys: function() {
5928
+ return __ag_ReflectOwnKeys(value);
5929
+ },
5930
+ getOwnPropertyDescriptor: function(_shell, property) {
5931
+ var descriptor = __ag_ReflectGetOwnPropertyDescriptor(value, property);
5932
+ if (!descriptor) {
5933
+ return undefined;
5934
+ }
5935
+ return {
5936
+ value: guardMemberForHost(__ag_ReflectGet(value, property, value), value),
5937
+ writable: true,
5938
+ enumerable: descriptor.enumerable === true,
5939
+ configurable: true
5940
+ };
5941
+ },
5942
+ // What a built-in stores in the object is a host value like any other.
5943
+ set: function(_shell, property, stored) {
5944
+ return __ag_ReflectSet(value, property, toSandboxValue(stored), value);
5945
+ }
5946
+ });
5947
+ hostArgumentGuards.set(value, guard);
5948
+ guardedHostArguments.set(guard, value);
5949
+ return guard;
5950
+ }
5951
+
5952
+ function guardMemberForHost(member, holder) {
5953
+ if (typeof member !== 'function') {
5954
+ return guardObjectForHost(member);
5955
+ }
5956
+ var method = function() {
5957
+ var hostArgs = [];
5958
+ for (var i = 0; i < arguments.length; i++) {
5959
+ hostArgs[i] = toSandboxValue(arguments[i]);
5960
+ }
5961
+ return guardArgumentForHost(__ag_ReflectApply(member, holder, hostArgs));
5962
+ };
5963
+ guardedHostArguments.set(method, member);
5964
+ return method;
5965
+ }
5966
+
4253
5967
  /**
4254
5968
  * A value of THIS realm on its way into script code. Objects created here (the arrays that
4255
5969
  * Object.keys and Object.entries build, a promise of this realm) are not the script's and not
@@ -4291,6 +6005,112 @@ function generateParentVmBootstrap(options) {
4291
6005
  };
4292
6006
  }
4293
6007
 
6008
+ // SECURITY (a function of the script on a value of this realm): a script can store a function
6009
+ // of its own on a value of THIS realm that it holds behind the membrane (a tool result, the
6010
+ // array a built-in made, a promise), as a property, a getter or a setter. Whoever finds the
6011
+ // function there calls it: the script through the membrane, but also a built-in of this realm
6012
+ // that works on the raw value (a conversion looks up toString, a read runs a getter), and that
6013
+ // built-in calls it with the raw value as its receiver. So what is stored on the raw value is
6014
+ // never the script's function but a guard of this realm that calls it with what the script may
6015
+ // hold (see guardCallbackForRealm), and a read through the membrane gives the script its own
6016
+ // function back.
6017
+ const scriptFunctionGuards = new WeakMap();
6018
+ const guardedScriptFunctions = new WeakMap();
6019
+
6020
+ function isScriptFunction(value) {
6021
+ return typeof value === 'function' && !membraneProxies.has(value) && belongsToInnerRealm(value);
6022
+ }
6023
+
6024
+ function guardScriptFunction(fn) {
6025
+ var existing = scriptFunctionGuards.get(fn);
6026
+ if (existing) {
6027
+ return existing;
6028
+ }
6029
+ var guard = guardCallbackForRealm(fn);
6030
+ scriptFunctionGuards.set(fn, guard);
6031
+ guardedScriptFunctions.set(guard, fn);
6032
+ return guard;
6033
+ }
6034
+
6035
+ /**
6036
+ * Whether a value is a raw object or function of this realm: not a primitive, not the script's
6037
+ * own, not a safe error and not behind the membrane already.
6038
+ */
6039
+ function isRawRealmReference(value) {
6040
+ if (value === null || (typeof value !== 'object' && typeof value !== 'function')) {
6041
+ return false;
6042
+ }
6043
+ return !membraneProxies.has(value) && !safeErrors.has(value) && !belongsToInnerRealm(value);
6044
+ }
6045
+
6046
+ /**
6047
+ * The descriptor to apply when a script defines a property on a value of this realm.
6048
+ *
6049
+ * - A function of the script (the value, the getter or the setter) is stored as its guard.
6050
+ * - A data property that ends up neither configurable nor writable is pinned: the language
6051
+ * requires every later read through a Proxy to answer with exactly what is stored. What is
6052
+ * stored then is the membrane's own answer for the value (its proxy), so that freezing or
6053
+ * sealing a value does not turn its nested values into raw objects of this realm.
6054
+ */
6055
+ function descriptorForRealmValue(obj, property, descriptor, depth) {
6056
+ if (descriptor === null || typeof descriptor !== 'object') {
6057
+ return descriptor;
6058
+ }
6059
+ var next = {};
6060
+ var fields = ['value', 'get', 'set', 'writable', 'enumerable', 'configurable'];
6061
+ for (var f = 0; f < fields.length; f++) {
6062
+ if (fields[f] in descriptor) next[fields[f]] = descriptor[fields[f]];
6063
+ }
6064
+ if (isScriptFunction(next.value)) next.value = guardScriptFunction(next.value);
6065
+ if (isScriptFunction(next.get)) next.get = guardScriptFunction(next.get);
6066
+ if (isScriptFunction(next.set)) next.set = guardScriptFunction(next.set);
6067
+
6068
+ if ('get' in next || 'set' in next) {
6069
+ return next;
6070
+ }
6071
+ var current = __ag_getOwnPropertyDescriptor(obj, property);
6072
+ var currentIsData = !!current && 'value' in current;
6073
+ if (current && !currentIsData && !('value' in next) && !('writable' in next)) {
6074
+ // Stays an accessor
6075
+ return next;
6076
+ }
6077
+ if (currentIsData && !current.configurable && !current.writable) {
6078
+ // Pinned already: nothing can be stored in its place
6079
+ return next;
6080
+ }
6081
+ var configurable = 'configurable' in next ? next.configurable : (current ? current.configurable : false);
6082
+ var writable = 'writable' in next ? next.writable : (currentIsData ? current.writable : false);
6083
+ if (!configurable && !writable) {
6084
+ var pinned = 'value' in next ? next.value : (currentIsData ? current.value : undefined);
6085
+ if (isRawRealmReference(pinned)) {
6086
+ next.value = createSecureProxy(pinned, depth + 1, false);
6087
+ }
6088
+ }
6089
+ return next;
6090
+ }
6091
+
6092
+ /**
6093
+ * An object of this realm on its way behind the membrane: a function of the script that a
6094
+ * built-in of this realm stored in it by name (Object.fromEntries, Object.groupBy) is replaced
6095
+ * by its guard, as the membrane does for a function the script stores there itself. An array
6096
+ * holds its items by index, which no built-in calls as a method of the array.
6097
+ */
6098
+ function guardScriptFunctionsOf(obj) {
6099
+ var keys;
6100
+ try {
6101
+ keys = __ag_ReflectOwnKeys(obj);
6102
+ } catch (e) {
6103
+ return;
6104
+ }
6105
+ for (var k = 0; k < keys.length; k++) {
6106
+ var own = __ag_getOwnPropertyDescriptor(obj, keys[k]);
6107
+ if (!own || !('value' in own) || !own.writable || !isScriptFunction(own.value)) continue;
6108
+ try {
6109
+ obj[keys[k]] = guardScriptFunction(own.value);
6110
+ } catch (e) { /* left as it is */ }
6111
+ }
6112
+ }
6113
+
4294
6114
  /**
4295
6115
  * The result of a built-in method of host data. An array (map, filter, slice, concat, ...) is
4296
6116
  * copied into an array of this realm, so the script can sort or extend what it derived
@@ -4301,6 +6121,9 @@ function generateParentVmBootstrap(options) {
4301
6121
  if (result === null || (typeof result !== 'object' && typeof result !== 'function')) {
4302
6122
  return result;
4303
6123
  }
6124
+ if (guardedHostArguments.has(result)) {
6125
+ result = guardedHostArguments.get(result);
6126
+ }
4304
6127
  if (membraneProxies.has(result)) {
4305
6128
  return result;
4306
6129
  }
@@ -4394,6 +6217,12 @@ function generateParentVmBootstrap(options) {
4394
6217
  return obj;
4395
6218
  }
4396
6219
 
6220
+ // An argument guard (see guardObjectForHost) that a built-in of host data kept in what it
6221
+ // returned stands for a value of the script: that value is what the script gets back.
6222
+ if (guardedHostArguments.has(obj)) {
6223
+ return guardedHostArguments.get(obj);
6224
+ }
6225
+
4397
6226
  // Check cache
4398
6227
  var cache = host ? hostProxyCache : proxyCache;
4399
6228
  if (cache.has(obj)) {
@@ -4408,6 +6237,15 @@ function generateParentVmBootstrap(options) {
4408
6237
  var shelled = typeof obj === 'function' && !realmOwnedCallables.has(obj);
4409
6238
  var proxyTarget = shelled ? newCallableShell() : obj;
4410
6239
 
6240
+ // Whether obj is a value of THIS realm: neither the host's nor the script's own (an array a
6241
+ // built-in made, a tool result, a promise of this realm, a forwarder). Decided once, here:
6242
+ // the answer follows the prototype chain, which a script cannot change afterwards (see the
6243
+ // setPrototypeOf trap).
6244
+ var foreign = !host && !belongsToInnerRealm(obj);
6245
+ if (foreign && typeof obj === 'object' && !__ag_ArrayIsArray(obj)) {
6246
+ guardScriptFunctionsOf(obj);
6247
+ }
6248
+
4411
6249
  var handler = {
4412
6250
  get: function(_target, property, receiver) {
4413
6251
  var propName = String(property);
@@ -4435,6 +6273,15 @@ function generateParentVmBootstrap(options) {
4435
6273
  // A shelled callable is not the Proxy target, so no invariant pins its value: a
4436
6274
  // reference takes the blocking and wrapping path below like any other read.
4437
6275
  if (!shelled || !exactIsReference) {
6276
+ // A raw object of this realm that is pinned in a value of this realm (a member of
6277
+ // an intrinsic of this realm, which is frozen) can be neither handed over nor
6278
+ // wrapped. What a script pins itself is stored wrapped (descriptorForRealmValue).
6279
+ if (foreign && isRawRealmReference(exactValue)) {
6280
+ throw createSafeError(
6281
+ "Security violation: Access to '" + propName + "' is blocked. " +
6282
+ "This property cannot be exposed without breaking the sandbox barrier."
6283
+ );
6284
+ }
4438
6285
  return exactValue;
4439
6286
  }
4440
6287
  }
@@ -4474,6 +6321,29 @@ function generateParentVmBootstrap(options) {
4474
6321
  // block constructor access. It is a closure rather than value.bind(obj): a bound
4475
6322
  // function keeps the realm of its target (see realmOwnedCallables).
4476
6323
  if (typeof value === 'function') {
6324
+ // A function of the script that sits on a value of this realm is the script's own: it
6325
+ // gets it back as it is, and calls it on the value it holds (see guardScriptFunction).
6326
+ if (foreign) {
6327
+ if (guardedScriptFunctions.has(value)) {
6328
+ return guardedScriptFunctions.get(value);
6329
+ }
6330
+ if (isScriptFunction(value)) {
6331
+ return value;
6332
+ }
6333
+ }
6334
+ // The text of a host function is a fixed form, never its source: toString (and
6335
+ // toLocaleString, which calls it) read off a host function answer with that form. A
6336
+ // forwarder stands for the host method it calls, and its own methods are this realm's.
6337
+ if (host && typeof obj === 'function') {
6338
+ var ownTextMethod = value === __ag_FunctionToString || value === __ag_ObjectToLocaleString;
6339
+ var functionText = hostFunctionText(
6340
+ ownTextMethod ? null : value,
6341
+ forwardedMethods.has(obj) ? forwardedMethods.get(obj) : obj
6342
+ );
6343
+ if (typeof functionText === 'string') {
6344
+ return createSecureProxy(createTextAnswer(functionText), depth + 1, false);
6345
+ }
6346
+ }
4477
6347
  var hostBuiltin = host && hostIsBuiltinMethod(value);
4478
6348
  // push, sort, Map.prototype.set, ... called on host data would write to the host's
4479
6349
  // own object without ever reaching the set trap.
@@ -4484,7 +6354,7 @@ function generateParentVmBootstrap(options) {
4484
6354
  var method = createMethodForwarder(value, obj);
4485
6355
  if (hostBuiltin) {
4486
6356
  ungatedHostFunctions.add(method);
4487
- } else if (!host && typeof obj === 'object' && !belongsToInnerRealm(obj)) {
6357
+ } else if (foreign && typeof obj === 'object') {
4488
6358
  parentRealmMethods.add(method);
4489
6359
  }
4490
6360
  return createSecureProxy(method, depth + 1, host);
@@ -4535,7 +6405,11 @@ function generateParentVmBootstrap(options) {
4535
6405
  "Security violation: Defining non-configurable property '" + propName + "' on a function is blocked."
4536
6406
  );
4537
6407
  }
4538
- return __ag_ReflectDefineProperty(obj, property, descriptor);
6408
+ return __ag_ReflectDefineProperty(
6409
+ obj,
6410
+ property,
6411
+ foreign ? descriptorForRealmValue(obj, property, descriptor, depth) : descriptor
6412
+ );
4539
6413
  },
4540
6414
  deleteProperty: function(_target, property) {
4541
6415
  if (host) {
@@ -4600,6 +6474,23 @@ function generateParentVmBootstrap(options) {
4600
6474
  // path below, described as configurable.
4601
6475
  if (descriptor && !descriptor.configurable) {
4602
6476
  if (!shelled) {
6477
+ // On a value of this realm such a description would hand out a raw object of this
6478
+ // realm. A writable property may be described with another value (the wrapped one);
6479
+ // a pinned one may not, and is refused as the get trap refuses it.
6480
+ if (foreign && 'value' in descriptor && isRawRealmReference(descriptor.value)) {
6481
+ if (descriptor.writable === false) {
6482
+ throw createSafeError(
6483
+ "Security violation: Access to property descriptor for '" + propName + "' is blocked. " +
6484
+ "This property cannot be exposed without breaking the sandbox barrier."
6485
+ );
6486
+ }
6487
+ var described = {};
6488
+ for (var nk in descriptor) { if (__ag_hasOwnProperty.call(descriptor, nk)) described[nk] = descriptor[nk]; }
6489
+ described.value = guardedScriptFunctions.has(descriptor.value)
6490
+ ? guardedScriptFunctions.get(descriptor.value)
6491
+ : createSecureProxy(descriptor.value, depth + 1, false);
6492
+ return described;
6493
+ }
4603
6494
  return descriptor;
4604
6495
  }
4605
6496
  descriptor = reportable(descriptor);
@@ -4621,8 +6512,18 @@ function generateParentVmBootstrap(options) {
4621
6512
  if (descriptor && (typeof descriptor.get === 'function' || typeof descriptor.set === 'function')) {
4622
6513
  var accessorWrapped = {};
4623
6514
  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);
6515
+ // A getter or setter of the script is described as the script's function, not as the
6516
+ // guard that is stored for it (see guardScriptFunction).
6517
+ if (typeof descriptor.get === 'function') {
6518
+ accessorWrapped.get = guardedScriptFunctions.has(descriptor.get)
6519
+ ? guardedScriptFunctions.get(descriptor.get)
6520
+ : createSecureProxy(descriptor.get, depth + 1, host);
6521
+ }
6522
+ if (typeof descriptor.set === 'function') {
6523
+ accessorWrapped.set = guardedScriptFunctions.has(descriptor.set)
6524
+ ? guardedScriptFunctions.get(descriptor.set)
6525
+ : createSecureProxy(descriptor.set, depth + 1, host);
6526
+ }
4626
6527
  return accessorWrapped;
4627
6528
  }
4628
6529
 
@@ -4638,7 +6539,9 @@ function generateParentVmBootstrap(options) {
4638
6539
  var refusedValue = (host && typeof value === 'function' && hostIsBuiltinMethod(value))
4639
6540
  ? refusedHostBuiltin(value, propName, depth)
4640
6541
  : null;
4641
- wrapped.value = refusedValue || createSecureProxy(value, depth + 1, host);
6542
+ wrapped.value = refusedValue || (guardedScriptFunctions.has(value)
6543
+ ? guardedScriptFunctions.get(value)
6544
+ : createSecureProxy(value, depth + 1, host));
4642
6545
  return wrapped;
4643
6546
  }
4644
6547
  }
@@ -4669,9 +6572,10 @@ function generateParentVmBootstrap(options) {
4669
6572
  // Return null to hide prototype chain
4670
6573
  return null;
4671
6574
  },
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() {
6575
+ // The default would change the prototype of the Proxy target: of the shell (pointless), of
6576
+ // a host-owned value (a write to the host), or of a value of this realm, whose prototype
6577
+ // chain is how the membrane tells it from a value of the script (see 'foreign' above).
6578
+ setPrototypeOf: (host || shelled || foreign) ? function() {
4675
6579
  if (host) {
4676
6580
  return refuseHostWrite('Changing the prototype of the value', false);
4677
6581
  }
@@ -4744,7 +6648,10 @@ function generateParentVmBootstrap(options) {
4744
6648
  * Sliding one-second window; entries older than two seconds are dropped.
4745
6649
  */
4746
6650
  function enforceRateLimit(now) {
4747
- while (operationHistory.length > 0 && now - operationHistory[0].timestamp > 2000) {
6651
+ // Kept for as long as the longest look-back of a sequence detector (30 seconds for the
6652
+ // built-in ones, twice that here), not only for the rate window below: a detector that
6653
+ // asks for the last ten seconds has to find them.
6654
+ while (operationHistory.length > 0 && now - operationHistory[0].timestamp > 60000) {
4748
6655
  operationHistory.shift();
4749
6656
  }
4750
6657
  while (globalFunctionCallTimes.length > 0 && now - globalFunctionCallTimes[0] > 2000) {
@@ -5374,6 +7281,10 @@ function generateParentVmBootstrap(options) {
5374
7281
  codeGeneration: { strings: false, wasm: false }
5375
7282
  });
5376
7283
 
7284
+ // The inner realm captures no stack traces, at every security level (see ../realm-stack): the
7285
+ // first thing that runs there, while its Error is the intrinsic one.
7286
+ new vm.Script(${JSON.stringify(STACK_CAPTURE_OFF_SOURCE)}, { filename: 'inner-stack.js' }).runInContext(innerContext);
7287
+
5377
7288
  // The function that removes globals from the inner realm at the end of setup (see
5378
7289
  // INNER_REALM_SCRUB_SOURCE). Compiled before anything else runs there.
5379
7290
  var __ag_scrubInnerRealm = new vm.Script(${JSON.stringify(INNER_REALM_SCRUB_SOURCE)}, {
@@ -5425,7 +7336,9 @@ function generateParentVmBootstrap(options) {
5425
7336
  // The script's cooperative deadline (see ../deadline-guard): the inner realm's __safe_tick,
5426
7337
  // which the transformed script calls at every function entry and loop iteration. vm's timeout
5427
7338
  // below only covers the script up to its first await.
5428
- new vm.Script(${JSON.stringify(realmTickSource(innerTimeout))}, {
7339
+ // What that script evaluates to ends the checks: called when the script has settled, it makes
7340
+ // whatever the script left behind stop at its next function entry or loop iteration.
7341
+ var __ag_endDeadlineChecks = new vm.Script(${JSON.stringify(realmTickSource(innerTimeout))}, {
5429
7342
  filename: 'inner-deadline.js'
5430
7343
  }).runInContext(innerContext);
5431
7344
 
@@ -5491,6 +7404,9 @@ function generateParentVmBootstrap(options) {
5491
7404
  // Strict mode: an unbound call (const f = [].fill; f(0)) must fail on its undefined "this".
5492
7405
  // In sloppy mode "this" was coerced to the realm's global object, and fill RETURNED it.
5493
7406
  '"use strict";' +
7407
+ // The functions of Math, not the object: a script can assign to its members, and a
7408
+ // replaced Math.max would decide what a fill is charged.
7409
+ 'Math = { max: Math.max, min: Math.min, round: Math.round };' +
5494
7410
  'var memoryLimit = ' + memoryLimit + ';' +
5495
7411
  'var trackMemory = __host_memory_track__;' +
5496
7412
  // A size is only usable when it is a positive number. NaN (a missing or non-numeric count,
@@ -5562,31 +7478,21 @@ function generateParentVmBootstrap(options) {
5562
7478
  ' trackMemory(estimatedSize);' +
5563
7479
  ' return chargeActual(originalPadEnd.call(this, targetLength, padString), estimatedSize, "String.padEnd");' +
5564
7480
  '};' +
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
- '};' +
7481
+ // Array.prototype.fill is accounted for with the other array operations (see
7482
+ // ../realm-memory), where its range is worked out by the built-in's own rules.
5584
7483
  '})(Math, String, RangeError);';
5585
7484
  var patchScript = new vm.Script(patchCode);
5586
7485
  patchScript.runInContext(innerContext);
5587
7486
  }
5588
7487
  })();
5589
7488
 
7489
+ // Arrays that grow are accounted for like strings that grow (see ../realm-memory), and the
7490
+ // helpers the transformed code calls around an array literal with spreads are defined. Always:
7491
+ // without a memory limit the helpers count nothing.
7492
+ new vm.Script(${JSON.stringify(realmArrayAccountingSource(memoryLimit))}, {
7493
+ filename: 'inner-array-accounting.js'
7494
+ }).runInContext(innerContext);
7495
+
5590
7496
  // ============================================================
5591
7497
  // PHASE 2 HARDENING: CVE-2023-29017 Stack Overflow Escape Defense
5592
7498
  // ============================================================
@@ -5930,6 +7836,7 @@ function generateParentVmBootstrap(options) {
5930
7836
  var getIntrinsicsCode =
5931
7837
  '({ ' +
5932
7838
  ' Array: Array, ' +
7839
+ ' objectAssign: Object.assign, ' +
5933
7840
  ' String: String, ' +
5934
7841
  ' Number: Number, ' +
5935
7842
  ' Boolean: Boolean, ' +
@@ -5954,6 +7861,13 @@ function generateParentVmBootstrap(options) {
5954
7861
  return script.runInContext(innerContext);
5955
7862
  })();
5956
7863
 
7864
+ // Object.assign is the inner realm's: where memory is accounted for, that one keeps an array
7865
+ // within what the limit holds (see ../realm-memory); this realm's own would write to an
7866
+ // array of the script unseen.
7867
+ if (typeof innerIntrinsics.objectAssign === 'function') {
7868
+ SafeObject.assign = innerIntrinsics.objectAssign;
7869
+ }
7870
+
5957
7871
  // The constructors the script uses with new and instanceof. They are proxied directly (see
5958
7872
  // realmOwnedCallables): each belongs to the inner realm, except SafeObject, which is a
5959
7873
  // function of this realm. Neither realm can generate code from strings.
@@ -6146,10 +8060,16 @@ function generateParentVmBootstrap(options) {
6146
8060
  __ag_lockdownParentRealm();
6147
8061
 
6148
8062
  // Note: codeGeneration is set in createContext(), not runInContext()
6149
- var result = await script.runInContext(innerContext, {
6150
- timeout: ${innerTimeout},
6151
- breakOnSigint: true
6152
- });
8063
+ var result;
8064
+ try {
8065
+ result = await script.runInContext(innerContext, {
8066
+ timeout: ${innerTimeout},
8067
+ breakOnSigint: true
8068
+ });
8069
+ } finally {
8070
+ // The execution is over, whichever way: nothing the script left behind runs on from here
8071
+ try { __ag_endDeadlineChecks(); } catch (e) { /* the realm is gone */ }
8072
+ }
6153
8073
 
6154
8074
  return result;
6155
8075
  })();
@@ -6207,7 +8127,8 @@ var BULK_OPERATION = {
6207
8127
  if (typeof args === "object" && args !== null) {
6208
8128
  try {
6209
8129
  const argStr = JSON.stringify(args).toLowerCase();
6210
- const hasBulkArgs = /limit.*[0-9]{4,}|"\*"|no[_-]?limit/i.test(argStr);
8130
+ const firstLimit = argStr.indexOf("limit");
8131
+ 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
8132
  if (hasBulkArgs) return true;
6212
8133
  } catch {
6213
8134
  }
@@ -6375,17 +8296,18 @@ var DoubleVmWrapper = class {
6375
8296
  memSnapshot = memoryTracker.getSnapshot();
6376
8297
  stats.memoryUsage = memSnapshot.peakTrackedBytes;
6377
8298
  }
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;
8299
+ const thrown = describeThrown(error);
8300
+ if (error instanceof MemoryLimitError || memoryTracker?.hasExceededLimit() === true && isMemoryLimitPayload(error)) {
6382
8301
  return {
6383
8302
  success: false,
6384
8303
  error: {
6385
8304
  name: "MemoryLimitError",
6386
- message: typeof payload.message === "string" ? payload.message : "Memory limit exceeded",
8305
+ message: thrown.message ?? "Memory limit exceeded",
6387
8306
  code: "MEMORY_LIMIT_EXCEEDED",
6388
- data: { usedBytes, limitBytes }
8307
+ data: {
8308
+ usedBytes: error instanceof MemoryLimitError ? error.usedBytes : memSnapshot?.trackedBytes ?? 0,
8309
+ limitBytes: error instanceof MemoryLimitError ? error.limitBytes : config.memoryLimit ?? 0
8310
+ }
6389
8311
  },
6390
8312
  stats
6391
8313
  };
@@ -6396,19 +8318,18 @@ var DoubleVmWrapper = class {
6396
8318
  success: false,
6397
8319
  error: {
6398
8320
  name: "DoubleVMExecutionError",
6399
- message: error,
8321
+ message: thrown.message ?? "",
6400
8322
  code: "DOUBLE_VM_EXECUTION_ERROR"
6401
8323
  },
6402
8324
  stats
6403
8325
  };
6404
8326
  }
6405
- const err = error;
6406
8327
  return {
6407
8328
  success: false,
6408
8329
  error: {
6409
- name: err.name || "DoubleVMExecutionError",
6410
- message: err.message || "Unknown double VM execution error",
6411
- stack: sanitizeStackTrace(err.stack, shouldSanitize),
8330
+ name: thrown.name || "DoubleVMExecutionError",
8331
+ message: thrown.message || THROWN_WITHOUT_MESSAGE,
8332
+ stack: sanitizeStackTrace(thrown.stack, shouldSanitize),
6412
8333
  code: "DOUBLE_VM_EXECUTION_ERROR"
6413
8334
  },
6414
8335
  stats
@@ -6468,6 +8389,12 @@ var DoubleVmWrapper = class {
6468
8389
  configurable: true
6469
8390
  // Allow deletion after capture for defense-in-depth
6470
8391
  });
8392
+ Object.defineProperty(parentContext, "__host_functionText__", {
8393
+ value: (method, fn) => method === null || isFunctionTextMethod(method) ? hostFunctionText(fn) : void 0,
8394
+ writable: false,
8395
+ configurable: true
8396
+ // Allow deletion after capture for defense-in-depth
8397
+ });
6471
8398
  Object.defineProperty(parentContext, "__host_stats__", {
6472
8399
  value: stats,
6473
8400
  writable: false,
@@ -6825,7 +8752,8 @@ function createSafeRuntime(context, options) {
6825
8752
  const proxyOptions = {
6826
8753
  ...secureProxyConfig ? { levelConfig: secureProxyConfig } : {},
6827
8754
  ...options?.exposeToSandbox ? { exposeToSandbox: options.exposeToSandbox } : {},
6828
- ...options?.ownedBySandbox ? { ownedBySandbox: options.ownedBySandbox } : {}
8755
+ ...options?.ownedBySandbox ? { ownedBySandbox: options.ownedBySandbox } : {},
8756
+ ...options?.heldBySandbox ? { heldBySandbox: options.heldBySandbox } : {}
6829
8757
  };
6830
8758
  async function __safe_callTool(toolName, args, options2) {
6831
8759
  const throwOnError = readThrowOnError(options2);
@@ -7161,8 +9089,11 @@ ${errorMessages}`);
7161
9089
  }
7162
9090
 
7163
9091
  // libs/core/src/realm-airlock.ts
7164
- var ReflectGet5 = Reflect.get;
7165
- var ReflectHas = Reflect.has;
9092
+ var HostFunctionCall = Function.prototype.call;
9093
+ var HostFunctionApply = Function.prototype.apply;
9094
+ var HostFunctionBind = Function.prototype.bind;
9095
+ var ReflectGet6 = Reflect.get;
9096
+ var ReflectHas2 = Reflect.has;
7166
9097
  var ReflectOwnKeys3 = Reflect.ownKeys;
7167
9098
  var ReflectGetOwnPropertyDescriptor2 = Reflect.getOwnPropertyDescriptor;
7168
9099
  var ReflectApply6 = Reflect.apply;
@@ -7179,6 +9110,23 @@ function createRealmAirlock(realm) {
7179
9110
  };
7180
9111
  const refusedMethod = realm.wrap(refuseWrite, false);
7181
9112
  const realmObjectPrototype = ObjectGetPrototypeOf5(realm.shell("object"));
9113
+ const realmFunction = realm.shell("function");
9114
+ const realmCounterparts = /* @__PURE__ */ new Map([
9115
+ [HostFunctionCall, ReflectGet6(realmFunction, "call")],
9116
+ [HostFunctionApply, ReflectGet6(realmFunction, "apply")],
9117
+ [
9118
+ HostFunctionBind,
9119
+ realm.wrap(() => {
9120
+ throw createSafeError(
9121
+ "A host function cannot be bound in the sandbox. Call it from a function of your own.",
9122
+ "TypeError"
9123
+ );
9124
+ }, false)
9125
+ ]
9126
+ ]);
9127
+ function isAirlockProxy(value) {
9128
+ return inward.has(value);
9129
+ }
7182
9130
  function isRealmValue(value) {
7183
9131
  if (!isReference(realmObjectPrototype) || inward.has(value)) {
7184
9132
  return false;
@@ -7222,14 +9170,25 @@ function createRealmAirlock(realm) {
7222
9170
  } else if (isSafeError(value)) {
7223
9171
  return value;
7224
9172
  } else if (isRawHostObject(value)) {
7225
- hostProxy = createSecureProxy(value, { exposeToSandbox: toRealm, ownedBySandbox: isRealmValue });
9173
+ hostProxy = createSecureProxy(value, {
9174
+ exposeToSandbox: toRealm,
9175
+ ownedBySandbox: isRealmValue,
9176
+ heldBySandbox: isAirlockProxy
9177
+ });
7226
9178
  } else {
7227
9179
  return value;
7228
9180
  }
7229
9181
  const callable = typeof hostProxy === "function";
9182
+ if (callable) {
9183
+ const counterpart = realmCounterparts.get(unwrapSecureProxy(hostProxy));
9184
+ if (counterpart !== void 0) {
9185
+ outward.set(hostProxy, counterpart);
9186
+ return counterpart;
9187
+ }
9188
+ }
7230
9189
  const kind = callable ? "function" : ArrayIsArray4(hostProxy) ? "array" : "object";
7231
9190
  const readValue = (key) => {
7232
- const value2 = ReflectGet5(hostProxy, key, hostProxy);
9191
+ const value2 = ReflectGet6(hostProxy, key, hostProxy);
7233
9192
  if (typeof value2 === "function") {
7234
9193
  const method = unwrapSecureProxy(value2);
7235
9194
  if (isMutatingBuiltinMethod(method)) {
@@ -7246,7 +9205,7 @@ function createRealmAirlock(realm) {
7246
9205
  return readValue(key);
7247
9206
  },
7248
9207
  has(_shell, key) {
7249
- return ReflectHas(hostProxy, key);
9208
+ return ReflectHas2(hostProxy, key);
7250
9209
  },
7251
9210
  ownKeys() {
7252
9211
  return ReflectOwnKeys3(hostProxy);
@@ -7278,11 +9237,11 @@ function createRealmAirlock(realm) {
7278
9237
  setPrototypeOf: refuseWrite,
7279
9238
  preventExtensions: refuseWrite,
7280
9239
  apply(_shell, thisArg, args) {
7281
- const hostArgs = [];
9240
+ const passed = [];
7282
9241
  for (let i = 0; i < args.length; i++) {
7283
- hostArgs[i] = toHost(args[i]);
9242
+ passed[i] = args[i];
7284
9243
  }
7285
- return toRealm(ReflectApply6(hostProxy, toHost(thisArg), hostArgs));
9244
+ return toRealm(ReflectApply6(hostProxy, toHost(thisArg), passed));
7286
9245
  },
7287
9246
  construct() {
7288
9247
  throw createSafeError("Host functions cannot be called with new", "TypeError");
@@ -7296,7 +9255,7 @@ function createRealmAirlock(realm) {
7296
9255
  inward.set(proxy, hostProxy);
7297
9256
  return proxy;
7298
9257
  }
7299
- return { toRealm, toHost, isRealmValue };
9258
+ return { toRealm, toHost, isRealmValue, isAirlockProxy };
7300
9259
  }
7301
9260
 
7302
9261
  // libs/core/src/sandbox-console.ts
@@ -7451,6 +9410,7 @@ var STACK_TRACE_HARDENING_CODE = `
7451
9410
  })();
7452
9411
  `.trim();
7453
9412
  var STACK_TRACE_HARDENING_SCRIPT = new ReusableSandboxScript(STACK_TRACE_HARDENING_CODE);
9413
+ var STACK_CAPTURE_OFF_SCRIPT = new ReusableSandboxScript(STACK_CAPTURE_OFF_SOURCE, { filename: "realm-stack.js" });
7454
9414
  var CODE_GENERATION_VIOLATION_DETECTOR_CODE = `
7455
9415
  (function() {
7456
9416
  var __ag_report = (typeof __ag_reportViolation__ === 'function') ? __ag_reportViolation__ : null;
@@ -7516,6 +9476,15 @@ var INTRINSIC_OBJECT_NEUTRALIZATION_CODE = `
7516
9476
  })();
7517
9477
  `;
7518
9478
  var INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT = new ReusableSandboxScript(INTRINSIC_OBJECT_NEUTRALIZATION_CODE);
9479
+ var CLOSE_OBJECT_PROTOTYPE_SCRIPT = new ReusableSandboxScript(
9480
+ `(function () {
9481
+ 'use strict';
9482
+ var root = Object.getPrototypeOf({});
9483
+ Object.preventExtensions(root);
9484
+ if (Object.isExtensible(root)) throw new TypeError('The prototype of plain objects could not be closed');
9485
+ })()`,
9486
+ { filename: "close-object-prototype.js" }
9487
+ );
7519
9488
  var DETACH_GLOBAL_PROTOTYPE_SCRIPT = new ReusableSandboxScript(
7520
9489
  `(function (global) {
7521
9490
  'use strict';
@@ -7957,10 +9926,12 @@ var VmAdapter = class {
7957
9926
  // Object tracking has higher overhead, skip for now
7958
9927
  }) : void 0;
7959
9928
  memoryTracker?.start();
9929
+ let endDeadlineChecks;
7960
9930
  try {
7961
9931
  const baseSandbox = vm3.createContext(/* @__PURE__ */ Object.create(null), {
7962
9932
  codeGeneration: { strings: false, wasm: false }
7963
9933
  });
9934
+ STACK_CAPTURE_OFF_SCRIPT.runInContext(baseSandbox);
7964
9935
  const realmMembrane = REALM_GUARD_SCRIPT.runInContext(baseSandbox);
7965
9936
  const airlock = createRealmAirlock(realmMembrane);
7966
9937
  REALM_SYMBOL_REGISTRY_SCRIPT.runInContext(baseSandbox);
@@ -7998,11 +9969,18 @@ var VmAdapter = class {
7998
9969
  enumerable: true
7999
9970
  });
8000
9971
  }
8001
- compileSandboxScript(realmTickSource(config.timeout), { filename: "deadline.js" }).runInContext(baseSandbox);
9972
+ endDeadlineChecks = compileSandboxScript(realmTickSource(config.timeout), {
9973
+ filename: "deadline.js"
9974
+ }).runInContext(baseSandbox);
8002
9975
  const installToolNamespaces = executionContext.toolNamespaces?.length ? TOOL_NAMESPACE_FACTORY_SCRIPT.runInContext(baseSandbox) : void 0;
8003
9976
  const handlerConsole = executionContext.consoleHandler ? createHandlerConsole(baseSandbox, realmMembrane, executionContext.consoleHandler, config) : void 0;
8004
9977
  const installConsole = handlerConsole ? void 0 : SANDBOX_CONSOLE_FACTORY_SCRIPT.runInContext(baseSandbox);
8005
- const globalFunctionGate = createGlobalFunctionGate(executionContext, realmBridge, unwrapHostValue);
9978
+ const globalFunctionGate = createGlobalFunctionGate(
9979
+ executionContext,
9980
+ realmBridge,
9981
+ unwrapHostValue,
9982
+ airlock.isRealmValue
9983
+ );
8006
9984
  const safeRuntime = createSafeRuntime(executionContext, {
8007
9985
  sidecar: executionContext.sidecar,
8008
9986
  referenceConfig: executionContext.referenceConfig,
@@ -8012,6 +9990,7 @@ var VmAdapter = class {
8012
9990
  globalFunctionGate,
8013
9991
  exposeToSandbox: airlock.toRealm,
8014
9992
  ownedBySandbox: airlock.isRealmValue,
9993
+ heldBySandbox: airlock.isAirlockProxy,
8015
9994
  hostObjects: false
8016
9995
  });
8017
9996
  if (memoryTracker && config.memoryLimit && config.memoryLimit > 0) {
@@ -8039,7 +10018,10 @@ var VmAdapter = class {
8039
10018
  // "this". In sloppy mode "this" was coerced to the realm's global object, and fill
8040
10019
  // RETURNED it.
8041
10020
  'use strict';
8042
- var memoryLimit = ${config.memoryLimit};
10021
+ // The functions of Math, not the object: a script can assign to its members, and a
10022
+ // replaced Math.max would decide what a fill is charged.
10023
+ var Math = (function (M) { return { max: M.max, min: M.min, round: M.round }; })(globalThis.Math);
10024
+ var memoryLimit = ${numericLiteral("memoryLimit", config.memoryLimit)};
8043
10025
  var trackMemory = __host_memory_track__;
8044
10026
 
8045
10027
  // A size is only usable when it is a positive number. NaN (a missing or non-numeric
@@ -8123,29 +10105,8 @@ var VmAdapter = class {
8123
10105
  return chargeActual(originalPadEnd.call(this, targetLength, padString), estimatedSize, 'String.padEnd');
8124
10106
  };
8125
10107
 
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
- };
10108
+ // Array.prototype.fill is accounted for with the other array operations (see
10109
+ // ../realm-memory), where its range is worked out by the built-in's own rules.
8149
10110
 
8150
10111
  // Array.from and Array.of build an array of any size in one call: charged for what
8151
10112
  // they built (8 bytes per element), on the realm's own Array, so that the constructor
@@ -8168,6 +10129,12 @@ var VmAdapter = class {
8168
10129
  `);
8169
10130
  patchScript.runInContext(baseSandbox);
8170
10131
  }
10132
+ compileSandboxScript(
10133
+ realmArrayAccountingSource(
10134
+ memoryTracker && config.memoryLimit && config.memoryLimit > 0 ? config.memoryLimit : 0
10135
+ ),
10136
+ { filename: "array-accounting.js" }
10137
+ ).runInContext(baseSandbox);
8171
10138
  const shouldHardenStacks = config.sanitizeStackTraces ?? true;
8172
10139
  const blockedProperties = executionContext.secureProxyConfig ? buildBlockedPropertiesFromConfig(executionContext.secureProxyConfig) : getBlockedPropertiesForLevel(this.securityLevel);
8173
10140
  compileSandboxScript(
@@ -8208,16 +10175,6 @@ var VmAdapter = class {
8208
10175
  } catch {
8209
10176
  }
8210
10177
  }
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
10178
  if (config.toolBridge?.mode === "string") {
8222
10179
  const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
8223
10180
  const hostToolBridge = createHostToolBridge(executionContext, { updateStats: false, limitChecked: true });
@@ -8266,7 +10223,7 @@ var VmAdapter = class {
8266
10223
  var promiseThen = Promise.prototype.then;
8267
10224
  var settled = Promise.resolve();
8268
10225
  var reflectApply = Reflect.apply;
8269
- var maxBytes = ${maxPayloadBytes};
10226
+ var maxBytes = ${numericLiteral("toolBridge.maxPayloadBytes", maxPayloadBytes)};
8270
10227
  var limitMessage = ${JSON.stringify(limitMessage)};
8271
10228
 
8272
10229
  // Tool calls whose host bridge has not been started yet.
@@ -8433,12 +10390,14 @@ var VmAdapter = class {
8433
10390
  };
8434
10391
  })()
8435
10392
  `);
8436
- const vmSafeCallTool = bridgeInitScript.runInContext(baseSandbox);
8437
- const proxiedVmSafeCallTool = createSecureProxy(vmSafeCallTool, {
8438
- levelConfig: executionContext.secureProxyConfig
8439
- });
10393
+ const realmCallTool = realmMembrane.wrap(
10394
+ bridgeInitScript.runInContext(baseSandbox),
10395
+ true
10396
+ );
10397
+ Object.defineProperty(realmCallTool, "name", { value: "__safe_callTool", configurable: true });
10398
+ Object.defineProperty(realmCallTool, "length", { value: 3, configurable: true });
8440
10399
  Object.defineProperty(baseSandbox, "__safe_callTool", {
8441
- value: airlock.toRealm(proxiedVmSafeCallTool),
10400
+ value: Object.freeze(realmCallTool),
8442
10401
  writable: false,
8443
10402
  configurable: false,
8444
10403
  enumerable: true
@@ -8448,6 +10407,16 @@ var VmAdapter = class {
8448
10407
  } catch {
8449
10408
  }
8450
10409
  }
10410
+ if (this.securityLevel !== "STRICT") {
10411
+ Object.defineProperty(baseSandbox, "Reflect", {
10412
+ value: realmRuntime.createSafeReflect(
10413
+ this.securityLevel === "SECURE" ? "setPrototypeOf,apply,defineProperty" : "setPrototypeOf"
10414
+ ),
10415
+ writable: false,
10416
+ configurable: false,
10417
+ enumerable: true
10418
+ });
10419
+ }
8451
10420
  for (const [key, value2] of Object.entries(safeRuntime)) {
8452
10421
  if (key in baseSandbox) continue;
8453
10422
  Object.defineProperty(baseSandbox, key, {
@@ -8464,7 +10433,8 @@ var VmAdapter = class {
8464
10433
  levelConfig: executionContext.secureProxyConfig,
8465
10434
  callGate: globalFunctionGate,
8466
10435
  exposeToSandbox: airlock.toRealm,
8467
- ownedBySandbox: airlock.isRealmValue
10436
+ ownedBySandbox: airlock.isRealmValue,
10437
+ heldBySandbox: airlock.isAirlockProxy
8468
10438
  })
8469
10439
  ) : value2;
8470
10440
  for (const name of [key, `__safe_${key}`]) {
@@ -8522,6 +10492,7 @@ var VmAdapter = class {
8522
10492
  INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT.runInContext(baseSandbox);
8523
10493
  } catch {
8524
10494
  }
10495
+ CLOSE_OBJECT_PROTOTYPE_SCRIPT.runInContext(baseSandbox);
8525
10496
  detachGlobalPrototype();
8526
10497
  Object.defineProperty(baseSandbox, "Object", {
8527
10498
  value: realmRuntime.createSafeObject(),
@@ -8592,25 +10563,25 @@ var VmAdapter = class {
8592
10563
  stats
8593
10564
  };
8594
10565
  } catch (error) {
8595
- const err = error;
10566
+ const thrown = describeThrown(error);
8596
10567
  stats.duration = Date.now() - startTime;
8597
10568
  stats.endTime = Date.now();
8598
10569
  if (memoryTracker) {
8599
10570
  const memSnapshot = memoryTracker.getSnapshot();
8600
10571
  stats.memoryUsage = memSnapshot.peakTrackedBytes;
8601
10572
  }
8602
- const isMemoryLimit = err instanceof MemoryLimitError || typeof err === "object" && err !== null && err.code === "MEMORY_LIMIT_EXCEEDED";
10573
+ const isMemoryLimit = error instanceof MemoryLimitError || memoryTracker?.hasExceededLimit() === true && isMemoryLimitPayload(error);
8603
10574
  if (isMemoryLimit) {
8604
10575
  const snapshot = memoryTracker?.getSnapshot();
8605
10576
  return {
8606
10577
  success: false,
8607
10578
  error: {
8608
10579
  name: "MemoryLimitError",
8609
- message: typeof err.message === "string" ? err.message : "Memory limit exceeded",
10580
+ message: thrown.message ?? "Memory limit exceeded",
8610
10581
  code: "MEMORY_LIMIT_EXCEEDED",
8611
10582
  data: {
8612
- usedBytes: err instanceof MemoryLimitError ? err.usedBytes : snapshot?.trackedBytes ?? 0,
8613
- limitBytes: err instanceof MemoryLimitError ? err.limitBytes : config.memoryLimit ?? 0
10583
+ usedBytes: error instanceof MemoryLimitError ? error.usedBytes : snapshot?.trackedBytes ?? 0,
10584
+ limitBytes: error instanceof MemoryLimitError ? error.limitBytes : config.memoryLimit ?? 0
8614
10585
  }
8615
10586
  },
8616
10587
  stats
@@ -8621,7 +10592,7 @@ var VmAdapter = class {
8621
10592
  success: false,
8622
10593
  error: {
8623
10594
  name: "VMExecutionError",
8624
- message: error,
10595
+ message: thrown.message ?? "",
8625
10596
  code: "VM_EXECUTION_ERROR"
8626
10597
  },
8627
10598
  stats
@@ -8631,13 +10602,18 @@ var VmAdapter = class {
8631
10602
  return {
8632
10603
  success: false,
8633
10604
  error: {
8634
- name: err.name || "VMExecutionError",
8635
- message: err.message || "Unknown VM execution error",
8636
- stack: sanitizeStackTrace(err.stack, shouldSanitize),
10605
+ name: thrown.name || "VMExecutionError",
10606
+ message: thrown.message || THROWN_WITHOUT_MESSAGE,
10607
+ stack: sanitizeStackTrace(thrown.stack, shouldSanitize),
8637
10608
  code: "VM_EXECUTION_ERROR"
8638
10609
  },
8639
10610
  stats
8640
10611
  };
10612
+ } finally {
10613
+ try {
10614
+ endDeadlineChecks?.();
10615
+ } catch {
10616
+ }
8641
10617
  }
8642
10618
  }
8643
10619
  /**
@@ -8648,188 +10624,12 @@ var VmAdapter = class {
8648
10624
  }
8649
10625
  };
8650
10626
 
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
10627
  // libs/core/src/adapters/worker-pool/worker-script.ts
8829
10628
  var port = import_worker_threads.parentPort;
8830
10629
  if (!port) {
8831
10630
  throw new Error("worker-script.ts must run inside a worker thread");
8832
10631
  }
10632
+ var nextEventLoopTurn = setImmediate;
8833
10633
  var DANGEROUS_GLOBALS = [
8834
10634
  "parentPort",
8835
10635
  "workerData",
@@ -8909,6 +10709,16 @@ port.on("message", async (raw) => {
8909
10709
  });
8910
10710
  async function handleExecute(msg) {
8911
10711
  const startTime = Date.now();
10712
+ if (currentExecution) {
10713
+ sendMessage({
10714
+ type: "result",
10715
+ requestId: msg.requestId,
10716
+ success: false,
10717
+ error: { name: "WorkerBusyError", message: "The worker is still running another execution" },
10718
+ stats: resultStats({ duration: 0, toolCallCount: 0, iterationCount: 0, startTime, endTime: startTime })
10719
+ });
10720
+ return;
10721
+ }
8912
10722
  const config = msg.config;
8913
10723
  const stats = {
8914
10724
  duration: 0,
@@ -8944,7 +10754,10 @@ async function handleExecute(msg) {
8944
10754
  execution.aborted = value;
8945
10755
  },
8946
10756
  hostToolBridge: (requestJson) => relayToolRequest(execution, requestJson),
8947
- consoleHandler: config.hasConsoleHandler ? (level, text) => sendMessage({ type: "console", requestId: execution.id, level, args: [text] }) : void 0,
10757
+ consoleHandler: config.hasConsoleHandler ? (level, text) => {
10758
+ if (currentExecution !== execution) return;
10759
+ sendMessage({ type: "console", requestId: execution.id, level, args: [text] });
10760
+ } : void 0,
8948
10761
  secureProxyConfig: config.secureProxyConfig,
8949
10762
  toolNamespaces: config.toolNamespaces,
8950
10763
  realmGlobalAllowlist: config.realmGlobalAllowlist,
@@ -9001,8 +10814,17 @@ async function handleExecute(msg) {
9001
10814
  if (currentExecution === execution) {
9002
10815
  currentExecution = null;
9003
10816
  }
10817
+ confirmIdle(msg.requestId);
9004
10818
  }
9005
10819
  }
10820
+ function confirmIdle(requestId) {
10821
+ nextEventLoopTurn(() => {
10822
+ try {
10823
+ sendMessage({ type: "idle", requestId });
10824
+ } catch {
10825
+ }
10826
+ });
10827
+ }
9006
10828
  function createSandboxAdapter(config) {
9007
10829
  const doubleVm = config.doubleVm;
9008
10830
  if (doubleVm && doubleVm.enabled === false) {