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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -328,9 +328,12 @@ function sanitizeObjectValue(value, options, depth, context) {
328
328
  const sanitizedMap = ObjectCreate(null);
329
329
  const entries = ReflectApply(MapProtoEntries, inspected, []);
330
330
  for (const [key, val] of entries) {
331
+ context.propCount.count++;
332
+ if (context.propCount.count > maxProperties) {
333
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
334
+ }
331
335
  if (typeof key !== "string") continue;
332
336
  if (DANGEROUS_KEYS.has(key)) continue;
333
- context.propCount.count++;
334
337
  sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
335
338
  }
336
339
  return sanitizedMap;
@@ -340,6 +343,9 @@ function sanitizeObjectValue(value, options, depth, context) {
340
343
  const result = [];
341
344
  for (const item of iter) {
342
345
  context.propCount.count++;
346
+ if (context.propCount.count > maxProperties) {
347
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
348
+ }
343
349
  result.push(sanitizeValue(item, options, depth + 1, context));
344
350
  }
345
351
  return result;
@@ -427,7 +433,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
427
433
  }
428
434
  if (ArrayIsArray(value)) {
429
435
  if (currentPath.has(value)) {
430
- return 4;
436
+ return CIRCULAR_MARKER_BYTES;
431
437
  }
432
438
  currentPath.add(value);
433
439
  try {
@@ -453,7 +459,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
453
459
  if (type === "object") {
454
460
  const object = value;
455
461
  if (currentPath.has(object)) {
456
- return 4;
462
+ return CIRCULAR_MARKER_BYTES;
457
463
  }
458
464
  if (!isPlainObject(object)) {
459
465
  if (hasBrand(DateProtoGetTime, object)) {
@@ -544,11 +550,12 @@ function checkSerializedSize(value, maxBytes) {
544
550
  return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
545
551
  }
546
552
  }
547
- var DANGEROUS_KEYS, ReflectApply, ReflectGet, ArrayIsArray, ObjectKeys, ObjectCreate, ObjectGetPrototypeOf, NumberIsFinite, MathFloor, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoSourceGetter, RegExpFlagGetters, MapProtoSizeGetter, SetProtoSizeGetter;
553
+ var DANGEROUS_KEYS, CIRCULAR_MARKER_BYTES, ReflectApply, ReflectGet, ArrayIsArray, ObjectKeys, ObjectCreate, ObjectGetPrototypeOf, NumberIsFinite, MathFloor, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoSourceGetter, RegExpFlagGetters, MapProtoSizeGetter, SetProtoSizeGetter;
548
554
  var init_value_sanitizer = __esm({
549
555
  "libs/core/src/value-sanitizer.ts"() {
550
556
  "use strict";
551
557
  DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
558
+ CIRCULAR_MARKER_BYTES = 12;
552
559
  ReflectApply = Reflect.apply;
553
560
  ReflectGet = Reflect.get;
554
561
  ArrayIsArray = Array.isArray;
@@ -1034,6 +1041,11 @@ var init_global_function_gate = __esm({
1034
1041
  });
1035
1042
 
1036
1043
  // libs/core/src/secure-proxy.ts
1044
+ function isArrayIndexKey(property) {
1045
+ if (typeof property !== "string") return false;
1046
+ const index = Number(property);
1047
+ return index >>> 0 === index && index !== 4294967295 && String(index) === property;
1048
+ }
1037
1049
  function getBlockedPropertiesForLevel(level) {
1038
1050
  const blocked = /* @__PURE__ */ new Set();
1039
1051
  if (level !== "PERMISSIVE") {
@@ -1197,6 +1209,7 @@ function isOfBuiltinKind(receiver, homes) {
1197
1209
  return false;
1198
1210
  }
1199
1211
  function passesHostValuesToCallbacks(fn, builtinMethod) {
1212
+ if (COMPARING_BUILTINS.has(fn)) return false;
1200
1213
  return builtinMethod || fn === JsonParse || fn === JsonStringify2 || typeof fn === "function" && boundBuiltinMethods.has(fn);
1201
1214
  }
1202
1215
  function isProxyable(value) {
@@ -1280,10 +1293,11 @@ function createSecureProxy(target, options = {}) {
1280
1293
  };
1281
1294
  const guardObjectArgument = (value) => {
1282
1295
  if (value === null || typeof value !== "object") return value;
1283
- if (proxySet.has(value) || guardedArguments.has(value) || Array.isArray(value)) return value;
1296
+ if (proxySet.has(value) || guardedArguments.has(value)) return value;
1284
1297
  if (heldBySandbox && heldBySandbox(value)) return value;
1285
1298
  const existing = lookupGuard(value);
1286
1299
  if (existing) return existing;
1300
+ if (Array.isArray(value)) return guardArrayArgument(value);
1287
1301
  const original = value;
1288
1302
  const guard = new Proxy(/* @__PURE__ */ Object.create(null), {
1289
1303
  get: (_shell, property) => guardMember(ReflectGet2(original, property, original), original),
@@ -1308,6 +1322,24 @@ function createSecureProxy(target, options = {}) {
1308
1322
  guardedArguments.set(guard, original);
1309
1323
  return guard;
1310
1324
  };
1325
+ const guardArrayArgument = (original) => {
1326
+ const guard = new Proxy(original, {
1327
+ get: (target2, property) => {
1328
+ const member = ReflectGet2(target2, property, target2);
1329
+ return property === "length" || isArrayIndexKey(property) ? member : guardMember(member, target2);
1330
+ },
1331
+ // What a host function stores in the array is a host value like any other
1332
+ set: (target2, property, stored) => ReflectSet(target2, property, toSandbox(stored), target2),
1333
+ defineProperty: (target2, property, descriptor) => {
1334
+ if ("get" in descriptor || "set" in descriptor) return false;
1335
+ const stored = "value" in descriptor ? { ...descriptor, value: toSandbox(descriptor.value) } : descriptor;
1336
+ return ReflectDefineProperty(target2, property, stored);
1337
+ }
1338
+ });
1339
+ storeGuard(original, guard);
1340
+ guardedArguments.set(guard, original);
1341
+ return guard;
1342
+ };
1311
1343
  const guardMember = (member, holder) => {
1312
1344
  if (typeof member !== "function") return guardObjectArgument(member);
1313
1345
  const method = function guardedMethod(...hostArgs) {
@@ -1628,7 +1660,7 @@ function unwrapSecureProxy(value) {
1628
1660
  }
1629
1661
  return current;
1630
1662
  }
1631
- var ObjectGetOwnPropertyDescriptor2, ObjectToString, FunctionBind, ReflectGet2, ReflectSet, ReflectDefineProperty, ReflectGetOwnPropertyDescriptor2, ReflectOwnKeys3, ReflectApply5, ReflectHas, ReflectConstruct, ObjectGetPrototypeOf4, HostObjectPrototype, ReflectObject, PINNED_REFLECT_VALUES, FunctionCtor, AsyncFunctionCtor, GeneratorFunctionCtor, AsyncGeneratorFunctionCtor, MIN_MEMBRANE_RECURSION_DEPTH, BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, gatedProxyCaches, proxyCache, proxySet, proxyToTarget, INTERNAL_SLOT_BUILTINS, INTERNAL_SLOT_TYPES, boundBuiltinMethods, argumentGuards, gatedArgumentGuards, guardedArguments, JsonParse, JsonStringify2, HOST_RECEIVER_MESSAGE, HOST_RECEIVER_KIND_MESSAGE;
1663
+ var ObjectGetOwnPropertyDescriptor2, ObjectToString, FunctionBind, ReflectGet2, ReflectSet, ReflectDefineProperty, ReflectGetOwnPropertyDescriptor2, ReflectOwnKeys3, ReflectApply5, ReflectHas, ReflectConstruct, ObjectGetPrototypeOf4, HostObjectPrototype, ReflectObject, PINNED_REFLECT_VALUES, FunctionCtor, AsyncFunctionCtor, GeneratorFunctionCtor, AsyncGeneratorFunctionCtor, MIN_MEMBRANE_RECURSION_DEPTH, BLOCKED_PROPERTY_CATEGORIES, BLOCKED_PROPERTIES, DEFAULT_SECURE_PROXY_CONFIG, FUNCTION_BLOCKED_PROPERTIES, gatedProxyCaches, proxyCache, proxySet, proxyToTarget, INTERNAL_SLOT_BUILTINS, INTERNAL_SLOT_TYPES, boundBuiltinMethods, argumentGuards, gatedArgumentGuards, guardedArguments, JsonParse, JsonStringify2, HOST_RECEIVER_MESSAGE, HOST_RECEIVER_KIND_MESSAGE, TypedArrayPrototype, COMPARING_BUILTINS;
1632
1664
  var init_secure_proxy = __esm({
1633
1665
  "libs/core/src/secure-proxy.ts"() {
1634
1666
  "use strict";
@@ -1803,6 +1835,15 @@ var init_secure_proxy = __esm({
1803
1835
  JsonStringify2 = JSON.stringify;
1804
1836
  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.";
1805
1837
  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).";
1838
+ TypedArrayPrototype = ObjectGetPrototypeOf4(Uint8Array.prototype);
1839
+ COMPARING_BUILTINS = /* @__PURE__ */ new Set([
1840
+ Array.prototype.includes,
1841
+ Array.prototype.indexOf,
1842
+ Array.prototype.lastIndexOf,
1843
+ TypedArrayPrototype["includes"],
1844
+ TypedArrayPrototype["indexOf"],
1845
+ TypedArrayPrototype["lastIndexOf"]
1846
+ ]);
1806
1847
  }
1807
1848
  });
1808
1849
 
@@ -1928,11 +1969,10 @@ var init_reference_config = __esm({
1928
1969
  });
1929
1970
 
1930
1971
  // libs/core/src/sidecar/reference-sidecar.ts
1931
- var import_crypto, SidecarLimitError, ReferenceNotFoundError, ReferenceSidecar;
1972
+ var SidecarLimitError, ReferenceNotFoundError, ReferenceSidecar;
1932
1973
  var init_reference_sidecar = __esm({
1933
1974
  "libs/core/src/sidecar/reference-sidecar.ts"() {
1934
1975
  "use strict";
1935
- import_crypto = require("crypto");
1936
1976
  init_reference_config();
1937
1977
  SidecarLimitError = class _SidecarLimitError extends Error {
1938
1978
  constructor(message, code, limit, current) {
@@ -2005,7 +2045,9 @@ var init_reference_sidecar = __esm({
2005
2045
  this.totalSize + size
2006
2046
  );
2007
2047
  }
2008
- const refId = `${REF_ID_PREFIX}${(0, import_crypto.randomUUID)()}${REF_ID_SUFFIX}`;
2048
+ const randomUUID = globalThis.crypto?.randomUUID?.bind(globalThis.crypto);
2049
+ if (!randomUUID) throw new Error("Secure random UUID generation is unavailable");
2050
+ const refId = `${REF_ID_PREFIX}${randomUUID()}${REF_ID_SUFFIX}`;
2009
2051
  this.storage.set(refId, Buffer.from(buffer));
2010
2052
  this.totalSize += size;
2011
2053
  this.metadata.set(refId, {
@@ -2467,28 +2509,38 @@ var init_reference_resolver = __esm({
2467
2509
  /**
2468
2510
  * Check if a value contains any reference IDs
2469
2511
  *
2512
+ * Every value is looked at, at any depth: a reference or composite past `maxResolutionDepth`
2513
+ * cannot be resolved, and it must still be found, so that `resolve()` refuses the call rather
2514
+ * than the handler receiving it unresolved. The value is walked with a list instead of by
2515
+ * recursion, so a deep value cannot exhaust the stack, and an object is looked at once.
2516
+ *
2470
2517
  * @param value - The value to check
2471
- * @param depth - Current recursion depth (internal)
2518
+ * @param _depth - Unused; kept for callers that pass a depth
2472
2519
  * @returns true if the value or any nested value is a reference
2473
2520
  */
2474
- containsReferences(value, depth = 0) {
2475
- if (depth > this.config.maxResolutionDepth) {
2476
- return false;
2477
- }
2478
- if (isReferenceId(value) || isCompositeHandle(value)) {
2479
- return true;
2480
- }
2481
- if (Array.isArray(value)) {
2482
- const len = untrustedLength(value);
2483
- for (let i = 0; i < len; i++) {
2484
- if (this.containsReferences(untrustedAt(value, i), depth + 1)) {
2485
- return true;
2521
+ containsReferences(value, _depth = 0) {
2522
+ const pending = [value];
2523
+ const seen = /* @__PURE__ */ new Set();
2524
+ while (pending.length > 0) {
2525
+ const current = pending.pop();
2526
+ if (isReferenceId(current) || isCompositeHandle(current)) {
2527
+ return true;
2528
+ }
2529
+ if (current === null || typeof current !== "object" || seen.has(current)) {
2530
+ continue;
2531
+ }
2532
+ seen.add(current);
2533
+ if (Array.isArray(current)) {
2534
+ const len = untrustedLength(current);
2535
+ for (let i = 0; i < len; i++) {
2536
+ pending.push(untrustedAt(current, i));
2486
2537
  }
2538
+ continue;
2539
+ }
2540
+ const members = Object.values(current);
2541
+ for (let i = 0; i < members.length; i++) {
2542
+ pending.push(members[i]);
2487
2543
  }
2488
- return false;
2489
- }
2490
- if (value !== null && typeof value === "object") {
2491
- return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
2492
2544
  }
2493
2545
  return false;
2494
2546
  }
@@ -4164,7 +4216,9 @@ function realmArrayAccountingSource(memoryLimit) {
4164
4216
 
4165
4217
  // An array literal with spreads: [a, ...b, ...c] is compiled to
4166
4218
  // __safe_array(__safe_arrayStart(), [a, ...__safe_spread(b), ...__safe_spread(c)])
4167
- // so that each source is seen before it is spread and the result when it exists.
4219
+ // so that each source is seen before it is spread and the result when it exists. One without
4220
+ // spreads, [a, b], is compiled to __safe_array(0, [a, b]): it has no frame, and its slots are
4221
+ // checked and charged like those of any array.
4168
4222
  var frames = [];
4169
4223
  var nextId = 1;
4170
4224
 
@@ -4226,7 +4280,7 @@ function realmArrayAccountingSource(memoryLimit) {
4226
4280
 
4227
4281
  function arrayFinish(id, array) {
4228
4282
  var largest = 0;
4229
- for (var i = frames.length - 1; i >= 0; i--) {
4283
+ for (var i = id === 0 ? -1 : frames.length - 1; i >= 0; i--) {
4230
4284
  if (frames[i].id === id) {
4231
4285
  largest = frames[i].largest;
4232
4286
  frames.length = i;
@@ -4234,7 +4288,7 @@ function realmArrayAccountingSource(memoryLimit) {
4234
4288
  }
4235
4289
  }
4236
4290
  if (isArray(array)) {
4237
- checkLength(array.length, 'Array spread');
4291
+ checkLength(array.length, id === 0 ? 'Array literal' : 'Array spread');
4238
4292
  charge(array.length - largest);
4239
4293
  }
4240
4294
  return array;
@@ -5776,15 +5830,73 @@ var init_console_handler = __esm({
5776
5830
  var toText = ''.constructor;
5777
5831
  var freeze = Object.freeze;
5778
5832
  var RealmError = Error;
5833
+ var apply = Reflect.apply;
5834
+ var isArray = Array.isArray;
5835
+ var stringValueOf = ''.constructor.prototype.valueOf;
5836
+ var numberValueOf = (0).constructor.prototype.valueOf;
5837
+
5838
+ // Whether a value has the internal slot that a built-in's valueOf reads.
5839
+ function hasSlot(valueOf, value) {
5840
+ try {
5841
+ apply(valueOf, value, []);
5842
+ return true;
5843
+ } catch (e) {
5844
+ return false;
5845
+ }
5846
+ }
5779
5847
 
5780
- function formatArgument(value) {
5848
+ // The JSON text of a value, given up as soon as it would be longer than limit characters. A
5849
+ // value referenced many times is written as many times, so the text can be far longer than the
5850
+ // value is large. What each member adds is counted as JSON.stringify writes it, and the count
5851
+ // is a lower bound of its length (an escape only adds), so a text within the limit is never
5852
+ // given up. The members JSON.stringify visits are counted as well, also those it leaves out (a
5853
+ // function, undefined): at most as many as the limit has characters.
5854
+ var TOO_LARGE = {};
5855
+ function stringifyWithin(value, limit) {
5856
+ var length = 0;
5857
+ var visits = 0;
5858
+ var root = true;
5859
+ return stringify(value, function (key, member) {
5860
+ if (++visits > limit) throw TOO_LARGE;
5861
+ // A String or Number object is written as what it converts to; converted here, the way
5862
+ // JSON.stringify converts it and once, so the count is of what is written.
5863
+ if (member !== null && typeof member === 'object') {
5864
+ if (hasSlot(stringValueOf, member)) member = toText(member);
5865
+ else if (hasSlot(numberValueOf, member)) member = +member;
5866
+ }
5867
+ var added;
5868
+ var kind = typeof member;
5869
+ if (kind === 'string') added = member.length + 2;
5870
+ else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
5871
+ else if (kind === 'boolean') added = member ? 4 : 5;
5872
+ else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
5873
+ else added = 0;
5874
+ if (!root) {
5875
+ // An element of an array is written, as null if nothing else; a member of an object
5876
+ // that is written has its key in front of it.
5877
+ if (isArray(this)) added = added || 4;
5878
+ else if (added > 0) added += key.length + 3;
5879
+ }
5880
+ root = false;
5881
+ length += added;
5882
+ if (length > limit) throw TOO_LARGE;
5883
+ return member;
5884
+ });
5885
+ }
5886
+
5887
+ // An argument as it is written in the line, in at most room characters for an object: an
5888
+ // object is written only when the line has room left, and its text within that room. TOO_LARGE
5889
+ // when it does not fit.
5890
+ function formatArgument(value, room) {
5781
5891
  if (value === undefined) return 'undefined';
5782
5892
  if (value === null) return 'null';
5783
5893
  if (typeof value === 'object') {
5894
+ if (room <= 0) throw TOO_LARGE;
5784
5895
  try {
5785
- var json = stringify(value);
5896
+ var json = stringifyWithin(value, room);
5786
5897
  return json === undefined ? '' : json;
5787
5898
  } catch (e) {
5899
+ if (e === TOO_LARGE) throw e;
5788
5900
  return toText(value);
5789
5901
  }
5790
5902
  }
@@ -5795,19 +5907,38 @@ var init_console_handler = __esm({
5795
5907
  var callCount = 0;
5796
5908
  var totalBytes = 0;
5797
5909
 
5910
+ function tooLarge() {
5911
+ return new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
5912
+ }
5913
+
5798
5914
  function method(level) {
5799
5915
  return (...args) => {
5800
5916
  callCount++;
5801
5917
  if (callCount > maxCalls) {
5802
5918
  throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
5803
5919
  }
5920
+ // The line is measured as it is built: what an argument may add is the room the limit
5921
+ // leaves, so the work done on a line that does not fit is in proportion to the limit.
5804
5922
  var line = '';
5805
5923
  for (var i = 0; i < args.length; i++) {
5806
- line += (i === 0 ? '' : ' ') + formatArgument(args[i]);
5924
+ var separator = i === 0 ? '' : ' ';
5925
+ var text;
5926
+ try {
5927
+ text = formatArgument(args[i], maxBytes - totalBytes - line.length - separator.length);
5928
+ } catch (e) {
5929
+ if (e !== TOO_LARGE) throw e;
5930
+ totalBytes = maxBytes + 1;
5931
+ throw tooLarge();
5932
+ }
5933
+ line += separator + text;
5934
+ if (totalBytes + line.length > maxBytes) {
5935
+ totalBytes = maxBytes + 1;
5936
+ throw tooLarge();
5937
+ }
5807
5938
  }
5808
5939
  totalBytes += line.length;
5809
5940
  if (totalBytes > maxBytes) {
5810
- throw new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
5941
+ throw tooLarge();
5811
5942
  }
5812
5943
  try {
5813
5944
  write(level, line);
@@ -5829,6 +5960,81 @@ var init_console_handler = __esm({
5829
5960
  }
5830
5961
  });
5831
5962
 
5963
+ // libs/core/src/bounded-json.ts
5964
+ function hasSlot(valueOf, value) {
5965
+ try {
5966
+ ReflectApply7(valueOf, value, []);
5967
+ return true;
5968
+ } catch {
5969
+ return false;
5970
+ }
5971
+ }
5972
+ function stringifyWithin(value, limit) {
5973
+ let bytes = 0;
5974
+ let visits = 0;
5975
+ const maxVisits = Math.max(1e4, Math.min(1e6, limit * 10));
5976
+ let root = true;
5977
+ return JSONStringify(value, function(key, member) {
5978
+ if (++visits > maxVisits) throw new JsonTraversalLimitError(maxVisits);
5979
+ if (member !== null && typeof member === "object") {
5980
+ if (hasSlot(StringValueOf, member)) member = String(member);
5981
+ else if (hasSlot(NumberValueOf, member)) member = Number(member);
5982
+ }
5983
+ let added;
5984
+ switch (typeof member) {
5985
+ case "string":
5986
+ added = member.length + 2;
5987
+ break;
5988
+ case "number":
5989
+ added = Number.isFinite(member) ? String(member).length : 4;
5990
+ break;
5991
+ case "boolean":
5992
+ added = member ? 4 : 5;
5993
+ break;
5994
+ case "object":
5995
+ case "bigint":
5996
+ added = member === null ? 4 : 2;
5997
+ break;
5998
+ default:
5999
+ added = 0;
6000
+ }
6001
+ if (!root) {
6002
+ if (ArrayIsArray4(this)) added = added || 4;
6003
+ else if (added > 0) added += key.length + 3;
6004
+ }
6005
+ root = false;
6006
+ bytes += added;
6007
+ if (bytes > limit) throw new JsonTooLargeError(limit);
6008
+ return member;
6009
+ });
6010
+ }
6011
+ function utf8Length(value) {
6012
+ return Buffer.byteLength(value, "utf8");
6013
+ }
6014
+ var JSONStringify, ReflectApply7, ArrayIsArray4, StringValueOf, NumberValueOf, JsonTooLargeError, JsonTraversalLimitError;
6015
+ var init_bounded_json = __esm({
6016
+ "libs/core/src/bounded-json.ts"() {
6017
+ "use strict";
6018
+ JSONStringify = JSON.stringify;
6019
+ ReflectApply7 = Reflect.apply;
6020
+ ArrayIsArray4 = Array.isArray;
6021
+ StringValueOf = String.prototype.valueOf;
6022
+ NumberValueOf = Number.prototype.valueOf;
6023
+ JsonTooLargeError = class extends Error {
6024
+ constructor(limit) {
6025
+ super(`JSON text exceeds ${limit} bytes`);
6026
+ this.name = "JsonTooLargeError";
6027
+ }
6028
+ };
6029
+ JsonTraversalLimitError = class extends Error {
6030
+ constructor(limit) {
6031
+ super(`JSON traversal exceeds ${limit} members`);
6032
+ this.name = "JsonTraversalLimitError";
6033
+ }
6034
+ };
6035
+ }
6036
+ });
6037
+
5832
6038
  // libs/core/src/tool-bridge.ts
5833
6039
  function utf8ByteLength2(value) {
5834
6040
  return Buffer.byteLength(value, "utf8");
@@ -6163,6 +6369,7 @@ function createHostToolBridge(executionContext, options) {
6163
6369
  "Tool returned an unsupported value",
6164
6370
  "TOOL_RESULT_NOT_SAFE"
6165
6371
  );
6372
+ executionContext.onToolBridgeFailure?.();
6166
6373
  return serializeResponse(
6167
6374
  {
6168
6375
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -6172,6 +6379,34 @@ function createHostToolBridge(executionContext, options) {
6172
6379
  maxPayloadBytes
6173
6380
  );
6174
6381
  }
6382
+ const resultLimit = executionContext.maxToolResultBytes;
6383
+ if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
6384
+ let tooLarge = false;
6385
+ let tooComplex = false;
6386
+ try {
6387
+ const resultJson = stringifyWithin(sanitizedResult, resultLimit);
6388
+ tooLarge = resultJson !== void 0 && utf8ByteLength2(resultJson) > resultLimit;
6389
+ } catch (error) {
6390
+ tooLarge = error instanceof JsonTooLargeError;
6391
+ tooComplex = error instanceof JsonTraversalLimitError;
6392
+ }
6393
+ if (tooLarge || tooComplex) {
6394
+ executionContext.onToolBridgeFailure?.();
6395
+ return serializeResponse(
6396
+ {
6397
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
6398
+ ok: false,
6399
+ error: {
6400
+ name: "ToolBridgeError",
6401
+ message: tooComplex ? "Tool result exceeds the traversal limit" : `Tool result exceeds the limit of ${resultLimit} bytes`,
6402
+ code: tooComplex ? "TOOL_RESULT_TOO_COMPLEX" : "TOOL_RESULT_TOO_LARGE",
6403
+ toolError: true
6404
+ }
6405
+ },
6406
+ maxPayloadBytes
6407
+ );
6408
+ }
6409
+ }
6175
6410
  if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
6176
6411
  const size = utf8ByteLength2(sanitizedResult);
6177
6412
  if (size >= referenceConfig.extractionThreshold) {
@@ -6179,6 +6414,20 @@ function createHostToolBridge(executionContext, options) {
6179
6414
  const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
6180
6415
  sanitizedResult = refId;
6181
6416
  } catch {
6417
+ executionContext.onToolBridgeFailure?.();
6418
+ return serializeResponse(
6419
+ {
6420
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
6421
+ ok: false,
6422
+ error: {
6423
+ name: "ToolBridgeError",
6424
+ message: "Tool result could not be stored in the reference sidecar",
6425
+ code: "TOOL_RESULT_NOT_STORED",
6426
+ toolError: true
6427
+ }
6428
+ },
6429
+ maxPayloadBytes
6430
+ );
6182
6431
  }
6183
6432
  }
6184
6433
  }
@@ -6193,6 +6442,7 @@ function createHostToolBridge(executionContext, options) {
6193
6442
  "Tool result must be JSON-serializable",
6194
6443
  "TOOL_RESULT_NOT_JSON"
6195
6444
  );
6445
+ executionContext.onToolBridgeFailure?.();
6196
6446
  return serializeResponse(
6197
6447
  {
6198
6448
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -6203,6 +6453,7 @@ function createHostToolBridge(executionContext, options) {
6203
6453
  );
6204
6454
  }
6205
6455
  if (utf8ByteLength2(okJson) > maxPayloadBytes) {
6456
+ executionContext.onToolBridgeFailure?.();
6206
6457
  return serializeResponse(
6207
6458
  {
6208
6459
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -6237,6 +6488,7 @@ var init_tool_bridge = __esm({
6237
6488
  "use strict";
6238
6489
  init_value_sanitizer();
6239
6490
  init_reference_resolver();
6491
+ init_bounded_json();
6240
6492
  TOOL_BRIDGE_PROTOCOL_VERSION = 1;
6241
6493
  }
6242
6494
  });
@@ -6310,7 +6562,8 @@ var init_suspicious_patterns = __esm({
6310
6562
  if (localConfig) {
6311
6563
  const defaultThreshold = localConfig.rapidEnumerationThreshold ?? 30;
6312
6564
  const overrides = localConfig.rapidEnumerationOverrides ?? {};
6313
- threshold = overrides[operationName] ?? defaultThreshold;
6565
+ const override = Object.prototype.hasOwnProperty.call(overrides, operationName) ? overrides[operationName] : void 0;
6566
+ threshold = typeof override === "number" ? override : defaultThreshold;
6314
6567
  }
6315
6568
  } catch {
6316
6569
  threshold = 30;
@@ -6392,11 +6645,11 @@ function serializeDoubleVmConfig(config) {
6392
6645
  function isExecutionMessage(msg) {
6393
6646
  return !isMemoryReportResultMessage(msg) && !isWorkerReadyMessage(msg);
6394
6647
  }
6395
- var import_crypto3, IDLE_CONFIRMATION_TIMEOUT_MS, DEFAULT_TOOL_PAYLOAD_BYTES, MESSAGE_ENVELOPE_BYTES, WorkerPoolAdapter;
6648
+ var import_crypto2, IDLE_CONFIRMATION_TIMEOUT_MS, DEFAULT_TOOL_PAYLOAD_BYTES, MESSAGE_ENVELOPE_BYTES, WorkerPoolAdapter;
6396
6649
  var init_worker_pool_adapter = __esm({
6397
6650
  "libs/core/src/adapters/worker-pool/worker-pool-adapter.ts"() {
6398
6651
  "use strict";
6399
- import_crypto3 = __toESM(require("crypto"));
6652
+ import_crypto2 = __toESM(require("crypto"));
6400
6653
  init_config();
6401
6654
  init_protocol();
6402
6655
  init_worker_slot();
@@ -6578,7 +6831,7 @@ var init_worker_pool_adapter = __esm({
6578
6831
  * else can see it idle (the caller asked for a worker because none was free).
6579
6832
  */
6580
6833
  async createAndAddSlot(executionId) {
6581
- const slotId = `worker-${Date.now()}-${import_crypto3.default.randomUUID()}`;
6834
+ const slotId = `worker-${Date.now()}-${import_crypto2.default.randomUUID()}`;
6582
6835
  const slot = new WorkerSlot(slotId, {
6583
6836
  memoryLimitMB: Math.round(this.config.memoryLimitPerWorker / 1024 / 1024),
6584
6837
  maxMessageSizeBytes: this.config.maxMessageSizeBytes,
@@ -6776,7 +7029,7 @@ var init_worker_pool_adapter = __esm({
6776
7029
  if (context.abortController?.signal.aborted) {
6777
7030
  throw new ExecutionAbortedError("Execution aborted before it started");
6778
7031
  }
6779
- const requestId = `exec-${Date.now()}-${import_crypto3.default.randomUUID()}`;
7032
+ const requestId = `exec-${Date.now()}-${import_crypto2.default.randomUUID()}`;
6780
7033
  const startTime = Date.now();
6781
7034
  const consoleSink = context.consoleHandler ? createConsoleSink(context.consoleHandler, context.config) : void 0;
6782
7035
  const serializedConfig = {
@@ -7431,6 +7684,32 @@ var init_tool_namespaces = __esm({
7431
7684
  }
7432
7685
  });
7433
7686
 
7687
+ // libs/core/src/realm-regex-backstop.ts
7688
+ var REALM_REGEX_BACKSTOP_SOURCE;
7689
+ var init_realm_regex_backstop = __esm({
7690
+ "libs/core/src/realm-regex-backstop.ts"() {
7691
+ "use strict";
7692
+ REALM_REGEX_BACKSTOP_SOURCE = `
7693
+ (function () {
7694
+ 'use strict';
7695
+ var defineProperty = Object.defineProperty;
7696
+ var freeze = Object.freeze;
7697
+ var RealmTypeError = TypeError;
7698
+ var proto = RegExp.prototype;
7699
+ var refuse = () => {
7700
+ throw new RealmTypeError('Regular expressions are not available in this sandbox');
7701
+ };
7702
+ freeze(refuse);
7703
+ var keys = ['exec', 'test', 'compile', Symbol.match, Symbol.matchAll, Symbol.replace, Symbol.search, Symbol.split];
7704
+ for (var i = 0; i < keys.length; i++) {
7705
+ defineProperty(proto, keys[i], { value: refuse, writable: false, configurable: false, enumerable: false });
7706
+ }
7707
+ freeze(proto);
7708
+ })()
7709
+ `.trim();
7710
+ }
7711
+ });
7712
+
7434
7713
  // libs/core/src/realm-stack.ts
7435
7714
  var STACK_CAPTURE_OFF_SOURCE;
7436
7715
  var init_realm_stack = __esm({
@@ -8092,6 +8371,10 @@ function generateParentVmBootstrap(options) {
8092
8371
  const __ag_FunctionToString = Function.prototype.toString;
8093
8372
  const __ag_ObjectToLocaleString = Object.prototype.toLocaleString;
8094
8373
  const __ag_Promise = Promise;
8374
+ const __ag_JSONStringify = JSON.stringify;
8375
+ const __ag_String = String;
8376
+ const __ag_StringValueOf = String.prototype.valueOf;
8377
+ const __ag_NumberValueOf = Number.prototype.valueOf;
8095
8378
 
8096
8379
  /**
8097
8380
  * Creates a "safe" error object that cannot be used to escape the sandbox.
@@ -8500,20 +8783,23 @@ function generateParentVmBootstrap(options) {
8500
8783
  * object, with a function member replaced by one that passes its arguments through
8501
8784
  * toSandboxValue (and keeps the script's object as its receiver), and an object member or
8502
8785
  * result guarded the same way. Its own properties are listed as they are, so a built-in that
8503
- * copies or serializes the object sees the same data. An array is data to every built-in and
8504
- * is passed as it is, as is a value that is behind the membrane already.
8786
+ * copies or serializes the object sees the same data. An array gets a guard that is still an
8787
+ * array, see guardArrayForHost. A value that is behind the membrane already is passed as it is.
8505
8788
  */
8506
8789
  function guardObjectForHost(value) {
8507
8790
  if (value === null || typeof value !== 'object') {
8508
8791
  return value;
8509
8792
  }
8510
- if (membraneProxies.has(value) || guardedHostArguments.has(value) || __ag_ArrayIsArray(value)) {
8793
+ if (membraneProxies.has(value) || guardedHostArguments.has(value)) {
8511
8794
  return value;
8512
8795
  }
8513
8796
  var existing = hostArgumentGuards.get(value);
8514
8797
  if (existing) {
8515
8798
  return existing;
8516
8799
  }
8800
+ if (__ag_ArrayIsArray(value)) {
8801
+ return guardArrayForHost(value);
8802
+ }
8517
8803
  // Over an empty object of this realm, not over the script's object: a frozen member of the
8518
8804
  // target would have to be reported as it is (proxy invariant), unguarded.
8519
8805
  var guard = new __ag_ParentProxy(__ag_objectCreate(null), {
@@ -8550,6 +8836,52 @@ function generateParentVmBootstrap(options) {
8550
8836
  return guard;
8551
8837
  }
8552
8838
 
8839
+ /**
8840
+ * An array of the script on its way into a built-in method of host data. The built-ins read
8841
+ * its length and its elements and spread it (concat), so its guard is a proxy of the array
8842
+ * itself, which is an array to them. An element and the length are answered as they are: they
8843
+ * are data. Every other member is read like a member of an object (guardMemberForHost): an
8844
+ * array can carry methods of its own, and the set operations call size, has and keys of
8845
+ * whatever set-like they are given, with the host's own values. A frozen method of the array
8846
+ * cannot be answered guarded (proxy invariant), so the built-in fails instead of calling it.
8847
+ */
8848
+ function guardArrayForHost(value) {
8849
+ var guard = new __ag_ParentProxy(value, {
8850
+ get: function(target, property) {
8851
+ var member = __ag_ReflectGet(target, property, target);
8852
+ if (property === 'length' || isArrayIndexKey(property)) {
8853
+ return member;
8854
+ }
8855
+ return guardMemberForHost(member, target);
8856
+ },
8857
+ // What a built-in stores in the array is a host value like any other.
8858
+ set: function(target, property, stored) {
8859
+ return __ag_ReflectSet(target, property, toSandboxValue(stored), target);
8860
+ },
8861
+ defineProperty: function(target, property, descriptor) {
8862
+ if ('get' in descriptor || 'set' in descriptor) {
8863
+ return false;
8864
+ }
8865
+ if ('value' in descriptor) {
8866
+ descriptor.value = toSandboxValue(descriptor.value);
8867
+ }
8868
+ return __ag_ReflectDefineProperty(target, property, descriptor);
8869
+ }
8870
+ });
8871
+ hostArgumentGuards.set(value, guard);
8872
+ guardedHostArguments.set(guard, value);
8873
+ return guard;
8874
+ }
8875
+
8876
+ /** Whether a property key is an array index ('0' to '4294967294' in canonical form). */
8877
+ function isArrayIndexKey(property) {
8878
+ if (typeof property !== 'string') {
8879
+ return false;
8880
+ }
8881
+ var index = +property;
8882
+ return index >>> 0 === index && index !== 4294967295 && '' + index === property;
8883
+ }
8884
+
8553
8885
  function guardMemberForHost(member, holder) {
8554
8886
  if (typeof member !== 'function') {
8555
8887
  return guardObjectForHost(member);
@@ -9343,8 +9675,11 @@ function generateParentVmBootstrap(options) {
9343
9675
  throw createSafeError('Operation name must be a non-empty string', 'TypeError');
9344
9676
  }
9345
9677
 
9346
- // Operation name pattern validation (whitelist)
9678
+ // Operation name pattern validation (whitelist). Each test starts at the beginning of the
9679
+ // name: a global or sticky pattern would otherwise go on from where its last match ended,
9680
+ // and decide the same name differently on the next call.
9347
9681
  if (validationConfig.validateOperationNames && typeof allowedOperationPattern !== 'undefined') {
9682
+ allowedOperationPattern.lastIndex = 0;
9348
9683
  if (!allowedOperationPattern.test(operationName)) {
9349
9684
  throw createSafeError('Operation "' + operationName + '" does not match allowed pattern');
9350
9685
  }
@@ -9353,6 +9688,7 @@ function generateParentVmBootstrap(options) {
9353
9688
  // Operation name pattern validation (blacklist)
9354
9689
  if (typeof blockedOperationPatterns !== 'undefined') {
9355
9690
  for (var i = 0; i < blockedOperationPatterns.length; i++) {
9691
+ blockedOperationPatterns[i].lastIndex = 0;
9356
9692
  if (blockedOperationPatterns[i].test(operationName)) {
9357
9693
  throw createSafeError('Operation "' + operationName + '" matches blocked pattern');
9358
9694
  }
@@ -9425,6 +9761,58 @@ function generateParentVmBootstrap(options) {
9425
9761
  return false;
9426
9762
  }
9427
9763
 
9764
+ /** Whether a value has the internal slot that a built-in's valueOf reads. */
9765
+ function hasSlot(valueOf, value) {
9766
+ try {
9767
+ __ag_ReflectApply(valueOf, value, []);
9768
+ return true;
9769
+ } catch (e) {
9770
+ return false;
9771
+ }
9772
+ }
9773
+
9774
+ /**
9775
+ * The JSON text of a value, given up as soon as it would be longer than limit bytes. A value
9776
+ * referenced many times is written as many times, so the text can be far longer than the value
9777
+ * is large. What each member adds is counted as JSON.stringify writes it, and the count is a
9778
+ * lower bound of its UTF-8 bytes (a code unit is at least one byte, an escape only adds), so a
9779
+ * value whose text is within the limit is never given up. The members JSON.stringify visits are
9780
+ * counted as well, also those it leaves out (a function, undefined): at most as many as the limit
9781
+ * has bytes.
9782
+ */
9783
+ var TOO_LARGE = {};
9784
+ function stringifyWithin(value, limit) {
9785
+ var bytes = 0;
9786
+ var visits = 0;
9787
+ var root = true;
9788
+ return __ag_JSONStringify(value, function(key, member) {
9789
+ if (++visits > limit) throw TOO_LARGE;
9790
+ // A String or Number object is written as what it converts to; converted here, the way
9791
+ // JSON.stringify converts it and once, so the count is of what is written.
9792
+ if (member !== null && typeof member === 'object') {
9793
+ if (hasSlot(__ag_StringValueOf, member)) member = __ag_String(member);
9794
+ else if (hasSlot(__ag_NumberValueOf, member)) member = +member;
9795
+ }
9796
+ var added;
9797
+ var kind = typeof member;
9798
+ if (kind === 'string') added = member.length + 2;
9799
+ else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
9800
+ else if (kind === 'boolean') added = member ? 4 : 5;
9801
+ else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
9802
+ else added = 0;
9803
+ if (!root) {
9804
+ // An element of an array is written, as null if nothing else; a member of an object
9805
+ // that is written has its key in front of it.
9806
+ if (__ag_ArrayIsArray(this)) added = added || 4;
9807
+ else if (added > 0) added += key.length + 3;
9808
+ }
9809
+ root = false;
9810
+ bytes += added;
9811
+ if (bytes > limit) throw TOO_LARGE;
9812
+ return member;
9813
+ });
9814
+ }
9815
+
9428
9816
  /**
9429
9817
  * Inner VM's callTool function
9430
9818
  * Proxies through parent VM with validation
@@ -9452,11 +9840,16 @@ function generateParentVmBootstrap(options) {
9452
9840
  throw createSafeError('Tool arguments must be an object', 'TypeError');
9453
9841
  }
9454
9842
 
9455
- // Double sanitization (defense in depth)
9843
+ // Double sanitization (defense in depth). The text is written within the payload limit (see
9844
+ // stringifyWithin), so what is done before the request is measured is in proportion to the
9845
+ // limit; in direct mode as well, where the request is held to the same limit below.
9456
9846
  var sanitizedArgs;
9457
9847
  try {
9458
- sanitizedArgs = JSON.parse(JSON.stringify(args));
9848
+ sanitizedArgs = JSON.parse(stringifyWithin(args, toolBridgeMaxPayloadBytes));
9459
9849
  } catch (e) {
9850
+ if (e === TOO_LARGE) {
9851
+ throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
9852
+ }
9460
9853
  throw createSafeError('Tool arguments must be JSON-serializable');
9461
9854
  }
9462
9855
 
@@ -9548,8 +9941,12 @@ function generateParentVmBootstrap(options) {
9548
9941
  throw createSafeError('Tool bridge returned invalid response');
9549
9942
  });
9550
9943
  } else {
9551
- // Direct mode: the rejection is mapped here rather than by launderThrown alone, which
9552
- // would drop the code the host uses to mark a failure of the tool itself.
9944
+ // Direct mode: the request is held to the payload limit as through the string bridge.
9945
+ if (exceedsPayloadLimit(JSON.stringify({ v: 1, tool: toolName, args: sanitizedArgs }), toolBridgeMaxPayloadBytes)) {
9946
+ throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
9947
+ }
9948
+ // The rejection is mapped here rather than by launderThrown alone, which would drop the
9949
+ // code the host uses to mark a failure of the tool itself.
9553
9950
  promise = deferHostCall(function() {
9554
9951
  return hostCallTool(toolName, sanitizedArgs);
9555
9952
  }, function(error) {
@@ -9559,9 +9956,16 @@ function generateParentVmBootstrap(options) {
9559
9956
  code = error && error.code;
9560
9957
  message = error && error.message;
9561
9958
  } catch (e) { /* treated as an unmarked failure */ }
9562
- if (code === 'TOOL_CALL_FAILED') {
9959
+ // A failure of the tool, or a result the host refused, keeps its code.
9960
+ if (
9961
+ code === 'TOOL_CALL_FAILED' ||
9962
+ code === 'TOOL_RESULT_NOT_STORED' ||
9963
+ code === 'TOOL_RESULT_TOO_LARGE' ||
9964
+ code === 'TOOL_RESULT_TOO_COMPLEX' ||
9965
+ code === 'TOOL_BRIDGE_RESPONSE_TOO_LARGE'
9966
+ ) {
9563
9967
  var text = typeof message === 'string' ? message : 'Tool call failed';
9564
- return markToolFailure(createSafeError(text), toolName, 'Error', text, 'TOOL_CALL_FAILED');
9968
+ return markToolFailure(createSafeError(text), toolName, 'Error', text, code);
9565
9969
  }
9566
9970
  return launderThrown(error);
9567
9971
  });
@@ -9821,8 +10225,9 @@ function generateParentVmBootstrap(options) {
9821
10225
  * Rate-limited console for inner VM
9822
10226
  */
9823
10227
  var consoleStats = { totalBytes: 0, callCount: 0 };
9824
- var maxConsoleBytes = hostConfig.maxConsoleOutputBytes || 65536;
9825
- var maxConsoleCalls = hostConfig.maxConsoleCalls || 100;
10228
+ // A limit of 0 is a limit: nothing may be written (it is not "unset").
10229
+ var maxConsoleBytes = typeof hostConfig.maxConsoleOutputBytes === 'number' ? hostConfig.maxConsoleOutputBytes : 65536;
10230
+ var maxConsoleCalls = typeof hostConfig.maxConsoleCalls === 'number' ? hostConfig.maxConsoleCalls : 100;
9826
10231
 
9827
10232
  function createSafeConsoleMethod(level) {
9828
10233
  return function() {
@@ -10375,7 +10780,7 @@ function generateParentVmBootstrap(options) {
10375
10780
  // After inner-runtime.js, whose one trusted pattern has kept its own matcher. Not optional:
10376
10781
  // a failure here aborts the execution.
10377
10782
  if (__ag_realmAllowed && __ag_realmAllowed.RegExp !== true) {
10378
- new vm.Script(${JSON.stringify(INNER_REALM_REGEX_BACKSTOP_SOURCE)}, {
10783
+ new vm.Script(${JSON.stringify(REALM_REGEX_BACKSTOP_SOURCE)}, {
10379
10784
  filename: 'inner-regex-backstop.js'
10380
10785
  }).runInContext(innerContext);
10381
10786
  }
@@ -10676,13 +11081,14 @@ function generateParentVmBootstrap(options) {
10676
11081
  })();
10677
11082
  `.trim();
10678
11083
  }
10679
- var MEMBRANE_MAX_RECURSION_DEPTH, NODEJS_24_DANGEROUS_GLOBALS, INNER_REALM_SCRUB_SOURCE, INNER_REALM_PARALLEL_SOURCE, STACK_RESERVE_ARGUMENTS, INNER_REALM_GUARD_SOURCE, INNER_REALM_SYMBOL_REGISTRY_SOURCE, REALM_RUNTIME_GLOBALS, INNER_REALM_REGEX_BACKSTOP_SOURCE, REALM_LOCKDOWN_SOURCE;
11084
+ var MEMBRANE_MAX_RECURSION_DEPTH, NODEJS_24_DANGEROUS_GLOBALS, INNER_REALM_SCRUB_SOURCE, INNER_REALM_PARALLEL_SOURCE, STACK_RESERVE_ARGUMENTS, INNER_REALM_GUARD_SOURCE, INNER_REALM_SYMBOL_REGISTRY_SOURCE, REALM_RUNTIME_GLOBALS, REALM_LOCKDOWN_SOURCE;
10680
11085
  var init_parent_vm_bootstrap = __esm({
10681
11086
  "libs/core/src/double-vm/parent-vm-bootstrap.ts"() {
10682
11087
  "use strict";
10683
11088
  init_global_function_gate();
10684
11089
  init_tool_namespaces();
10685
11090
  init_console_handler();
11091
+ init_realm_regex_backstop();
10686
11092
  init_deadline_guard();
10687
11093
  init_enclave_options();
10688
11094
  init_realm_stack();
@@ -10974,24 +11380,6 @@ var init_parent_vm_bootstrap = __esm({
10974
11380
  "TypeError",
10975
11381
  "RangeError"
10976
11382
  ];
10977
- INNER_REALM_REGEX_BACKSTOP_SOURCE = `
10978
- (function () {
10979
- 'use strict';
10980
- var defineProperty = Object.defineProperty;
10981
- var freeze = Object.freeze;
10982
- var RealmTypeError = TypeError;
10983
- var proto = RegExp.prototype;
10984
- var refuse = () => {
10985
- throw new RealmTypeError('Regular expressions are not available in this sandbox');
10986
- };
10987
- freeze(refuse);
10988
- var keys = ['exec', 'test', 'compile', Symbol.match, Symbol.matchAll, Symbol.replace, Symbol.search, Symbol.split];
10989
- for (var i = 0; i < keys.length; i++) {
10990
- defineProperty(proto, keys[i], { value: refuse, writable: false, configurable: false, enumerable: false });
10991
- }
10992
- freeze(proto);
10993
- })()
10994
- `.trim();
10995
11383
  REALM_LOCKDOWN_SOURCE = `
10996
11384
  (function () {
10997
11385
  'use strict';
@@ -11089,12 +11477,18 @@ var init_parent_vm_bootstrap = __esm({
11089
11477
  });
11090
11478
 
11091
11479
  // libs/core/src/double-vm/double-vm-wrapper.ts
11092
- var vm4, DoubleVmWrapper;
11480
+ function resultRefusal(message, code) {
11481
+ const error = new Error(message);
11482
+ resultRefusals.set(error, code);
11483
+ return error;
11484
+ }
11485
+ var vm4, resultRefusals, DoubleVmWrapper;
11093
11486
  var init_double_vm_wrapper = __esm({
11094
11487
  "libs/core/src/double-vm/double-vm-wrapper.ts"() {
11095
11488
  "use strict";
11096
11489
  vm4 = __toESM(require("vm"));
11097
11490
  init_value_sanitizer();
11491
+ init_bounded_json();
11098
11492
  init_secure_proxy();
11099
11493
  init_safe_error();
11100
11494
  init_reference_resolver();
@@ -11109,6 +11503,7 @@ var init_double_vm_wrapper = __esm({
11109
11503
  init_global_function_gate();
11110
11504
  init_parent_vm_bootstrap();
11111
11505
  init_suspicious_patterns();
11506
+ resultRefusals = /* @__PURE__ */ new WeakMap();
11112
11507
  DoubleVmWrapper = class {
11113
11508
  /**
11114
11509
  * @param config Double VM configuration
@@ -11432,33 +11827,72 @@ var init_double_vm_wrapper = __esm({
11432
11827
  }
11433
11828
  resolvedArgs = resolver.resolve(args);
11434
11829
  }
11830
+ let handlerCompleted = false;
11435
11831
  try {
11436
11832
  const result = await toolHandler(toolName, resolvedArgs);
11833
+ handlerCompleted = true;
11437
11834
  const sanitized = sanitizeValue(result, {
11438
11835
  maxDepth: config.maxSanitizeDepth,
11439
11836
  maxProperties: config.maxSanitizeProperties,
11440
11837
  allowDates: true,
11441
11838
  allowErrors: true
11442
11839
  });
11840
+ const resultLimit = executionContext.maxToolResultBytes;
11841
+ if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
11842
+ try {
11843
+ const resultJson = stringifyWithin(sanitized, resultLimit);
11844
+ if (resultJson !== void 0 && utf8Length(resultJson) > resultLimit) {
11845
+ throw resultRefusal(`Tool result exceeds the limit of ${resultLimit} bytes`, "TOOL_RESULT_TOO_LARGE");
11846
+ }
11847
+ } catch (error) {
11848
+ if (error instanceof JsonTraversalLimitError) {
11849
+ throw resultRefusal("Tool result exceeds the traversal limit", "TOOL_RESULT_TOO_COMPLEX");
11850
+ }
11851
+ if (error instanceof JsonTooLargeError) {
11852
+ throw resultRefusal(`Tool result exceeds the limit of ${resultLimit} bytes`, "TOOL_RESULT_TOO_LARGE");
11853
+ }
11854
+ throw error;
11855
+ }
11856
+ }
11857
+ let outgoing = sanitized;
11443
11858
  if (sidecar && referenceConfig && typeof sanitized === "string") {
11444
11859
  const size = Buffer.byteLength(sanitized, "utf-8");
11445
11860
  if (size >= referenceConfig.extractionThreshold) {
11446
11861
  try {
11447
- const refId = sidecar.store(sanitized, "tool-result", { origin: toolName });
11448
- return refId;
11449
- } catch (storageError) {
11450
- if (process.env["NODE_ENV"] !== "production") {
11451
- console.debug(
11452
- `[DoubleVmWrapper] Sidecar storage failed for tool "${toolName}": ${storageError.message}`
11453
- );
11454
- }
11455
- return sanitized;
11862
+ outgoing = sidecar.store(sanitized, "tool-result", { origin: toolName });
11863
+ } catch {
11864
+ throw resultRefusal("Tool result could not be stored in the reference sidecar", "TOOL_RESULT_NOT_STORED");
11456
11865
  }
11457
11866
  }
11458
11867
  }
11459
- return sanitized;
11868
+ const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
11869
+ let responseJson;
11870
+ try {
11871
+ responseJson = outgoing === void 0 ? void 0 : stringifyWithin(outgoing, maxPayloadBytes);
11872
+ } catch (error) {
11873
+ if (error instanceof JsonTraversalLimitError) {
11874
+ throw resultRefusal("Tool response exceeds traversal limit", "TOOL_RESULT_TOO_COMPLEX");
11875
+ }
11876
+ if (!(error instanceof JsonTooLargeError)) throw error;
11877
+ throw resultRefusal(
11878
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
11879
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
11880
+ );
11881
+ }
11882
+ if (responseJson !== void 0 && utf8Length(responseJson) > maxPayloadBytes) {
11883
+ throw resultRefusal(
11884
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
11885
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
11886
+ );
11887
+ }
11888
+ return outgoing;
11460
11889
  } catch (error) {
11890
+ if (handlerCompleted) executionContext.onToolBridgeFailure?.();
11461
11891
  const err = error;
11892
+ const refused = resultRefusals.get(error);
11893
+ if (refused) {
11894
+ throw createSafeError(err.message, "Error", refused);
11895
+ }
11462
11896
  throw createSafeError(
11463
11897
  `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`,
11464
11898
  "Error",
@@ -11711,6 +12145,12 @@ function createSafeRuntime(context, options) {
11711
12145
  const secureProxyConfig = options?.secureProxyConfig;
11712
12146
  const memoryTracker = options?.memoryTracker;
11713
12147
  const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
12148
+ const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
12149
+ const codedError = (message, code) => Object.assign(new Error(message), { code });
12150
+ const refuseToolResult = (message, code) => {
12151
+ context.onToolBridgeFailure?.();
12152
+ throw codedError(message, code);
12153
+ };
11714
12154
  const proxyOptions = {
11715
12155
  ...secureProxyConfig ? { levelConfig: secureProxyConfig } : {},
11716
12156
  ...options?.exposeToSandbox ? { exposeToSandbox: options.exposeToSandbox } : {},
@@ -11737,6 +12177,21 @@ function createSafeRuntime(context, options) {
11737
12177
  if (!context.toolHandler) {
11738
12178
  throw createSafeError("No tool handler configured. Cannot execute tool calls.");
11739
12179
  }
12180
+ let requestJson;
12181
+ try {
12182
+ requestJson = stringifyWithin({ v: 1, tool: toolName, args }, maxPayloadBytes);
12183
+ } catch (error) {
12184
+ if (error instanceof JsonTooLargeError) {
12185
+ throw createSafeError(`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`, "RangeError");
12186
+ }
12187
+ if (error instanceof JsonTraversalLimitError) {
12188
+ throw createSafeError("Tool request exceeds traversal limit", "RangeError");
12189
+ }
12190
+ throw createSafeTypeError("Tool arguments must be JSON-serializable");
12191
+ }
12192
+ if (requestJson !== void 0 && utf8Length(requestJson) > maxPayloadBytes) {
12193
+ throw createSafeError(`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`, "RangeError");
12194
+ }
11740
12195
  let resolvedArgs = args;
11741
12196
  if (resolver && resolver.containsReferences(args)) {
11742
12197
  if (resolver.wouldExceedLimit(args)) {
@@ -11756,12 +12211,34 @@ function createSafeRuntime(context, options) {
11756
12211
  }
11757
12212
  try {
11758
12213
  const result = await context.toolHandler(toolName, resolvedArgs);
11759
- const sanitized = sanitizeValue(result, {
11760
- maxDepth: 20,
11761
- maxProperties: 1e4,
11762
- allowDates: true,
11763
- allowErrors: true
11764
- });
12214
+ let sanitized;
12215
+ try {
12216
+ sanitized = sanitizeValue(result, {
12217
+ maxDepth: config.maxSanitizeDepth ?? 20,
12218
+ maxProperties: config.maxSanitizeProperties ?? 1e4,
12219
+ allowDates: true,
12220
+ allowErrors: true
12221
+ });
12222
+ } catch {
12223
+ refuseToolResult("Tool returned an unsupported value", "TOOL_RESULT_NOT_SAFE");
12224
+ }
12225
+ const resultLimit = context.maxToolResultBytes;
12226
+ if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
12227
+ let tooLarge = false;
12228
+ try {
12229
+ const resultJson = stringifyWithin(sanitized, resultLimit);
12230
+ tooLarge = resultJson !== void 0 && utf8Length(resultJson) > resultLimit;
12231
+ } catch (error) {
12232
+ if (error instanceof JsonTraversalLimitError) {
12233
+ refuseToolResult("Tool result exceeds the traversal limit", "TOOL_RESULT_TOO_COMPLEX");
12234
+ }
12235
+ if (!(error instanceof JsonTooLargeError)) throw error;
12236
+ tooLarge = true;
12237
+ }
12238
+ if (tooLarge) {
12239
+ refuseToolResult(`Tool result exceeds the limit of ${resultLimit} bytes`, "TOOL_RESULT_TOO_LARGE");
12240
+ }
12241
+ }
11765
12242
  let value = sanitized;
11766
12243
  if (sidecar && referenceConfig && typeof sanitized === "string") {
11767
12244
  const size = Buffer.byteLength(sanitized, "utf-8");
@@ -11769,27 +12246,47 @@ function createSafeRuntime(context, options) {
11769
12246
  try {
11770
12247
  value = sidecar.store(sanitized, "tool-result", { origin: toolName });
11771
12248
  } catch {
11772
- value = sanitized;
12249
+ refuseToolResult("Tool result could not be stored in the reference sidecar", "TOOL_RESULT_NOT_STORED");
11773
12250
  }
11774
12251
  }
11775
12252
  }
12253
+ let responseJson;
12254
+ try {
12255
+ responseJson = value === void 0 ? void 0 : stringifyWithin(value, maxPayloadBytes);
12256
+ } catch (error) {
12257
+ if (error instanceof JsonTraversalLimitError) {
12258
+ refuseToolResult("Tool response exceeds traversal limit", "TOOL_RESULT_TOO_COMPLEX");
12259
+ }
12260
+ if (!(error instanceof JsonTooLargeError)) throw error;
12261
+ refuseToolResult(
12262
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
12263
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
12264
+ );
12265
+ }
12266
+ if (responseJson !== void 0 && utf8Length(responseJson) > maxPayloadBytes) {
12267
+ refuseToolResult(
12268
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
12269
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
12270
+ );
12271
+ }
11776
12272
  return throwOnError ? value : plainResult({ success: true, data: value });
11777
12273
  } catch (error) {
11778
12274
  const err = error;
11779
12275
  const message = `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`;
11780
12276
  if (!throwOnError) {
11781
- const code = error?.code;
12277
+ const code2 = error?.code;
11782
12278
  return plainResult({
11783
12279
  success: false,
11784
12280
  error: plainResult({
11785
12281
  name: "Error",
11786
12282
  message,
11787
- ...typeof code === "string" ? { code } : {},
12283
+ ...typeof code2 === "string" ? { code: code2 } : {},
11788
12284
  toolName
11789
12285
  })
11790
12286
  });
11791
12287
  }
11792
- throw createSafeError(message);
12288
+ const code = error?.code;
12289
+ throw createSafeError(message, "Error", typeof code === "string" ? code : void 0);
11793
12290
  }
11794
12291
  }
11795
12292
  function* __safe_forOf(iterable) {
@@ -12222,6 +12719,7 @@ var init_safe_runtime = __esm({
12222
12719
  "libs/core/src/safe-runtime.ts"() {
12223
12720
  "use strict";
12224
12721
  init_value_sanitizer();
12722
+ init_bounded_json();
12225
12723
  init_safe_error();
12226
12724
  init_reference_resolver();
12227
12725
  init_reference_config();
@@ -12318,7 +12816,7 @@ function createRealmAirlock(realm) {
12318
12816
  return counterpart;
12319
12817
  }
12320
12818
  }
12321
- const kind = callable ? "function" : ArrayIsArray4(hostProxy) ? "array" : "object";
12819
+ const kind = callable ? "function" : ArrayIsArray5(hostProxy) ? "array" : "object";
12322
12820
  const readValue = (key) => {
12323
12821
  const value2 = ReflectGet6(hostProxy, key, hostProxy);
12324
12822
  if (typeof value2 === "function") {
@@ -12373,7 +12871,7 @@ function createRealmAirlock(realm) {
12373
12871
  for (let i = 0; i < args.length; i++) {
12374
12872
  passed[i] = args[i];
12375
12873
  }
12376
- return toRealm(ReflectApply7(hostProxy, toHost(thisArg), passed));
12874
+ return toRealm(ReflectApply8(hostProxy, toHost(thisArg), passed));
12377
12875
  },
12378
12876
  construct() {
12379
12877
  throw createSafeError("Host functions cannot be called with new", "TypeError");
@@ -12389,7 +12887,7 @@ function createRealmAirlock(realm) {
12389
12887
  }
12390
12888
  return { toRealm, toHost, isRealmValue, isAirlockProxy };
12391
12889
  }
12392
- var HostFunctionCall, HostFunctionApply, HostFunctionBind, ReflectGet6, ReflectHas2, ReflectOwnKeys4, ReflectGetOwnPropertyDescriptor3, ReflectApply7, ArrayIsArray4, ObjectGetPrototypeOf6;
12890
+ var HostFunctionCall, HostFunctionApply, HostFunctionBind, ReflectGet6, ReflectHas2, ReflectOwnKeys4, ReflectGetOwnPropertyDescriptor3, ReflectApply8, ArrayIsArray5, ObjectGetPrototypeOf6;
12393
12891
  var init_realm_airlock = __esm({
12394
12892
  "libs/core/src/realm-airlock.ts"() {
12395
12893
  "use strict";
@@ -12403,8 +12901,8 @@ var init_realm_airlock = __esm({
12403
12901
  ReflectHas2 = Reflect.has;
12404
12902
  ReflectOwnKeys4 = Reflect.ownKeys;
12405
12903
  ReflectGetOwnPropertyDescriptor3 = Reflect.getOwnPropertyDescriptor;
12406
- ReflectApply7 = Reflect.apply;
12407
- ArrayIsArray4 = Array.isArray;
12904
+ ReflectApply8 = Reflect.apply;
12905
+ ArrayIsArray5 = Array.isArray;
12408
12906
  ObjectGetPrototypeOf6 = Object.getPrototypeOf;
12409
12907
  }
12410
12908
  });
@@ -12594,6 +13092,7 @@ var init_vm_adapter = __esm({
12594
13092
  "use strict";
12595
13093
  vm5 = __toESM(require("vm"));
12596
13094
  init_sandbox_script();
13095
+ init_realm_regex_backstop();
12597
13096
  init_safe_runtime();
12598
13097
  init_secure_proxy();
12599
13098
  init_safe_error();
@@ -13410,6 +13909,10 @@ var init_vm_adapter = __esm({
13410
13909
  var promiseThen = Promise.prototype.then;
13411
13910
  var settled = Promise.resolve();
13412
13911
  var reflectApply = Reflect.apply;
13912
+ var isArray = Array.isArray;
13913
+ var StringOf = String;
13914
+ var stringValueOf = String.prototype.valueOf;
13915
+ var numberValueOf = Number.prototype.valueOf;
13413
13916
  var maxBytes = ${numericLiteral("toolBridge.maxPayloadBytes", maxPayloadBytes)};
13414
13917
  var limitMessage = ${JSON.stringify(limitMessage)};
13415
13918
 
@@ -13478,6 +13981,56 @@ var init_vm_adapter = __esm({
13478
13981
  return err;
13479
13982
  }
13480
13983
 
13984
+ // Whether a value has the internal slot that a built-in's valueOf reads.
13985
+ function hasSlot(valueOf, value) {
13986
+ try {
13987
+ reflectApply(valueOf, value, []);
13988
+ return true;
13989
+ } catch (e) {
13990
+ return false;
13991
+ }
13992
+ }
13993
+
13994
+ // The JSON text of a value, given up as soon as it would be longer than limit bytes.
13995
+ // A value referenced many times is written as many times, so the text can be far longer
13996
+ // than the value is large. What each member adds is counted as JSON.stringify writes it,
13997
+ // and the count is a lower bound of its UTF-8 bytes (a code unit is at least one byte,
13998
+ // an escape only adds), so a value whose text is within the limit is never given up.
13999
+ // The members JSON.stringify visits are counted as well, also those it leaves out (a
14000
+ // function, undefined): at most as many as the limit has bytes.
14001
+ var TOO_LARGE = {};
14002
+ function stringifyWithin(value, limit) {
14003
+ var bytes = 0;
14004
+ var visits = 0;
14005
+ var root = true;
14006
+ return stringify(value, function (key, member) {
14007
+ if (++visits > limit) throw TOO_LARGE;
14008
+ // A String or Number object is written as what it converts to; converted here, the
14009
+ // way JSON.stringify converts it and once, so the count is of what is written.
14010
+ if (member !== null && typeof member === 'object') {
14011
+ if (hasSlot(stringValueOf, member)) member = StringOf(member);
14012
+ else if (hasSlot(numberValueOf, member)) member = +member;
14013
+ }
14014
+ var added;
14015
+ var kind = typeof member;
14016
+ if (kind === 'string') added = member.length + 2;
14017
+ else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
14018
+ else if (kind === 'boolean') added = member ? 4 : 5;
14019
+ else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
14020
+ else added = 0;
14021
+ if (!root) {
14022
+ // An element of an array is written, as null if nothing else; a member of an
14023
+ // object that is written has its key in front of it.
14024
+ if (isArray(this)) added = added || 4;
14025
+ else if (added > 0) added += key.length + 3;
14026
+ }
14027
+ root = false;
14028
+ bytes += added;
14029
+ if (bytes > limit) throw TOO_LARGE;
14030
+ return member;
14031
+ });
14032
+ }
14033
+
13481
14034
  return async function __safe_callTool(toolName, args, options) {
13482
14035
  // callTool options: only { throwOnError: false } changes behavior. Tool failures
13483
14036
  // then resolve to { success: false, error }; the enclave's own refusals still throw.
@@ -13498,11 +14051,23 @@ var init_vm_adapter = __esm({
13498
14051
  throw makeError('Tool bridge is not available', 'Error');
13499
14052
  }
13500
14053
 
13501
- // Defense-in-depth: ensure JSON-serializable input.
14054
+ // Counted here, where the call is made and before anything is done with its
14055
+ // arguments: the first maxToolCalls calls are the ones that run, also when several
14056
+ // are made before any of them is started, and a call over the limit costs nothing.
14057
+ if (countCall() !== true) {
14058
+ throw makeError(limitMessage, 'ToolLimitError');
14059
+ }
14060
+
14061
+ // Defense-in-depth: ensure JSON-serializable input. The text is written within the
14062
+ // payload limit (see stringifyWithin), so what is done before the request is
14063
+ // measured is in proportion to the limit.
13502
14064
  var sanitizedArgs;
13503
14065
  try {
13504
- sanitizedArgs = parse(stringify(args));
14066
+ sanitizedArgs = parse(stringifyWithin(args, maxBytes));
13505
14067
  } catch (e) {
14068
+ if (e === TOO_LARGE) {
14069
+ throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
14070
+ }
13506
14071
  throw makeError('Tool arguments must be JSON-serializable', 'TypeError');
13507
14072
  }
13508
14073
 
@@ -13517,11 +14082,6 @@ var init_vm_adapter = __esm({
13517
14082
  throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
13518
14083
  }
13519
14084
 
13520
- // Counted here, where the call is made: the first maxToolCalls calls are the ones
13521
- // that run, also when several are made before any of them is started.
13522
- if (countCall() !== true) {
13523
- throw makeError(limitMessage, 'ToolLimitError');
13524
- }
13525
14085
  var responseJson = await callBridge(requestJson);
13526
14086
  if (typeof responseJson !== 'string') {
13527
14087
  throw makeError('Tool bridge returned invalid response', 'Error');
@@ -13675,6 +14235,12 @@ var init_vm_adapter = __esm({
13675
14235
  enumerable: false
13676
14236
  });
13677
14237
  }
14238
+ const realmAllowlist = executionContext.realmGlobalAllowlist;
14239
+ if (realmAllowlist && !realmAllowlist.includes("RegExp")) {
14240
+ compileSandboxScript(REALM_REGEX_BACKSTOP_SOURCE, { filename: "realm-regex-backstop.js" }).runInContext(
14241
+ baseSandbox
14242
+ );
14243
+ }
13678
14244
  try {
13679
14245
  INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT.runInContext(baseSandbox);
13680
14246
  } catch {
@@ -13734,8 +14300,8 @@ var init_vm_adapter = __esm({
13734
14300
  }
13735
14301
  const depthDefaulted = config.maxSanitizeDepth ?? 20;
13736
14302
  const propsDefaulted = config.maxSanitizeProperties ?? 100;
13737
- const clampedDepth = Math.max(5, Math.min(50, depthDefaulted));
13738
- const clampedProperties = Math.max(50, Math.min(1e3, propsDefaulted));
14303
+ const clampedDepth = Math.min(50, depthDefaulted);
14304
+ const clampedProperties = Math.min(1e3, propsDefaulted);
13739
14305
  const sanitizedValue = sanitizeValue(value, {
13740
14306
  maxDepth: clampedDepth,
13741
14307
  maxProperties: clampedProperties,
@@ -14965,7 +15531,7 @@ init_reference_resolver();
14965
15531
  // libs/core/src/scoring/feature-extractor.ts
14966
15532
  var acorn = __toESM(require("acorn"));
14967
15533
  var walk = __toESM(require("acorn-walk"));
14968
- var import_crypto2 = require("crypto");
15534
+ var import_crypto = require("crypto");
14969
15535
 
14970
15536
  // libs/core/src/scoring/types.ts
14971
15537
  var import_ast3 = require("@enclave-vm/ast");
@@ -15444,7 +16010,7 @@ var FeatureExtractor = class {
15444
16010
  * decision, so two texts may share a decision only if they are the same text.
15445
16011
  */
15446
16012
  hashCode(code) {
15447
- return (0, import_crypto2.createHash)("sha256").update(code).digest("hex");
16013
+ return (0, import_crypto.createHash)("sha256").update(code).digest("hex");
15448
16014
  }
15449
16015
  /**
15450
16016
  * Check if a tool sequence indicates potential exfiltration
@@ -16626,6 +17192,7 @@ var ScoringGate = class {
16626
17192
  scorer = null;
16627
17193
  cache = null;
16628
17194
  initialized = false;
17195
+ initializing = null;
16629
17196
  constructor(config) {
16630
17197
  this.config = normalizeScoringConfig(config);
16631
17198
  this.extractor = new FeatureExtractor({ toolNamespaces: this.config.toolNamespaces });
@@ -16643,9 +17210,23 @@ var ScoringGate = class {
16643
17210
  if (this.initialized) {
16644
17211
  return;
16645
17212
  }
16646
- this.scorer = this.createScorer();
16647
- await this.scorer.initialize?.();
16648
- this.initialized = true;
17213
+ if (!this.initializing) {
17214
+ const setup = this.setUpScorer().finally(() => {
17215
+ if (this.initializing === setup) this.initializing = null;
17216
+ });
17217
+ this.initializing = setup;
17218
+ }
17219
+ return this.initializing;
17220
+ }
17221
+ async setUpScorer() {
17222
+ const scorer = this.createScorer();
17223
+ this.scorer = scorer;
17224
+ await scorer.initialize?.();
17225
+ if (this.scorer === scorer) {
17226
+ this.initialized = true;
17227
+ } else if (this.scorer === null) {
17228
+ scorer.dispose?.();
17229
+ }
16649
17230
  }
16650
17231
  /**
16651
17232
  * Create the appropriate scorer based on configuration
@@ -16800,6 +17381,7 @@ var ScoringGate = class {
16800
17381
  this.scorer = null;
16801
17382
  this.cache = null;
16802
17383
  this.initialized = false;
17384
+ this.initializing = null;
16803
17385
  }
16804
17386
  /**
16805
17387
  * Check if the gate is ready to evaluate
@@ -17267,8 +17849,11 @@ var Enclave = class {
17267
17849
  * @param toolHandler Optional tool handler (overrides constructor config)
17268
17850
  * @returns Execution result
17269
17851
  */
17270
- async run(code, toolHandler) {
17271
- const result = await this.execute(code, toolHandler);
17852
+ async run(code, toolHandler, options = {}) {
17853
+ if (options.maxToolResultBytes !== void 0 && (typeof options.maxToolResultBytes !== "number" || !Number.isFinite(options.maxToolResultBytes) || options.maxToolResultBytes <= 0)) {
17854
+ throw new TypeError("maxToolResultBytes must be a positive finite number");
17855
+ }
17856
+ const result = await this.execute(code, toolHandler, options);
17272
17857
  return this.applyStackTracePolicy(result);
17273
17858
  }
17274
17859
  /**
@@ -17289,7 +17874,7 @@ var Enclave = class {
17289
17874
  /**
17290
17875
  * Transform, validate and execute. `run` applies the stack-trace policy to what this returns.
17291
17876
  */
17292
- async execute(code, toolHandler) {
17877
+ async execute(code, toolHandler, options = {}) {
17293
17878
  const startTime = Date.now();
17294
17879
  const stats = {
17295
17880
  duration: 0,
@@ -17378,6 +17963,7 @@ ${errorMessages}`,
17378
17963
  };
17379
17964
  }
17380
17965
  }
17966
+ const codeForScoring = transformedCode;
17381
17967
  if (sidecar && this.referenceConfig) {
17382
17968
  transformedCode = this.applySidecarTransforms(transformedCode, sidecar);
17383
17969
  } else if (this.config.memoryLimit && this.config.memoryLimit > 0) {
@@ -17410,7 +17996,7 @@ ${errorMessages}`,
17410
17996
  }
17411
17997
  let scoringResult;
17412
17998
  if (this.scoringGate) {
17413
- scoringResult = await this.scoringGate.evaluate(transformedCode);
17999
+ scoringResult = await this.scoringGate.evaluate(codeForScoring);
17414
18000
  if (!scoringResult.allowed) {
17415
18001
  const hasScore = typeof scoringResult.totalScore === "number";
17416
18002
  const signalSummary = scoringResult.signals && scoringResult.signals.length > 0 ? scoringResult.signals.map((s) => `${s.id}: ${s.description}`).join("; ") : scoringResult.reason ?? "Unknown risk";
@@ -17454,6 +18040,13 @@ ${errorMessages}`,
17454
18040
  abortRequested = value;
17455
18041
  },
17456
18042
  toolHandler: hostToolHandler ? trackToolCalls(hostToolHandler, hostActivity) : void 0,
18043
+ maxToolResultBytes: options.maxToolResultBytes,
18044
+ onToolBridgeFailure: options.onToolBridgeFailure ? () => {
18045
+ try {
18046
+ options.onToolBridgeFailure?.();
18047
+ } catch {
18048
+ }
18049
+ } : void 0,
17457
18050
  hostActivity,
17458
18051
  consoleHandler: hostConsoleHandler ? (level, message) => returned ? void 0 : asyncContexts.inHostContext(() => hostConsoleHandler(level, message)) : void 0,
17459
18052
  sidecar,
@@ -18171,6 +18764,11 @@ var ReturnSignal = class {
18171
18764
  this.value = value;
18172
18765
  }
18173
18766
  };
18767
+ var ScriptThrown = class {
18768
+ constructor(value) {
18769
+ this.value = value;
18770
+ }
18771
+ };
18174
18772
  var BreakSignal = class {
18175
18773
  };
18176
18774
  var ContinueSignal = class {
@@ -18334,33 +18932,44 @@ var Interpreter = class {
18334
18932
  * For a host helper that is handed a callback (`parallel(items, fn)`): `fn` may be a function
18335
18933
  * of the script, or a built-in or host function the script passed along.
18336
18934
  */
18337
- call(fn, args) {
18338
- if (this.fatal !== void 0) throw this.fatal;
18339
- if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
18340
- if (this.interpretedFunctions.has(fn)) return fn(...args);
18341
- return this.callFunction(fn, void 0, args, this.callerDepth);
18935
+ async call(fn, args) {
18936
+ try {
18937
+ if (this.fatal !== void 0) throw this.fatal;
18938
+ if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
18939
+ if (this.interpretedFunctions.has(fn)) return await fn(...args);
18940
+ return await this.callFunction(fn, void 0, args, this.callerDepth);
18941
+ } catch (thrown) {
18942
+ if (thrown instanceof ScriptThrown) throw thrown.value;
18943
+ if (!(thrown instanceof Error)) throw new InterpreterError("Host operation failed");
18944
+ throw thrown;
18945
+ }
18342
18946
  }
18343
18947
  /** Number of AST nodes evaluated so far (for execution stats). */
18344
18948
  get stepCount() {
18345
18949
  return this.steps;
18346
18950
  }
18347
18951
  async run(program) {
18348
- const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
18349
- for (const stmt of program.body) {
18350
- if (stmt.type === "FunctionDeclaration" && stmt.id) {
18351
- root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
18952
+ try {
18953
+ const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
18954
+ for (const stmt of program.body) {
18955
+ if (stmt.type === "FunctionDeclaration" && stmt.id) {
18956
+ root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
18957
+ }
18352
18958
  }
18959
+ let last;
18960
+ for (const stmt of program.body) {
18961
+ if (stmt.type === "FunctionDeclaration") continue;
18962
+ last = await this.execStatement(stmt, root);
18963
+ }
18964
+ if (root.has("__ag_main")) {
18965
+ const main = root.get("__ag_main");
18966
+ if (typeof main === "function") return await main();
18967
+ }
18968
+ return last;
18969
+ } catch (thrown) {
18970
+ if (thrown instanceof ScriptThrown) throw thrown.value;
18971
+ throw thrown;
18353
18972
  }
18354
- let last;
18355
- for (const stmt of program.body) {
18356
- if (stmt.type === "FunctionDeclaration") continue;
18357
- last = await this.execStatement(stmt, root);
18358
- }
18359
- if (root.has("__ag_main")) {
18360
- const main = root.get("__ag_main");
18361
- if (typeof main === "function") return main();
18362
- }
18363
- return last;
18364
18973
  }
18365
18974
  /**
18366
18975
  * End the run from outside: whatever of the script is still going (a callback waiting for a
@@ -18534,7 +19143,7 @@ var Interpreter = class {
18534
19143
  case "TryStatement":
18535
19144
  return this.execTry(node, scope);
18536
19145
  case "ThrowStatement":
18537
- throw await this.evalExpr(node.argument, scope);
19146
+ throw new ScriptThrown(await this.evalExpr(node.argument, scope));
18538
19147
  case "ReturnStatement":
18539
19148
  throw new ReturnSignal(node.argument ? await this.evalReturned(node.argument, scope) : void 0);
18540
19149
  case "BreakStatement":
@@ -18656,12 +19265,12 @@ var Interpreter = class {
18656
19265
  }
18657
19266
  }
18658
19267
  /**
18659
- * What a `catch` clause receives. A value the script threw is its own. A host Error (a refusal
18660
- * by the interpreter, a failed tool call, a TypeError of a built-in) is replaced by a plain
18661
- * copy with its name, message and code.
19268
+ * What a `catch` clause receives. A value the script threw is its own. A host Error is copied
19269
+ * with its name, message and code; every other host rejection reason becomes a generic error.
18662
19270
  */
18663
19271
  toScriptValue(thrown) {
18664
- if (!(thrown instanceof Error)) return thrown;
19272
+ if (thrown instanceof ScriptThrown) return thrown.value;
19273
+ if (!(thrown instanceof Error)) return createScriptError("Error", "Host operation failed");
18665
19274
  const known = this.errorCopies.get(thrown);
18666
19275
  if (known) return known;
18667
19276
  const code = thrown.code;
@@ -20052,23 +20661,23 @@ function expandReplacement(template, text, at, matched) {
20052
20661
  function convertedOnce(value, convert) {
20053
20662
  return typeof value === "object" && value !== null ? convert(value) : value;
20054
20663
  }
20055
- function checkArrayWrite(array, key, value) {
20664
+ function checkArrayWrite(array, key, value, currentLength = array.length) {
20056
20665
  if (key === "length") value = convertedOnce(value, Number);
20057
- const length = arrayLengthAfterWrite(array, key, value);
20666
+ const length = arrayLengthAfterWrite(currentLength, key, value);
20058
20667
  if (length > MAX_ARRAY_LENGTH2) {
20059
20668
  throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH2} items`);
20060
20669
  }
20061
20670
  return { value, length };
20062
20671
  }
20063
- function arrayLengthAfterWrite(array, key, value) {
20672
+ function arrayLengthAfterWrite(currentLength, key, value) {
20064
20673
  if (key === "length") {
20065
20674
  const length = Number(value);
20066
20675
  if (!Number.isInteger(length) || length < 0) throw new InterpreterError("Invalid array length");
20067
20676
  return length;
20068
20677
  }
20069
20678
  const index = Number(key);
20070
- if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(array.length, index + 1);
20071
- return array.length;
20679
+ if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(currentLength, index + 1);
20680
+ return currentLength;
20072
20681
  }
20073
20682
 
20074
20683
  // libs/core/src/interpreter/safe-globals.ts
@@ -20090,7 +20699,7 @@ function indentationSize(value, indent, limit, depth, path2) {
20090
20699
  path2.delete(value);
20091
20700
  return size;
20092
20701
  }
20093
- function utf8Length(text) {
20702
+ function utf8Length2(text) {
20094
20703
  let bytes = 0;
20095
20704
  for (let index = 0; index < text.length; index++) {
20096
20705
  const code = text.charCodeAt(index);
@@ -20108,7 +20717,7 @@ function utf8Length(text) {
20108
20717
  }
20109
20718
  function indentOf(space) {
20110
20719
  if (typeof space === "number") return Math.max(0, Math.min(MAX_JSON_INDENT, Math.floor(space) || 0));
20111
- if (typeof space === "string") return utf8Length(space.slice(0, MAX_JSON_INDENT));
20720
+ if (typeof space === "string") return utf8Length2(space.slice(0, MAX_JSON_INDENT));
20112
20721
  return 0;
20113
20722
  }
20114
20723
  function parsedJsonCost(text) {
@@ -20204,13 +20813,26 @@ var SafeObject = frozenRecord({
20204
20813
  if (!isScriptData(target) || Object.isFrozen(target)) {
20205
20814
  throw new TypeError("Object.assign needs an object or array the script created as its target");
20206
20815
  }
20816
+ const targetIsArray = Array.isArray(target);
20817
+ const lengths = [];
20818
+ let length = targetIsArray ? target.length : 0;
20207
20819
  for (const source of sources) {
20208
20820
  if (source === null || source === void 0) continue;
20209
20821
  for (const key of dataKeys(source)) {
20210
- let value = source[key];
20822
+ const value = source[key];
20211
20823
  assertStorable(target, key, value);
20212
- if (Array.isArray(target)) value = checkArrayWrite(target, key, value).value;
20213
- target[key] = value;
20824
+ if (targetIsArray) {
20825
+ const checked = checkArrayWrite(target, key, value, length);
20826
+ length = checked.length;
20827
+ if (key === "length") lengths.push(checked.value);
20828
+ }
20829
+ }
20830
+ }
20831
+ let nextLength = 0;
20832
+ for (const source of sources) {
20833
+ if (source === null || source === void 0) continue;
20834
+ for (const key of dataKeys(source)) {
20835
+ target[key] = targetIsArray && key === "length" ? lengths[nextLength++] : source[key];
20214
20836
  }
20215
20837
  }
20216
20838
  return target;
@@ -20425,7 +21047,9 @@ init_memory_tracker();
20425
21047
  init_reference_config();
20426
21048
  init_reference_resolver();
20427
21049
  init_stack_trace();
21050
+ init_thrown_value();
20428
21051
  init_tool_bridge();
21052
+ init_bounded_json();
20429
21053
  init_value_sanitizer();
20430
21054
  var DEFAULT_MAX_STEPS = 5e6;
20431
21055
  var DEFAULT_MAX_CALL_DEPTH = 256;
@@ -20607,7 +21231,7 @@ var InterpreterAdapter = class {
20607
21231
  */
20608
21232
  runtimeGlobals(context, charge, callbacks) {
20609
21233
  const { config } = context;
20610
- const callTool = observed(this.createCallTool(context, callbacks));
21234
+ const callTool = observed(this.createCallTool(context, callbacks, charge));
20611
21235
  const resolver = context.sidecar && context.referenceConfig ? new ReferenceResolver(context.sidecar, context.referenceConfig) : void 0;
20612
21236
  const joinReferences = (parts) => {
20613
21237
  if (!resolver) {
@@ -20689,9 +21313,21 @@ var InterpreterAdapter = class {
20689
21313
  const settled = await Promise.allSettled(tasks.map(async (task) => task()));
20690
21314
  const failures = settled.filter((result) => result.status === "rejected");
20691
21315
  if (failures.length > 0) {
20692
- const messages = failures.map((failure2) => this.describe(failure2.reason).message).join("\n");
20693
- throw sandboxError(`${failures.length} of ${tasks.length} parallel operations failed:
20694
- ${messages}`);
21316
+ let messages = "";
21317
+ let listed = 0;
21318
+ for (const failure2 of failures) {
21319
+ const room = MAX_THROWN_MESSAGE_LENGTH - messages.length - (listed === 0 ? 0 : 1);
21320
+ if (room <= 0) break;
21321
+ const message = this.describe(failure2.reason).message;
21322
+ messages += (listed === 0 ? "" : "\n") + (message.length > room ? message.slice(0, room) : message);
21323
+ listed++;
21324
+ }
21325
+ const unlisted = failures.length - listed;
21326
+ throw sandboxError(
21327
+ `${failures.length} of ${tasks.length} parallel operations failed:
21328
+ ${messages}` + (unlisted > 0 ? `
21329
+ (${unlisted} more not shown)` : "")
21330
+ );
20695
21331
  }
20696
21332
  return settled.map((result) => result.value);
20697
21333
  });
@@ -20748,9 +21384,81 @@ ${messages}`);
20748
21384
  }
20749
21385
  const custom = config.globals;
20750
21386
  if (custom && typeof custom === "object") {
21387
+ const maxGlobalCalls = config.maxGlobalFunctionCalls ?? Math.max(10, config.maxToolCalls * 10);
21388
+ const payloadLimit = config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_TOOL_PAYLOAD_BYTES;
21389
+ let globalCalls = 0;
21390
+ const serialize = (value) => {
21391
+ const sanitized = sanitizeValue(value, {
21392
+ maxDepth: config.maxSanitizeDepth,
21393
+ maxProperties: config.maxSanitizeProperties,
21394
+ allowDates: false,
21395
+ allowErrors: true
21396
+ });
21397
+ const json = stringifyWithin(sanitized, payloadLimit);
21398
+ if (json === void 0) return void 0;
21399
+ if (utf8Length(json) > payloadLimit) throw sandboxError("Global function value exceeds bridge limit");
21400
+ return json;
21401
+ };
21402
+ const copy = (value) => {
21403
+ const json = serialize(value);
21404
+ return json === void 0 ? void 0 : JSON.parse(json);
21405
+ };
21406
+ const safeHostCall = (name, fn) => (...args) => {
21407
+ if (callbacks.over || context.aborted) throw executionOver();
21408
+ if (++globalCalls > maxGlobalCalls)
21409
+ throw sandboxError(`Global function call limit exceeded (${maxGlobalCalls})`);
21410
+ if (context.beforeGlobalCall && context.beforeGlobalCall() !== true) {
21411
+ throw sandboxError("Global function policy refused the call");
21412
+ }
21413
+ let safeArgs;
21414
+ try {
21415
+ safeArgs = copy(args);
21416
+ } catch {
21417
+ throw sandboxError(`Global function ${name} received unsupported arguments`, "TypeError");
21418
+ }
21419
+ let outcome;
21420
+ try {
21421
+ outcome = fn(...safeArgs);
21422
+ } catch {
21423
+ throw sandboxError("Global function failed");
21424
+ }
21425
+ const settle = (value) => {
21426
+ if (callbacks.over || context.aborted) throw executionOver();
21427
+ let json;
21428
+ try {
21429
+ json = serialize(value);
21430
+ } catch {
21431
+ throw sandboxError(`Global function ${name} returned an unsupported value`);
21432
+ }
21433
+ if (json === void 0) return void 0;
21434
+ if (value !== null && typeof value === "object") charge(Math.max(json.length * 2, utf8Length(json)));
21435
+ return JSON.parse(json);
21436
+ };
21437
+ if (outcome !== null && (typeof outcome === "object" || typeof outcome === "function")) {
21438
+ let then;
21439
+ try {
21440
+ then = outcome.then;
21441
+ } catch {
21442
+ throw sandboxError(`Global function ${name} returned an unsupported value`);
21443
+ }
21444
+ if (typeof then === "function") {
21445
+ return observed(async () => {
21446
+ let value;
21447
+ try {
21448
+ value = await Promise.resolve(outcome);
21449
+ } catch {
21450
+ throw sandboxError("Global function failed");
21451
+ }
21452
+ return settle(value);
21453
+ })();
21454
+ }
21455
+ }
21456
+ return settle(outcome);
21457
+ };
20751
21458
  for (const name of Object.keys(custom)) {
20752
21459
  if (name.startsWith("__") || Object.prototype.hasOwnProperty.call(globals, name)) continue;
20753
- globals[name] = frozenDataCopy(name, custom[name]);
21460
+ const value = custom[name];
21461
+ globals[name] = typeof value === "function" ? safeHostCall(name, value) : frozenDataCopy(name, value);
20754
21462
  }
20755
21463
  }
20756
21464
  return globals;
@@ -20760,7 +21468,7 @@ ${messages}`);
20760
21468
  * and the response cross as JSON, so the handler never receives a value of the script and the
20761
21469
  * script never receives an object of the handler.
20762
21470
  */
20763
- createCallTool(context, execution) {
21471
+ createCallTool(context, execution, charge) {
20764
21472
  const configured = context.config.toolHandler;
20765
21473
  const bridgeContext = context.toolHandler === void 0 && typeof configured === "function" ? Object.create(context, { toolHandler: { value: configured } }) : context;
20766
21474
  const bridge = createHostToolBridge(bridgeContext, { updateStats: true });
@@ -20791,9 +21499,20 @@ ${messages}`);
20791
21499
  } catch {
20792
21500
  throw sandboxError("Tool arguments must be JSON-serializable", "TypeError");
20793
21501
  }
21502
+ if (utf8Length(requestJson) > maxPayloadBytes) {
21503
+ throw sandboxError(`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`, "ToolBridgeError");
21504
+ }
21505
+ if (context.beforeToolCall) {
21506
+ const request = JSON.parse(requestJson);
21507
+ if (context.beforeToolCall(toolName, request.args) !== true) {
21508
+ throw sandboxError("Tool policy refused the call");
21509
+ }
21510
+ }
20794
21511
  let response;
21512
+ let responseJson;
20795
21513
  try {
20796
- response = JSON.parse(await bridge(requestJson));
21514
+ responseJson = await bridge(requestJson);
21515
+ response = JSON.parse(responseJson);
20797
21516
  } catch {
20798
21517
  throw sandboxError("Tool bridge returned invalid JSON");
20799
21518
  }
@@ -20802,6 +21521,15 @@ ${messages}`);
20802
21521
  }
20803
21522
  const reply = response;
20804
21523
  if (reply.ok === true) {
21524
+ try {
21525
+ charge(Math.max(responseJson.length * 2, utf8Length(responseJson)));
21526
+ } catch (error) {
21527
+ try {
21528
+ context.onToolBridgeFailure?.();
21529
+ } catch {
21530
+ }
21531
+ throw error;
21532
+ }
20805
21533
  return throwOnError ? reply.value : { success: true, data: reply.value };
20806
21534
  }
20807
21535
  if (reply.ok === false && reply.error && typeof reply.error === "object") {