@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/esm/index.mjs CHANGED
@@ -309,9 +309,12 @@ function sanitizeObjectValue(value, options, depth, context) {
309
309
  const sanitizedMap = ObjectCreate(null);
310
310
  const entries = ReflectApply(MapProtoEntries, inspected, []);
311
311
  for (const [key, val] of entries) {
312
+ context.propCount.count++;
313
+ if (context.propCount.count > maxProperties) {
314
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
315
+ }
312
316
  if (typeof key !== "string") continue;
313
317
  if (DANGEROUS_KEYS.has(key)) continue;
314
- context.propCount.count++;
315
318
  sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
316
319
  }
317
320
  return sanitizedMap;
@@ -321,6 +324,9 @@ function sanitizeObjectValue(value, options, depth, context) {
321
324
  const result = [];
322
325
  for (const item of iter) {
323
326
  context.propCount.count++;
327
+ if (context.propCount.count > maxProperties) {
328
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
329
+ }
324
330
  result.push(sanitizeValue(item, options, depth + 1, context));
325
331
  }
326
332
  return result;
@@ -408,7 +414,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
408
414
  }
409
415
  if (ArrayIsArray(value)) {
410
416
  if (currentPath.has(value)) {
411
- return 4;
417
+ return CIRCULAR_MARKER_BYTES;
412
418
  }
413
419
  currentPath.add(value);
414
420
  try {
@@ -434,7 +440,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
434
440
  if (type === "object") {
435
441
  const object = value;
436
442
  if (currentPath.has(object)) {
437
- return 4;
443
+ return CIRCULAR_MARKER_BYTES;
438
444
  }
439
445
  if (!isPlainObject(object)) {
440
446
  if (hasBrand(DateProtoGetTime, object)) {
@@ -525,11 +531,12 @@ function checkSerializedSize(value, maxBytes) {
525
531
  return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
526
532
  }
527
533
  }
528
- var DANGEROUS_KEYS, ReflectApply, ReflectGet, ArrayIsArray, ObjectKeys, ObjectCreate, ObjectGetPrototypeOf, NumberIsFinite, MathFloor, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoSourceGetter, RegExpFlagGetters, MapProtoSizeGetter, SetProtoSizeGetter;
534
+ var DANGEROUS_KEYS, CIRCULAR_MARKER_BYTES, ReflectApply, ReflectGet, ArrayIsArray, ObjectKeys, ObjectCreate, ObjectGetPrototypeOf, NumberIsFinite, MathFloor, MapProtoEntries, SetProtoValues, DateProtoGetTime, DateProtoToISOString, RegExpProtoSourceGetter, RegExpFlagGetters, MapProtoSizeGetter, SetProtoSizeGetter;
529
535
  var init_value_sanitizer = __esm({
530
536
  "libs/core/src/value-sanitizer.ts"() {
531
537
  "use strict";
532
538
  DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
539
+ CIRCULAR_MARKER_BYTES = 12;
533
540
  ReflectApply = Reflect.apply;
534
541
  ReflectGet = Reflect.get;
535
542
  ArrayIsArray = Array.isArray;
@@ -1015,6 +1022,11 @@ var init_global_function_gate = __esm({
1015
1022
  });
1016
1023
 
1017
1024
  // libs/core/src/secure-proxy.ts
1025
+ function isArrayIndexKey(property) {
1026
+ if (typeof property !== "string") return false;
1027
+ const index = Number(property);
1028
+ return index >>> 0 === index && index !== 4294967295 && String(index) === property;
1029
+ }
1018
1030
  function getBlockedPropertiesForLevel(level) {
1019
1031
  const blocked = /* @__PURE__ */ new Set();
1020
1032
  if (level !== "PERMISSIVE") {
@@ -1178,6 +1190,7 @@ function isOfBuiltinKind(receiver, homes) {
1178
1190
  return false;
1179
1191
  }
1180
1192
  function passesHostValuesToCallbacks(fn, builtinMethod) {
1193
+ if (COMPARING_BUILTINS.has(fn)) return false;
1181
1194
  return builtinMethod || fn === JsonParse || fn === JsonStringify2 || typeof fn === "function" && boundBuiltinMethods.has(fn);
1182
1195
  }
1183
1196
  function isProxyable(value) {
@@ -1261,10 +1274,11 @@ function createSecureProxy(target, options = {}) {
1261
1274
  };
1262
1275
  const guardObjectArgument = (value) => {
1263
1276
  if (value === null || typeof value !== "object") return value;
1264
- if (proxySet.has(value) || guardedArguments.has(value) || Array.isArray(value)) return value;
1277
+ if (proxySet.has(value) || guardedArguments.has(value)) return value;
1265
1278
  if (heldBySandbox && heldBySandbox(value)) return value;
1266
1279
  const existing = lookupGuard(value);
1267
1280
  if (existing) return existing;
1281
+ if (Array.isArray(value)) return guardArrayArgument(value);
1268
1282
  const original = value;
1269
1283
  const guard = new Proxy(/* @__PURE__ */ Object.create(null), {
1270
1284
  get: (_shell, property) => guardMember(ReflectGet2(original, property, original), original),
@@ -1289,6 +1303,24 @@ function createSecureProxy(target, options = {}) {
1289
1303
  guardedArguments.set(guard, original);
1290
1304
  return guard;
1291
1305
  };
1306
+ const guardArrayArgument = (original) => {
1307
+ const guard = new Proxy(original, {
1308
+ get: (target2, property) => {
1309
+ const member = ReflectGet2(target2, property, target2);
1310
+ return property === "length" || isArrayIndexKey(property) ? member : guardMember(member, target2);
1311
+ },
1312
+ // What a host function stores in the array is a host value like any other
1313
+ set: (target2, property, stored) => ReflectSet(target2, property, toSandbox(stored), target2),
1314
+ defineProperty: (target2, property, descriptor) => {
1315
+ if ("get" in descriptor || "set" in descriptor) return false;
1316
+ const stored = "value" in descriptor ? { ...descriptor, value: toSandbox(descriptor.value) } : descriptor;
1317
+ return ReflectDefineProperty(target2, property, stored);
1318
+ }
1319
+ });
1320
+ storeGuard(original, guard);
1321
+ guardedArguments.set(guard, original);
1322
+ return guard;
1323
+ };
1292
1324
  const guardMember = (member, holder) => {
1293
1325
  if (typeof member !== "function") return guardObjectArgument(member);
1294
1326
  const method = function guardedMethod(...hostArgs) {
@@ -1609,7 +1641,7 @@ function unwrapSecureProxy(value) {
1609
1641
  }
1610
1642
  return current;
1611
1643
  }
1612
- 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;
1644
+ 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;
1613
1645
  var init_secure_proxy = __esm({
1614
1646
  "libs/core/src/secure-proxy.ts"() {
1615
1647
  "use strict";
@@ -1784,6 +1816,15 @@ var init_secure_proxy = __esm({
1784
1816
  JsonStringify2 = JSON.stringify;
1785
1817
  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.";
1786
1818
  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).";
1819
+ TypedArrayPrototype = ObjectGetPrototypeOf4(Uint8Array.prototype);
1820
+ COMPARING_BUILTINS = /* @__PURE__ */ new Set([
1821
+ Array.prototype.includes,
1822
+ Array.prototype.indexOf,
1823
+ Array.prototype.lastIndexOf,
1824
+ TypedArrayPrototype["includes"],
1825
+ TypedArrayPrototype["indexOf"],
1826
+ TypedArrayPrototype["lastIndexOf"]
1827
+ ]);
1787
1828
  }
1788
1829
  });
1789
1830
 
@@ -1909,7 +1950,6 @@ var init_reference_config = __esm({
1909
1950
  });
1910
1951
 
1911
1952
  // libs/core/src/sidecar/reference-sidecar.ts
1912
- import { randomUUID } from "crypto";
1913
1953
  var SidecarLimitError, ReferenceNotFoundError, ReferenceSidecar;
1914
1954
  var init_reference_sidecar = __esm({
1915
1955
  "libs/core/src/sidecar/reference-sidecar.ts"() {
@@ -1986,6 +2026,8 @@ var init_reference_sidecar = __esm({
1986
2026
  this.totalSize + size
1987
2027
  );
1988
2028
  }
2029
+ const randomUUID = globalThis.crypto?.randomUUID?.bind(globalThis.crypto);
2030
+ if (!randomUUID) throw new Error("Secure random UUID generation is unavailable");
1989
2031
  const refId = `${REF_ID_PREFIX}${randomUUID()}${REF_ID_SUFFIX}`;
1990
2032
  this.storage.set(refId, Buffer.from(buffer));
1991
2033
  this.totalSize += size;
@@ -2448,28 +2490,38 @@ var init_reference_resolver = __esm({
2448
2490
  /**
2449
2491
  * Check if a value contains any reference IDs
2450
2492
  *
2493
+ * Every value is looked at, at any depth: a reference or composite past `maxResolutionDepth`
2494
+ * cannot be resolved, and it must still be found, so that `resolve()` refuses the call rather
2495
+ * than the handler receiving it unresolved. The value is walked with a list instead of by
2496
+ * recursion, so a deep value cannot exhaust the stack, and an object is looked at once.
2497
+ *
2451
2498
  * @param value - The value to check
2452
- * @param depth - Current recursion depth (internal)
2499
+ * @param _depth - Unused; kept for callers that pass a depth
2453
2500
  * @returns true if the value or any nested value is a reference
2454
2501
  */
2455
- containsReferences(value, depth = 0) {
2456
- if (depth > this.config.maxResolutionDepth) {
2457
- return false;
2458
- }
2459
- if (isReferenceId(value) || isCompositeHandle(value)) {
2460
- return true;
2461
- }
2462
- if (Array.isArray(value)) {
2463
- const len = untrustedLength(value);
2464
- for (let i = 0; i < len; i++) {
2465
- if (this.containsReferences(untrustedAt(value, i), depth + 1)) {
2466
- return true;
2502
+ containsReferences(value, _depth = 0) {
2503
+ const pending = [value];
2504
+ const seen = /* @__PURE__ */ new Set();
2505
+ while (pending.length > 0) {
2506
+ const current = pending.pop();
2507
+ if (isReferenceId(current) || isCompositeHandle(current)) {
2508
+ return true;
2509
+ }
2510
+ if (current === null || typeof current !== "object" || seen.has(current)) {
2511
+ continue;
2512
+ }
2513
+ seen.add(current);
2514
+ if (Array.isArray(current)) {
2515
+ const len = untrustedLength(current);
2516
+ for (let i = 0; i < len; i++) {
2517
+ pending.push(untrustedAt(current, i));
2467
2518
  }
2519
+ continue;
2520
+ }
2521
+ const members = Object.values(current);
2522
+ for (let i = 0; i < members.length; i++) {
2523
+ pending.push(members[i]);
2468
2524
  }
2469
- return false;
2470
- }
2471
- if (value !== null && typeof value === "object") {
2472
- return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
2473
2525
  }
2474
2526
  return false;
2475
2527
  }
@@ -4145,7 +4197,9 @@ function realmArrayAccountingSource(memoryLimit) {
4145
4197
 
4146
4198
  // An array literal with spreads: [a, ...b, ...c] is compiled to
4147
4199
  // __safe_array(__safe_arrayStart(), [a, ...__safe_spread(b), ...__safe_spread(c)])
4148
- // so that each source is seen before it is spread and the result when it exists.
4200
+ // so that each source is seen before it is spread and the result when it exists. One without
4201
+ // spreads, [a, b], is compiled to __safe_array(0, [a, b]): it has no frame, and its slots are
4202
+ // checked and charged like those of any array.
4149
4203
  var frames = [];
4150
4204
  var nextId = 1;
4151
4205
 
@@ -4207,7 +4261,7 @@ function realmArrayAccountingSource(memoryLimit) {
4207
4261
 
4208
4262
  function arrayFinish(id, array) {
4209
4263
  var largest = 0;
4210
- for (var i = frames.length - 1; i >= 0; i--) {
4264
+ for (var i = id === 0 ? -1 : frames.length - 1; i >= 0; i--) {
4211
4265
  if (frames[i].id === id) {
4212
4266
  largest = frames[i].largest;
4213
4267
  frames.length = i;
@@ -4215,7 +4269,7 @@ function realmArrayAccountingSource(memoryLimit) {
4215
4269
  }
4216
4270
  }
4217
4271
  if (isArray(array)) {
4218
- checkLength(array.length, 'Array spread');
4272
+ checkLength(array.length, id === 0 ? 'Array literal' : 'Array spread');
4219
4273
  charge(array.length - largest);
4220
4274
  }
4221
4275
  return array;
@@ -5757,15 +5811,73 @@ var init_console_handler = __esm({
5757
5811
  var toText = ''.constructor;
5758
5812
  var freeze = Object.freeze;
5759
5813
  var RealmError = Error;
5814
+ var apply = Reflect.apply;
5815
+ var isArray = Array.isArray;
5816
+ var stringValueOf = ''.constructor.prototype.valueOf;
5817
+ var numberValueOf = (0).constructor.prototype.valueOf;
5818
+
5819
+ // Whether a value has the internal slot that a built-in's valueOf reads.
5820
+ function hasSlot(valueOf, value) {
5821
+ try {
5822
+ apply(valueOf, value, []);
5823
+ return true;
5824
+ } catch (e) {
5825
+ return false;
5826
+ }
5827
+ }
5760
5828
 
5761
- function formatArgument(value) {
5829
+ // The JSON text of a value, given up as soon as it would be longer than limit characters. A
5830
+ // value referenced many times is written as many times, so the text can be far longer than the
5831
+ // value is large. What each member adds is counted as JSON.stringify writes it, and the count
5832
+ // is a lower bound of its length (an escape only adds), so a text within the limit is never
5833
+ // given up. The members JSON.stringify visits are counted as well, also those it leaves out (a
5834
+ // function, undefined): at most as many as the limit has characters.
5835
+ var TOO_LARGE = {};
5836
+ function stringifyWithin(value, limit) {
5837
+ var length = 0;
5838
+ var visits = 0;
5839
+ var root = true;
5840
+ return stringify(value, function (key, member) {
5841
+ if (++visits > limit) throw TOO_LARGE;
5842
+ // A String or Number object is written as what it converts to; converted here, the way
5843
+ // JSON.stringify converts it and once, so the count is of what is written.
5844
+ if (member !== null && typeof member === 'object') {
5845
+ if (hasSlot(stringValueOf, member)) member = toText(member);
5846
+ else if (hasSlot(numberValueOf, member)) member = +member;
5847
+ }
5848
+ var added;
5849
+ var kind = typeof member;
5850
+ if (kind === 'string') added = member.length + 2;
5851
+ else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
5852
+ else if (kind === 'boolean') added = member ? 4 : 5;
5853
+ else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
5854
+ else added = 0;
5855
+ if (!root) {
5856
+ // An element of an array is written, as null if nothing else; a member of an object
5857
+ // that is written has its key in front of it.
5858
+ if (isArray(this)) added = added || 4;
5859
+ else if (added > 0) added += key.length + 3;
5860
+ }
5861
+ root = false;
5862
+ length += added;
5863
+ if (length > limit) throw TOO_LARGE;
5864
+ return member;
5865
+ });
5866
+ }
5867
+
5868
+ // An argument as it is written in the line, in at most room characters for an object: an
5869
+ // object is written only when the line has room left, and its text within that room. TOO_LARGE
5870
+ // when it does not fit.
5871
+ function formatArgument(value, room) {
5762
5872
  if (value === undefined) return 'undefined';
5763
5873
  if (value === null) return 'null';
5764
5874
  if (typeof value === 'object') {
5875
+ if (room <= 0) throw TOO_LARGE;
5765
5876
  try {
5766
- var json = stringify(value);
5877
+ var json = stringifyWithin(value, room);
5767
5878
  return json === undefined ? '' : json;
5768
5879
  } catch (e) {
5880
+ if (e === TOO_LARGE) throw e;
5769
5881
  return toText(value);
5770
5882
  }
5771
5883
  }
@@ -5776,19 +5888,38 @@ var init_console_handler = __esm({
5776
5888
  var callCount = 0;
5777
5889
  var totalBytes = 0;
5778
5890
 
5891
+ function tooLarge() {
5892
+ return new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
5893
+ }
5894
+
5779
5895
  function method(level) {
5780
5896
  return (...args) => {
5781
5897
  callCount++;
5782
5898
  if (callCount > maxCalls) {
5783
5899
  throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
5784
5900
  }
5901
+ // The line is measured as it is built: what an argument may add is the room the limit
5902
+ // leaves, so the work done on a line that does not fit is in proportion to the limit.
5785
5903
  var line = '';
5786
5904
  for (var i = 0; i < args.length; i++) {
5787
- line += (i === 0 ? '' : ' ') + formatArgument(args[i]);
5905
+ var separator = i === 0 ? '' : ' ';
5906
+ var text;
5907
+ try {
5908
+ text = formatArgument(args[i], maxBytes - totalBytes - line.length - separator.length);
5909
+ } catch (e) {
5910
+ if (e !== TOO_LARGE) throw e;
5911
+ totalBytes = maxBytes + 1;
5912
+ throw tooLarge();
5913
+ }
5914
+ line += separator + text;
5915
+ if (totalBytes + line.length > maxBytes) {
5916
+ totalBytes = maxBytes + 1;
5917
+ throw tooLarge();
5918
+ }
5788
5919
  }
5789
5920
  totalBytes += line.length;
5790
5921
  if (totalBytes > maxBytes) {
5791
- throw new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
5922
+ throw tooLarge();
5792
5923
  }
5793
5924
  try {
5794
5925
  write(level, line);
@@ -5810,6 +5941,81 @@ var init_console_handler = __esm({
5810
5941
  }
5811
5942
  });
5812
5943
 
5944
+ // libs/core/src/bounded-json.ts
5945
+ function hasSlot(valueOf, value) {
5946
+ try {
5947
+ ReflectApply7(valueOf, value, []);
5948
+ return true;
5949
+ } catch {
5950
+ return false;
5951
+ }
5952
+ }
5953
+ function stringifyWithin(value, limit) {
5954
+ let bytes = 0;
5955
+ let visits = 0;
5956
+ const maxVisits = Math.max(1e4, Math.min(1e6, limit * 10));
5957
+ let root = true;
5958
+ return JSONStringify(value, function(key, member) {
5959
+ if (++visits > maxVisits) throw new JsonTraversalLimitError(maxVisits);
5960
+ if (member !== null && typeof member === "object") {
5961
+ if (hasSlot(StringValueOf, member)) member = String(member);
5962
+ else if (hasSlot(NumberValueOf, member)) member = Number(member);
5963
+ }
5964
+ let added;
5965
+ switch (typeof member) {
5966
+ case "string":
5967
+ added = member.length + 2;
5968
+ break;
5969
+ case "number":
5970
+ added = Number.isFinite(member) ? String(member).length : 4;
5971
+ break;
5972
+ case "boolean":
5973
+ added = member ? 4 : 5;
5974
+ break;
5975
+ case "object":
5976
+ case "bigint":
5977
+ added = member === null ? 4 : 2;
5978
+ break;
5979
+ default:
5980
+ added = 0;
5981
+ }
5982
+ if (!root) {
5983
+ if (ArrayIsArray4(this)) added = added || 4;
5984
+ else if (added > 0) added += key.length + 3;
5985
+ }
5986
+ root = false;
5987
+ bytes += added;
5988
+ if (bytes > limit) throw new JsonTooLargeError(limit);
5989
+ return member;
5990
+ });
5991
+ }
5992
+ function utf8Length(value) {
5993
+ return Buffer.byteLength(value, "utf8");
5994
+ }
5995
+ var JSONStringify, ReflectApply7, ArrayIsArray4, StringValueOf, NumberValueOf, JsonTooLargeError, JsonTraversalLimitError;
5996
+ var init_bounded_json = __esm({
5997
+ "libs/core/src/bounded-json.ts"() {
5998
+ "use strict";
5999
+ JSONStringify = JSON.stringify;
6000
+ ReflectApply7 = Reflect.apply;
6001
+ ArrayIsArray4 = Array.isArray;
6002
+ StringValueOf = String.prototype.valueOf;
6003
+ NumberValueOf = Number.prototype.valueOf;
6004
+ JsonTooLargeError = class extends Error {
6005
+ constructor(limit) {
6006
+ super(`JSON text exceeds ${limit} bytes`);
6007
+ this.name = "JsonTooLargeError";
6008
+ }
6009
+ };
6010
+ JsonTraversalLimitError = class extends Error {
6011
+ constructor(limit) {
6012
+ super(`JSON traversal exceeds ${limit} members`);
6013
+ this.name = "JsonTraversalLimitError";
6014
+ }
6015
+ };
6016
+ }
6017
+ });
6018
+
5813
6019
  // libs/core/src/tool-bridge.ts
5814
6020
  function utf8ByteLength2(value) {
5815
6021
  return Buffer.byteLength(value, "utf8");
@@ -6144,6 +6350,7 @@ function createHostToolBridge(executionContext, options) {
6144
6350
  "Tool returned an unsupported value",
6145
6351
  "TOOL_RESULT_NOT_SAFE"
6146
6352
  );
6353
+ executionContext.onToolBridgeFailure?.();
6147
6354
  return serializeResponse(
6148
6355
  {
6149
6356
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -6153,6 +6360,34 @@ function createHostToolBridge(executionContext, options) {
6153
6360
  maxPayloadBytes
6154
6361
  );
6155
6362
  }
6363
+ const resultLimit = executionContext.maxToolResultBytes;
6364
+ if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
6365
+ let tooLarge = false;
6366
+ let tooComplex = false;
6367
+ try {
6368
+ const resultJson = stringifyWithin(sanitizedResult, resultLimit);
6369
+ tooLarge = resultJson !== void 0 && utf8ByteLength2(resultJson) > resultLimit;
6370
+ } catch (error) {
6371
+ tooLarge = error instanceof JsonTooLargeError;
6372
+ tooComplex = error instanceof JsonTraversalLimitError;
6373
+ }
6374
+ if (tooLarge || tooComplex) {
6375
+ executionContext.onToolBridgeFailure?.();
6376
+ return serializeResponse(
6377
+ {
6378
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
6379
+ ok: false,
6380
+ error: {
6381
+ name: "ToolBridgeError",
6382
+ message: tooComplex ? "Tool result exceeds the traversal limit" : `Tool result exceeds the limit of ${resultLimit} bytes`,
6383
+ code: tooComplex ? "TOOL_RESULT_TOO_COMPLEX" : "TOOL_RESULT_TOO_LARGE",
6384
+ toolError: true
6385
+ }
6386
+ },
6387
+ maxPayloadBytes
6388
+ );
6389
+ }
6390
+ }
6156
6391
  if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
6157
6392
  const size = utf8ByteLength2(sanitizedResult);
6158
6393
  if (size >= referenceConfig.extractionThreshold) {
@@ -6160,6 +6395,20 @@ function createHostToolBridge(executionContext, options) {
6160
6395
  const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
6161
6396
  sanitizedResult = refId;
6162
6397
  } catch {
6398
+ executionContext.onToolBridgeFailure?.();
6399
+ return serializeResponse(
6400
+ {
6401
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
6402
+ ok: false,
6403
+ error: {
6404
+ name: "ToolBridgeError",
6405
+ message: "Tool result could not be stored in the reference sidecar",
6406
+ code: "TOOL_RESULT_NOT_STORED",
6407
+ toolError: true
6408
+ }
6409
+ },
6410
+ maxPayloadBytes
6411
+ );
6163
6412
  }
6164
6413
  }
6165
6414
  }
@@ -6174,6 +6423,7 @@ function createHostToolBridge(executionContext, options) {
6174
6423
  "Tool result must be JSON-serializable",
6175
6424
  "TOOL_RESULT_NOT_JSON"
6176
6425
  );
6426
+ executionContext.onToolBridgeFailure?.();
6177
6427
  return serializeResponse(
6178
6428
  {
6179
6429
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -6184,6 +6434,7 @@ function createHostToolBridge(executionContext, options) {
6184
6434
  );
6185
6435
  }
6186
6436
  if (utf8ByteLength2(okJson) > maxPayloadBytes) {
6437
+ executionContext.onToolBridgeFailure?.();
6187
6438
  return serializeResponse(
6188
6439
  {
6189
6440
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -6218,6 +6469,7 @@ var init_tool_bridge = __esm({
6218
6469
  "use strict";
6219
6470
  init_value_sanitizer();
6220
6471
  init_reference_resolver();
6472
+ init_bounded_json();
6221
6473
  TOOL_BRIDGE_PROTOCOL_VERSION = 1;
6222
6474
  }
6223
6475
  });
@@ -6291,7 +6543,8 @@ var init_suspicious_patterns = __esm({
6291
6543
  if (localConfig) {
6292
6544
  const defaultThreshold = localConfig.rapidEnumerationThreshold ?? 30;
6293
6545
  const overrides = localConfig.rapidEnumerationOverrides ?? {};
6294
- threshold = overrides[operationName] ?? defaultThreshold;
6546
+ const override = Object.prototype.hasOwnProperty.call(overrides, operationName) ? overrides[operationName] : void 0;
6547
+ threshold = typeof override === "number" ? override : defaultThreshold;
6295
6548
  }
6296
6549
  } catch {
6297
6550
  threshold = 30;
@@ -7412,6 +7665,32 @@ var init_tool_namespaces = __esm({
7412
7665
  }
7413
7666
  });
7414
7667
 
7668
+ // libs/core/src/realm-regex-backstop.ts
7669
+ var REALM_REGEX_BACKSTOP_SOURCE;
7670
+ var init_realm_regex_backstop = __esm({
7671
+ "libs/core/src/realm-regex-backstop.ts"() {
7672
+ "use strict";
7673
+ REALM_REGEX_BACKSTOP_SOURCE = `
7674
+ (function () {
7675
+ 'use strict';
7676
+ var defineProperty = Object.defineProperty;
7677
+ var freeze = Object.freeze;
7678
+ var RealmTypeError = TypeError;
7679
+ var proto = RegExp.prototype;
7680
+ var refuse = () => {
7681
+ throw new RealmTypeError('Regular expressions are not available in this sandbox');
7682
+ };
7683
+ freeze(refuse);
7684
+ var keys = ['exec', 'test', 'compile', Symbol.match, Symbol.matchAll, Symbol.replace, Symbol.search, Symbol.split];
7685
+ for (var i = 0; i < keys.length; i++) {
7686
+ defineProperty(proto, keys[i], { value: refuse, writable: false, configurable: false, enumerable: false });
7687
+ }
7688
+ freeze(proto);
7689
+ })()
7690
+ `.trim();
7691
+ }
7692
+ });
7693
+
7415
7694
  // libs/core/src/realm-stack.ts
7416
7695
  var STACK_CAPTURE_OFF_SOURCE;
7417
7696
  var init_realm_stack = __esm({
@@ -8073,6 +8352,10 @@ function generateParentVmBootstrap(options) {
8073
8352
  const __ag_FunctionToString = Function.prototype.toString;
8074
8353
  const __ag_ObjectToLocaleString = Object.prototype.toLocaleString;
8075
8354
  const __ag_Promise = Promise;
8355
+ const __ag_JSONStringify = JSON.stringify;
8356
+ const __ag_String = String;
8357
+ const __ag_StringValueOf = String.prototype.valueOf;
8358
+ const __ag_NumberValueOf = Number.prototype.valueOf;
8076
8359
 
8077
8360
  /**
8078
8361
  * Creates a "safe" error object that cannot be used to escape the sandbox.
@@ -8481,20 +8764,23 @@ function generateParentVmBootstrap(options) {
8481
8764
  * object, with a function member replaced by one that passes its arguments through
8482
8765
  * toSandboxValue (and keeps the script's object as its receiver), and an object member or
8483
8766
  * result guarded the same way. Its own properties are listed as they are, so a built-in that
8484
- * copies or serializes the object sees the same data. An array is data to every built-in and
8485
- * is passed as it is, as is a value that is behind the membrane already.
8767
+ * copies or serializes the object sees the same data. An array gets a guard that is still an
8768
+ * array, see guardArrayForHost. A value that is behind the membrane already is passed as it is.
8486
8769
  */
8487
8770
  function guardObjectForHost(value) {
8488
8771
  if (value === null || typeof value !== 'object') {
8489
8772
  return value;
8490
8773
  }
8491
- if (membraneProxies.has(value) || guardedHostArguments.has(value) || __ag_ArrayIsArray(value)) {
8774
+ if (membraneProxies.has(value) || guardedHostArguments.has(value)) {
8492
8775
  return value;
8493
8776
  }
8494
8777
  var existing = hostArgumentGuards.get(value);
8495
8778
  if (existing) {
8496
8779
  return existing;
8497
8780
  }
8781
+ if (__ag_ArrayIsArray(value)) {
8782
+ return guardArrayForHost(value);
8783
+ }
8498
8784
  // Over an empty object of this realm, not over the script's object: a frozen member of the
8499
8785
  // target would have to be reported as it is (proxy invariant), unguarded.
8500
8786
  var guard = new __ag_ParentProxy(__ag_objectCreate(null), {
@@ -8531,6 +8817,52 @@ function generateParentVmBootstrap(options) {
8531
8817
  return guard;
8532
8818
  }
8533
8819
 
8820
+ /**
8821
+ * An array of the script on its way into a built-in method of host data. The built-ins read
8822
+ * its length and its elements and spread it (concat), so its guard is a proxy of the array
8823
+ * itself, which is an array to them. An element and the length are answered as they are: they
8824
+ * are data. Every other member is read like a member of an object (guardMemberForHost): an
8825
+ * array can carry methods of its own, and the set operations call size, has and keys of
8826
+ * whatever set-like they are given, with the host's own values. A frozen method of the array
8827
+ * cannot be answered guarded (proxy invariant), so the built-in fails instead of calling it.
8828
+ */
8829
+ function guardArrayForHost(value) {
8830
+ var guard = new __ag_ParentProxy(value, {
8831
+ get: function(target, property) {
8832
+ var member = __ag_ReflectGet(target, property, target);
8833
+ if (property === 'length' || isArrayIndexKey(property)) {
8834
+ return member;
8835
+ }
8836
+ return guardMemberForHost(member, target);
8837
+ },
8838
+ // What a built-in stores in the array is a host value like any other.
8839
+ set: function(target, property, stored) {
8840
+ return __ag_ReflectSet(target, property, toSandboxValue(stored), target);
8841
+ },
8842
+ defineProperty: function(target, property, descriptor) {
8843
+ if ('get' in descriptor || 'set' in descriptor) {
8844
+ return false;
8845
+ }
8846
+ if ('value' in descriptor) {
8847
+ descriptor.value = toSandboxValue(descriptor.value);
8848
+ }
8849
+ return __ag_ReflectDefineProperty(target, property, descriptor);
8850
+ }
8851
+ });
8852
+ hostArgumentGuards.set(value, guard);
8853
+ guardedHostArguments.set(guard, value);
8854
+ return guard;
8855
+ }
8856
+
8857
+ /** Whether a property key is an array index ('0' to '4294967294' in canonical form). */
8858
+ function isArrayIndexKey(property) {
8859
+ if (typeof property !== 'string') {
8860
+ return false;
8861
+ }
8862
+ var index = +property;
8863
+ return index >>> 0 === index && index !== 4294967295 && '' + index === property;
8864
+ }
8865
+
8534
8866
  function guardMemberForHost(member, holder) {
8535
8867
  if (typeof member !== 'function') {
8536
8868
  return guardObjectForHost(member);
@@ -9324,8 +9656,11 @@ function generateParentVmBootstrap(options) {
9324
9656
  throw createSafeError('Operation name must be a non-empty string', 'TypeError');
9325
9657
  }
9326
9658
 
9327
- // Operation name pattern validation (whitelist)
9659
+ // Operation name pattern validation (whitelist). Each test starts at the beginning of the
9660
+ // name: a global or sticky pattern would otherwise go on from where its last match ended,
9661
+ // and decide the same name differently on the next call.
9328
9662
  if (validationConfig.validateOperationNames && typeof allowedOperationPattern !== 'undefined') {
9663
+ allowedOperationPattern.lastIndex = 0;
9329
9664
  if (!allowedOperationPattern.test(operationName)) {
9330
9665
  throw createSafeError('Operation "' + operationName + '" does not match allowed pattern');
9331
9666
  }
@@ -9334,6 +9669,7 @@ function generateParentVmBootstrap(options) {
9334
9669
  // Operation name pattern validation (blacklist)
9335
9670
  if (typeof blockedOperationPatterns !== 'undefined') {
9336
9671
  for (var i = 0; i < blockedOperationPatterns.length; i++) {
9672
+ blockedOperationPatterns[i].lastIndex = 0;
9337
9673
  if (blockedOperationPatterns[i].test(operationName)) {
9338
9674
  throw createSafeError('Operation "' + operationName + '" matches blocked pattern');
9339
9675
  }
@@ -9406,6 +9742,58 @@ function generateParentVmBootstrap(options) {
9406
9742
  return false;
9407
9743
  }
9408
9744
 
9745
+ /** Whether a value has the internal slot that a built-in's valueOf reads. */
9746
+ function hasSlot(valueOf, value) {
9747
+ try {
9748
+ __ag_ReflectApply(valueOf, value, []);
9749
+ return true;
9750
+ } catch (e) {
9751
+ return false;
9752
+ }
9753
+ }
9754
+
9755
+ /**
9756
+ * The JSON text of a value, given up as soon as it would be longer than limit bytes. A value
9757
+ * referenced many times is written as many times, so the text can be far longer than the value
9758
+ * is large. What each member adds is counted as JSON.stringify writes it, and the count is a
9759
+ * lower bound of its UTF-8 bytes (a code unit is at least one byte, an escape only adds), so a
9760
+ * value whose text is within the limit is never given up. The members JSON.stringify visits are
9761
+ * counted as well, also those it leaves out (a function, undefined): at most as many as the limit
9762
+ * has bytes.
9763
+ */
9764
+ var TOO_LARGE = {};
9765
+ function stringifyWithin(value, limit) {
9766
+ var bytes = 0;
9767
+ var visits = 0;
9768
+ var root = true;
9769
+ return __ag_JSONStringify(value, function(key, member) {
9770
+ if (++visits > limit) throw TOO_LARGE;
9771
+ // A String or Number object is written as what it converts to; converted here, the way
9772
+ // JSON.stringify converts it and once, so the count is of what is written.
9773
+ if (member !== null && typeof member === 'object') {
9774
+ if (hasSlot(__ag_StringValueOf, member)) member = __ag_String(member);
9775
+ else if (hasSlot(__ag_NumberValueOf, member)) member = +member;
9776
+ }
9777
+ var added;
9778
+ var kind = typeof member;
9779
+ if (kind === 'string') added = member.length + 2;
9780
+ else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
9781
+ else if (kind === 'boolean') added = member ? 4 : 5;
9782
+ else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
9783
+ else added = 0;
9784
+ if (!root) {
9785
+ // An element of an array is written, as null if nothing else; a member of an object
9786
+ // that is written has its key in front of it.
9787
+ if (__ag_ArrayIsArray(this)) added = added || 4;
9788
+ else if (added > 0) added += key.length + 3;
9789
+ }
9790
+ root = false;
9791
+ bytes += added;
9792
+ if (bytes > limit) throw TOO_LARGE;
9793
+ return member;
9794
+ });
9795
+ }
9796
+
9409
9797
  /**
9410
9798
  * Inner VM's callTool function
9411
9799
  * Proxies through parent VM with validation
@@ -9433,11 +9821,16 @@ function generateParentVmBootstrap(options) {
9433
9821
  throw createSafeError('Tool arguments must be an object', 'TypeError');
9434
9822
  }
9435
9823
 
9436
- // Double sanitization (defense in depth)
9824
+ // Double sanitization (defense in depth). The text is written within the payload limit (see
9825
+ // stringifyWithin), so what is done before the request is measured is in proportion to the
9826
+ // limit; in direct mode as well, where the request is held to the same limit below.
9437
9827
  var sanitizedArgs;
9438
9828
  try {
9439
- sanitizedArgs = JSON.parse(JSON.stringify(args));
9829
+ sanitizedArgs = JSON.parse(stringifyWithin(args, toolBridgeMaxPayloadBytes));
9440
9830
  } catch (e) {
9831
+ if (e === TOO_LARGE) {
9832
+ throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
9833
+ }
9441
9834
  throw createSafeError('Tool arguments must be JSON-serializable');
9442
9835
  }
9443
9836
 
@@ -9529,8 +9922,12 @@ function generateParentVmBootstrap(options) {
9529
9922
  throw createSafeError('Tool bridge returned invalid response');
9530
9923
  });
9531
9924
  } else {
9532
- // Direct mode: the rejection is mapped here rather than by launderThrown alone, which
9533
- // would drop the code the host uses to mark a failure of the tool itself.
9925
+ // Direct mode: the request is held to the payload limit as through the string bridge.
9926
+ if (exceedsPayloadLimit(JSON.stringify({ v: 1, tool: toolName, args: sanitizedArgs }), toolBridgeMaxPayloadBytes)) {
9927
+ throw createSafeError('Tool request exceeds maximum size (' + toolBridgeMaxPayloadBytes + ' bytes)');
9928
+ }
9929
+ // The rejection is mapped here rather than by launderThrown alone, which would drop the
9930
+ // code the host uses to mark a failure of the tool itself.
9534
9931
  promise = deferHostCall(function() {
9535
9932
  return hostCallTool(toolName, sanitizedArgs);
9536
9933
  }, function(error) {
@@ -9540,9 +9937,16 @@ function generateParentVmBootstrap(options) {
9540
9937
  code = error && error.code;
9541
9938
  message = error && error.message;
9542
9939
  } catch (e) { /* treated as an unmarked failure */ }
9543
- if (code === 'TOOL_CALL_FAILED') {
9940
+ // A failure of the tool, or a result the host refused, keeps its code.
9941
+ if (
9942
+ code === 'TOOL_CALL_FAILED' ||
9943
+ code === 'TOOL_RESULT_NOT_STORED' ||
9944
+ code === 'TOOL_RESULT_TOO_LARGE' ||
9945
+ code === 'TOOL_RESULT_TOO_COMPLEX' ||
9946
+ code === 'TOOL_BRIDGE_RESPONSE_TOO_LARGE'
9947
+ ) {
9544
9948
  var text = typeof message === 'string' ? message : 'Tool call failed';
9545
- return markToolFailure(createSafeError(text), toolName, 'Error', text, 'TOOL_CALL_FAILED');
9949
+ return markToolFailure(createSafeError(text), toolName, 'Error', text, code);
9546
9950
  }
9547
9951
  return launderThrown(error);
9548
9952
  });
@@ -9802,8 +10206,9 @@ function generateParentVmBootstrap(options) {
9802
10206
  * Rate-limited console for inner VM
9803
10207
  */
9804
10208
  var consoleStats = { totalBytes: 0, callCount: 0 };
9805
- var maxConsoleBytes = hostConfig.maxConsoleOutputBytes || 65536;
9806
- var maxConsoleCalls = hostConfig.maxConsoleCalls || 100;
10209
+ // A limit of 0 is a limit: nothing may be written (it is not "unset").
10210
+ var maxConsoleBytes = typeof hostConfig.maxConsoleOutputBytes === 'number' ? hostConfig.maxConsoleOutputBytes : 65536;
10211
+ var maxConsoleCalls = typeof hostConfig.maxConsoleCalls === 'number' ? hostConfig.maxConsoleCalls : 100;
9807
10212
 
9808
10213
  function createSafeConsoleMethod(level) {
9809
10214
  return function() {
@@ -10356,7 +10761,7 @@ function generateParentVmBootstrap(options) {
10356
10761
  // After inner-runtime.js, whose one trusted pattern has kept its own matcher. Not optional:
10357
10762
  // a failure here aborts the execution.
10358
10763
  if (__ag_realmAllowed && __ag_realmAllowed.RegExp !== true) {
10359
- new vm.Script(${JSON.stringify(INNER_REALM_REGEX_BACKSTOP_SOURCE)}, {
10764
+ new vm.Script(${JSON.stringify(REALM_REGEX_BACKSTOP_SOURCE)}, {
10360
10765
  filename: 'inner-regex-backstop.js'
10361
10766
  }).runInContext(innerContext);
10362
10767
  }
@@ -10657,13 +11062,14 @@ function generateParentVmBootstrap(options) {
10657
11062
  })();
10658
11063
  `.trim();
10659
11064
  }
10660
- 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;
11065
+ 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;
10661
11066
  var init_parent_vm_bootstrap = __esm({
10662
11067
  "libs/core/src/double-vm/parent-vm-bootstrap.ts"() {
10663
11068
  "use strict";
10664
11069
  init_global_function_gate();
10665
11070
  init_tool_namespaces();
10666
11071
  init_console_handler();
11072
+ init_realm_regex_backstop();
10667
11073
  init_deadline_guard();
10668
11074
  init_enclave_options();
10669
11075
  init_realm_stack();
@@ -10955,24 +11361,6 @@ var init_parent_vm_bootstrap = __esm({
10955
11361
  "TypeError",
10956
11362
  "RangeError"
10957
11363
  ];
10958
- INNER_REALM_REGEX_BACKSTOP_SOURCE = `
10959
- (function () {
10960
- 'use strict';
10961
- var defineProperty = Object.defineProperty;
10962
- var freeze = Object.freeze;
10963
- var RealmTypeError = TypeError;
10964
- var proto = RegExp.prototype;
10965
- var refuse = () => {
10966
- throw new RealmTypeError('Regular expressions are not available in this sandbox');
10967
- };
10968
- freeze(refuse);
10969
- var keys = ['exec', 'test', 'compile', Symbol.match, Symbol.matchAll, Symbol.replace, Symbol.search, Symbol.split];
10970
- for (var i = 0; i < keys.length; i++) {
10971
- defineProperty(proto, keys[i], { value: refuse, writable: false, configurable: false, enumerable: false });
10972
- }
10973
- freeze(proto);
10974
- })()
10975
- `.trim();
10976
11364
  REALM_LOCKDOWN_SOURCE = `
10977
11365
  (function () {
10978
11366
  'use strict';
@@ -11071,11 +11459,17 @@ var init_parent_vm_bootstrap = __esm({
11071
11459
 
11072
11460
  // libs/core/src/double-vm/double-vm-wrapper.ts
11073
11461
  import * as vm4 from "vm";
11074
- var DoubleVmWrapper;
11462
+ function resultRefusal(message, code) {
11463
+ const error = new Error(message);
11464
+ resultRefusals.set(error, code);
11465
+ return error;
11466
+ }
11467
+ var resultRefusals, DoubleVmWrapper;
11075
11468
  var init_double_vm_wrapper = __esm({
11076
11469
  "libs/core/src/double-vm/double-vm-wrapper.ts"() {
11077
11470
  "use strict";
11078
11471
  init_value_sanitizer();
11472
+ init_bounded_json();
11079
11473
  init_secure_proxy();
11080
11474
  init_safe_error();
11081
11475
  init_reference_resolver();
@@ -11090,6 +11484,7 @@ var init_double_vm_wrapper = __esm({
11090
11484
  init_global_function_gate();
11091
11485
  init_parent_vm_bootstrap();
11092
11486
  init_suspicious_patterns();
11487
+ resultRefusals = /* @__PURE__ */ new WeakMap();
11093
11488
  DoubleVmWrapper = class {
11094
11489
  /**
11095
11490
  * @param config Double VM configuration
@@ -11413,33 +11808,72 @@ var init_double_vm_wrapper = __esm({
11413
11808
  }
11414
11809
  resolvedArgs = resolver.resolve(args);
11415
11810
  }
11811
+ let handlerCompleted = false;
11416
11812
  try {
11417
11813
  const result = await toolHandler(toolName, resolvedArgs);
11814
+ handlerCompleted = true;
11418
11815
  const sanitized = sanitizeValue(result, {
11419
11816
  maxDepth: config.maxSanitizeDepth,
11420
11817
  maxProperties: config.maxSanitizeProperties,
11421
11818
  allowDates: true,
11422
11819
  allowErrors: true
11423
11820
  });
11821
+ const resultLimit = executionContext.maxToolResultBytes;
11822
+ if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
11823
+ try {
11824
+ const resultJson = stringifyWithin(sanitized, resultLimit);
11825
+ if (resultJson !== void 0 && utf8Length(resultJson) > resultLimit) {
11826
+ throw resultRefusal(`Tool result exceeds the limit of ${resultLimit} bytes`, "TOOL_RESULT_TOO_LARGE");
11827
+ }
11828
+ } catch (error) {
11829
+ if (error instanceof JsonTraversalLimitError) {
11830
+ throw resultRefusal("Tool result exceeds the traversal limit", "TOOL_RESULT_TOO_COMPLEX");
11831
+ }
11832
+ if (error instanceof JsonTooLargeError) {
11833
+ throw resultRefusal(`Tool result exceeds the limit of ${resultLimit} bytes`, "TOOL_RESULT_TOO_LARGE");
11834
+ }
11835
+ throw error;
11836
+ }
11837
+ }
11838
+ let outgoing = sanitized;
11424
11839
  if (sidecar && referenceConfig && typeof sanitized === "string") {
11425
11840
  const size = Buffer.byteLength(sanitized, "utf-8");
11426
11841
  if (size >= referenceConfig.extractionThreshold) {
11427
11842
  try {
11428
- const refId = sidecar.store(sanitized, "tool-result", { origin: toolName });
11429
- return refId;
11430
- } catch (storageError) {
11431
- if (process.env["NODE_ENV"] !== "production") {
11432
- console.debug(
11433
- `[DoubleVmWrapper] Sidecar storage failed for tool "${toolName}": ${storageError.message}`
11434
- );
11435
- }
11436
- return sanitized;
11843
+ outgoing = sidecar.store(sanitized, "tool-result", { origin: toolName });
11844
+ } catch {
11845
+ throw resultRefusal("Tool result could not be stored in the reference sidecar", "TOOL_RESULT_NOT_STORED");
11437
11846
  }
11438
11847
  }
11439
11848
  }
11440
- return sanitized;
11849
+ const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
11850
+ let responseJson;
11851
+ try {
11852
+ responseJson = outgoing === void 0 ? void 0 : stringifyWithin(outgoing, maxPayloadBytes);
11853
+ } catch (error) {
11854
+ if (error instanceof JsonTraversalLimitError) {
11855
+ throw resultRefusal("Tool response exceeds traversal limit", "TOOL_RESULT_TOO_COMPLEX");
11856
+ }
11857
+ if (!(error instanceof JsonTooLargeError)) throw error;
11858
+ throw resultRefusal(
11859
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
11860
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
11861
+ );
11862
+ }
11863
+ if (responseJson !== void 0 && utf8Length(responseJson) > maxPayloadBytes) {
11864
+ throw resultRefusal(
11865
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
11866
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
11867
+ );
11868
+ }
11869
+ return outgoing;
11441
11870
  } catch (error) {
11871
+ if (handlerCompleted) executionContext.onToolBridgeFailure?.();
11442
11872
  const err = error;
11873
+ const refused = resultRefusals.get(error);
11874
+ if (refused) {
11875
+ throw createSafeError(err.message, "Error", refused);
11876
+ }
11443
11877
  throw createSafeError(
11444
11878
  `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`,
11445
11879
  "Error",
@@ -11692,6 +12126,12 @@ function createSafeRuntime(context, options) {
11692
12126
  const secureProxyConfig = options?.secureProxyConfig;
11693
12127
  const memoryTracker = options?.memoryTracker;
11694
12128
  const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
12129
+ const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
12130
+ const codedError = (message, code) => Object.assign(new Error(message), { code });
12131
+ const refuseToolResult = (message, code) => {
12132
+ context.onToolBridgeFailure?.();
12133
+ throw codedError(message, code);
12134
+ };
11695
12135
  const proxyOptions = {
11696
12136
  ...secureProxyConfig ? { levelConfig: secureProxyConfig } : {},
11697
12137
  ...options?.exposeToSandbox ? { exposeToSandbox: options.exposeToSandbox } : {},
@@ -11718,6 +12158,21 @@ function createSafeRuntime(context, options) {
11718
12158
  if (!context.toolHandler) {
11719
12159
  throw createSafeError("No tool handler configured. Cannot execute tool calls.");
11720
12160
  }
12161
+ let requestJson;
12162
+ try {
12163
+ requestJson = stringifyWithin({ v: 1, tool: toolName, args }, maxPayloadBytes);
12164
+ } catch (error) {
12165
+ if (error instanceof JsonTooLargeError) {
12166
+ throw createSafeError(`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`, "RangeError");
12167
+ }
12168
+ if (error instanceof JsonTraversalLimitError) {
12169
+ throw createSafeError("Tool request exceeds traversal limit", "RangeError");
12170
+ }
12171
+ throw createSafeTypeError("Tool arguments must be JSON-serializable");
12172
+ }
12173
+ if (requestJson !== void 0 && utf8Length(requestJson) > maxPayloadBytes) {
12174
+ throw createSafeError(`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`, "RangeError");
12175
+ }
11721
12176
  let resolvedArgs = args;
11722
12177
  if (resolver && resolver.containsReferences(args)) {
11723
12178
  if (resolver.wouldExceedLimit(args)) {
@@ -11737,12 +12192,34 @@ function createSafeRuntime(context, options) {
11737
12192
  }
11738
12193
  try {
11739
12194
  const result = await context.toolHandler(toolName, resolvedArgs);
11740
- const sanitized = sanitizeValue(result, {
11741
- maxDepth: 20,
11742
- maxProperties: 1e4,
11743
- allowDates: true,
11744
- allowErrors: true
11745
- });
12195
+ let sanitized;
12196
+ try {
12197
+ sanitized = sanitizeValue(result, {
12198
+ maxDepth: config.maxSanitizeDepth ?? 20,
12199
+ maxProperties: config.maxSanitizeProperties ?? 1e4,
12200
+ allowDates: true,
12201
+ allowErrors: true
12202
+ });
12203
+ } catch {
12204
+ refuseToolResult("Tool returned an unsupported value", "TOOL_RESULT_NOT_SAFE");
12205
+ }
12206
+ const resultLimit = context.maxToolResultBytes;
12207
+ if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
12208
+ let tooLarge = false;
12209
+ try {
12210
+ const resultJson = stringifyWithin(sanitized, resultLimit);
12211
+ tooLarge = resultJson !== void 0 && utf8Length(resultJson) > resultLimit;
12212
+ } catch (error) {
12213
+ if (error instanceof JsonTraversalLimitError) {
12214
+ refuseToolResult("Tool result exceeds the traversal limit", "TOOL_RESULT_TOO_COMPLEX");
12215
+ }
12216
+ if (!(error instanceof JsonTooLargeError)) throw error;
12217
+ tooLarge = true;
12218
+ }
12219
+ if (tooLarge) {
12220
+ refuseToolResult(`Tool result exceeds the limit of ${resultLimit} bytes`, "TOOL_RESULT_TOO_LARGE");
12221
+ }
12222
+ }
11746
12223
  let value = sanitized;
11747
12224
  if (sidecar && referenceConfig && typeof sanitized === "string") {
11748
12225
  const size = Buffer.byteLength(sanitized, "utf-8");
@@ -11750,27 +12227,47 @@ function createSafeRuntime(context, options) {
11750
12227
  try {
11751
12228
  value = sidecar.store(sanitized, "tool-result", { origin: toolName });
11752
12229
  } catch {
11753
- value = sanitized;
12230
+ refuseToolResult("Tool result could not be stored in the reference sidecar", "TOOL_RESULT_NOT_STORED");
11754
12231
  }
11755
12232
  }
11756
12233
  }
12234
+ let responseJson;
12235
+ try {
12236
+ responseJson = value === void 0 ? void 0 : stringifyWithin(value, maxPayloadBytes);
12237
+ } catch (error) {
12238
+ if (error instanceof JsonTraversalLimitError) {
12239
+ refuseToolResult("Tool response exceeds traversal limit", "TOOL_RESULT_TOO_COMPLEX");
12240
+ }
12241
+ if (!(error instanceof JsonTooLargeError)) throw error;
12242
+ refuseToolResult(
12243
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
12244
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
12245
+ );
12246
+ }
12247
+ if (responseJson !== void 0 && utf8Length(responseJson) > maxPayloadBytes) {
12248
+ refuseToolResult(
12249
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
12250
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE"
12251
+ );
12252
+ }
11757
12253
  return throwOnError ? value : plainResult({ success: true, data: value });
11758
12254
  } catch (error) {
11759
12255
  const err = error;
11760
12256
  const message = `Tool call failed: ${toolName} - ${err.message || "Unknown error"}`;
11761
12257
  if (!throwOnError) {
11762
- const code = error?.code;
12258
+ const code2 = error?.code;
11763
12259
  return plainResult({
11764
12260
  success: false,
11765
12261
  error: plainResult({
11766
12262
  name: "Error",
11767
12263
  message,
11768
- ...typeof code === "string" ? { code } : {},
12264
+ ...typeof code2 === "string" ? { code: code2 } : {},
11769
12265
  toolName
11770
12266
  })
11771
12267
  });
11772
12268
  }
11773
- throw createSafeError(message);
12269
+ const code = error?.code;
12270
+ throw createSafeError(message, "Error", typeof code === "string" ? code : void 0);
11774
12271
  }
11775
12272
  }
11776
12273
  function* __safe_forOf(iterable) {
@@ -12203,6 +12700,7 @@ var init_safe_runtime = __esm({
12203
12700
  "libs/core/src/safe-runtime.ts"() {
12204
12701
  "use strict";
12205
12702
  init_value_sanitizer();
12703
+ init_bounded_json();
12206
12704
  init_safe_error();
12207
12705
  init_reference_resolver();
12208
12706
  init_reference_config();
@@ -12299,7 +12797,7 @@ function createRealmAirlock(realm) {
12299
12797
  return counterpart;
12300
12798
  }
12301
12799
  }
12302
- const kind = callable ? "function" : ArrayIsArray4(hostProxy) ? "array" : "object";
12800
+ const kind = callable ? "function" : ArrayIsArray5(hostProxy) ? "array" : "object";
12303
12801
  const readValue = (key) => {
12304
12802
  const value2 = ReflectGet6(hostProxy, key, hostProxy);
12305
12803
  if (typeof value2 === "function") {
@@ -12354,7 +12852,7 @@ function createRealmAirlock(realm) {
12354
12852
  for (let i = 0; i < args.length; i++) {
12355
12853
  passed[i] = args[i];
12356
12854
  }
12357
- return toRealm(ReflectApply7(hostProxy, toHost(thisArg), passed));
12855
+ return toRealm(ReflectApply8(hostProxy, toHost(thisArg), passed));
12358
12856
  },
12359
12857
  construct() {
12360
12858
  throw createSafeError("Host functions cannot be called with new", "TypeError");
@@ -12370,7 +12868,7 @@ function createRealmAirlock(realm) {
12370
12868
  }
12371
12869
  return { toRealm, toHost, isRealmValue, isAirlockProxy };
12372
12870
  }
12373
- var HostFunctionCall, HostFunctionApply, HostFunctionBind, ReflectGet6, ReflectHas2, ReflectOwnKeys4, ReflectGetOwnPropertyDescriptor3, ReflectApply7, ArrayIsArray4, ObjectGetPrototypeOf6;
12871
+ var HostFunctionCall, HostFunctionApply, HostFunctionBind, ReflectGet6, ReflectHas2, ReflectOwnKeys4, ReflectGetOwnPropertyDescriptor3, ReflectApply8, ArrayIsArray5, ObjectGetPrototypeOf6;
12374
12872
  var init_realm_airlock = __esm({
12375
12873
  "libs/core/src/realm-airlock.ts"() {
12376
12874
  "use strict";
@@ -12384,8 +12882,8 @@ var init_realm_airlock = __esm({
12384
12882
  ReflectHas2 = Reflect.has;
12385
12883
  ReflectOwnKeys4 = Reflect.ownKeys;
12386
12884
  ReflectGetOwnPropertyDescriptor3 = Reflect.getOwnPropertyDescriptor;
12387
- ReflectApply7 = Reflect.apply;
12388
- ArrayIsArray4 = Array.isArray;
12885
+ ReflectApply8 = Reflect.apply;
12886
+ ArrayIsArray5 = Array.isArray;
12389
12887
  ObjectGetPrototypeOf6 = Object.getPrototypeOf;
12390
12888
  }
12391
12889
  });
@@ -12575,6 +13073,7 @@ var init_vm_adapter = __esm({
12575
13073
  "libs/core/src/adapters/vm-adapter.ts"() {
12576
13074
  "use strict";
12577
13075
  init_sandbox_script();
13076
+ init_realm_regex_backstop();
12578
13077
  init_safe_runtime();
12579
13078
  init_secure_proxy();
12580
13079
  init_safe_error();
@@ -13391,6 +13890,10 @@ var init_vm_adapter = __esm({
13391
13890
  var promiseThen = Promise.prototype.then;
13392
13891
  var settled = Promise.resolve();
13393
13892
  var reflectApply = Reflect.apply;
13893
+ var isArray = Array.isArray;
13894
+ var StringOf = String;
13895
+ var stringValueOf = String.prototype.valueOf;
13896
+ var numberValueOf = Number.prototype.valueOf;
13394
13897
  var maxBytes = ${numericLiteral("toolBridge.maxPayloadBytes", maxPayloadBytes)};
13395
13898
  var limitMessage = ${JSON.stringify(limitMessage)};
13396
13899
 
@@ -13459,6 +13962,56 @@ var init_vm_adapter = __esm({
13459
13962
  return err;
13460
13963
  }
13461
13964
 
13965
+ // Whether a value has the internal slot that a built-in's valueOf reads.
13966
+ function hasSlot(valueOf, value) {
13967
+ try {
13968
+ reflectApply(valueOf, value, []);
13969
+ return true;
13970
+ } catch (e) {
13971
+ return false;
13972
+ }
13973
+ }
13974
+
13975
+ // The JSON text of a value, given up as soon as it would be longer than limit bytes.
13976
+ // A value referenced many times is written as many times, so the text can be far longer
13977
+ // than the value is large. What each member adds is counted as JSON.stringify writes it,
13978
+ // and the count is a lower bound of its UTF-8 bytes (a code unit is at least one byte,
13979
+ // an escape only adds), so a value whose text is within the limit is never given up.
13980
+ // The members JSON.stringify visits are counted as well, also those it leaves out (a
13981
+ // function, undefined): at most as many as the limit has bytes.
13982
+ var TOO_LARGE = {};
13983
+ function stringifyWithin(value, limit) {
13984
+ var bytes = 0;
13985
+ var visits = 0;
13986
+ var root = true;
13987
+ return stringify(value, function (key, member) {
13988
+ if (++visits > limit) throw TOO_LARGE;
13989
+ // A String or Number object is written as what it converts to; converted here, the
13990
+ // way JSON.stringify converts it and once, so the count is of what is written.
13991
+ if (member !== null && typeof member === 'object') {
13992
+ if (hasSlot(stringValueOf, member)) member = StringOf(member);
13993
+ else if (hasSlot(numberValueOf, member)) member = +member;
13994
+ }
13995
+ var added;
13996
+ var kind = typeof member;
13997
+ if (kind === 'string') added = member.length + 2;
13998
+ else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
13999
+ else if (kind === 'boolean') added = member ? 4 : 5;
14000
+ else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
14001
+ else added = 0;
14002
+ if (!root) {
14003
+ // An element of an array is written, as null if nothing else; a member of an
14004
+ // object that is written has its key in front of it.
14005
+ if (isArray(this)) added = added || 4;
14006
+ else if (added > 0) added += key.length + 3;
14007
+ }
14008
+ root = false;
14009
+ bytes += added;
14010
+ if (bytes > limit) throw TOO_LARGE;
14011
+ return member;
14012
+ });
14013
+ }
14014
+
13462
14015
  return async function __safe_callTool(toolName, args, options) {
13463
14016
  // callTool options: only { throwOnError: false } changes behavior. Tool failures
13464
14017
  // then resolve to { success: false, error }; the enclave's own refusals still throw.
@@ -13479,11 +14032,23 @@ var init_vm_adapter = __esm({
13479
14032
  throw makeError('Tool bridge is not available', 'Error');
13480
14033
  }
13481
14034
 
13482
- // Defense-in-depth: ensure JSON-serializable input.
14035
+ // Counted here, where the call is made and before anything is done with its
14036
+ // arguments: the first maxToolCalls calls are the ones that run, also when several
14037
+ // are made before any of them is started, and a call over the limit costs nothing.
14038
+ if (countCall() !== true) {
14039
+ throw makeError(limitMessage, 'ToolLimitError');
14040
+ }
14041
+
14042
+ // Defense-in-depth: ensure JSON-serializable input. The text is written within the
14043
+ // payload limit (see stringifyWithin), so what is done before the request is
14044
+ // measured is in proportion to the limit.
13483
14045
  var sanitizedArgs;
13484
14046
  try {
13485
- sanitizedArgs = parse(stringify(args));
14047
+ sanitizedArgs = parse(stringifyWithin(args, maxBytes));
13486
14048
  } catch (e) {
14049
+ if (e === TOO_LARGE) {
14050
+ throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
14051
+ }
13487
14052
  throw makeError('Tool arguments must be JSON-serializable', 'TypeError');
13488
14053
  }
13489
14054
 
@@ -13498,11 +14063,6 @@ var init_vm_adapter = __esm({
13498
14063
  throw makeError('Tool request exceeds maximum size (' + maxBytes + ' bytes)', 'RangeError');
13499
14064
  }
13500
14065
 
13501
- // Counted here, where the call is made: the first maxToolCalls calls are the ones
13502
- // that run, also when several are made before any of them is started.
13503
- if (countCall() !== true) {
13504
- throw makeError(limitMessage, 'ToolLimitError');
13505
- }
13506
14066
  var responseJson = await callBridge(requestJson);
13507
14067
  if (typeof responseJson !== 'string') {
13508
14068
  throw makeError('Tool bridge returned invalid response', 'Error');
@@ -13656,6 +14216,12 @@ var init_vm_adapter = __esm({
13656
14216
  enumerable: false
13657
14217
  });
13658
14218
  }
14219
+ const realmAllowlist = executionContext.realmGlobalAllowlist;
14220
+ if (realmAllowlist && !realmAllowlist.includes("RegExp")) {
14221
+ compileSandboxScript(REALM_REGEX_BACKSTOP_SOURCE, { filename: "realm-regex-backstop.js" }).runInContext(
14222
+ baseSandbox
14223
+ );
14224
+ }
13659
14225
  try {
13660
14226
  INTRINSIC_OBJECT_NEUTRALIZATION_SCRIPT.runInContext(baseSandbox);
13661
14227
  } catch {
@@ -13715,8 +14281,8 @@ var init_vm_adapter = __esm({
13715
14281
  }
13716
14282
  const depthDefaulted = config.maxSanitizeDepth ?? 20;
13717
14283
  const propsDefaulted = config.maxSanitizeProperties ?? 100;
13718
- const clampedDepth = Math.max(5, Math.min(50, depthDefaulted));
13719
- const clampedProperties = Math.max(50, Math.min(1e3, propsDefaulted));
14284
+ const clampedDepth = Math.min(50, depthDefaulted);
14285
+ const clampedProperties = Math.min(1e3, propsDefaulted);
13720
14286
  const sanitizedValue = sanitizeValue(value, {
13721
14287
  maxDepth: clampedDepth,
13722
14288
  maxProperties: clampedProperties,
@@ -16534,6 +17100,7 @@ var ScoringGate = class {
16534
17100
  scorer = null;
16535
17101
  cache = null;
16536
17102
  initialized = false;
17103
+ initializing = null;
16537
17104
  constructor(config) {
16538
17105
  this.config = normalizeScoringConfig(config);
16539
17106
  this.extractor = new FeatureExtractor({ toolNamespaces: this.config.toolNamespaces });
@@ -16551,9 +17118,23 @@ var ScoringGate = class {
16551
17118
  if (this.initialized) {
16552
17119
  return;
16553
17120
  }
16554
- this.scorer = this.createScorer();
16555
- await this.scorer.initialize?.();
16556
- this.initialized = true;
17121
+ if (!this.initializing) {
17122
+ const setup = this.setUpScorer().finally(() => {
17123
+ if (this.initializing === setup) this.initializing = null;
17124
+ });
17125
+ this.initializing = setup;
17126
+ }
17127
+ return this.initializing;
17128
+ }
17129
+ async setUpScorer() {
17130
+ const scorer = this.createScorer();
17131
+ this.scorer = scorer;
17132
+ await scorer.initialize?.();
17133
+ if (this.scorer === scorer) {
17134
+ this.initialized = true;
17135
+ } else if (this.scorer === null) {
17136
+ scorer.dispose?.();
17137
+ }
16557
17138
  }
16558
17139
  /**
16559
17140
  * Create the appropriate scorer based on configuration
@@ -16708,6 +17289,7 @@ var ScoringGate = class {
16708
17289
  this.scorer = null;
16709
17290
  this.cache = null;
16710
17291
  this.initialized = false;
17292
+ this.initializing = null;
16711
17293
  }
16712
17294
  /**
16713
17295
  * Check if the gate is ready to evaluate
@@ -17175,8 +17757,11 @@ var Enclave = class {
17175
17757
  * @param toolHandler Optional tool handler (overrides constructor config)
17176
17758
  * @returns Execution result
17177
17759
  */
17178
- async run(code, toolHandler) {
17179
- const result = await this.execute(code, toolHandler);
17760
+ async run(code, toolHandler, options = {}) {
17761
+ if (options.maxToolResultBytes !== void 0 && (typeof options.maxToolResultBytes !== "number" || !Number.isFinite(options.maxToolResultBytes) || options.maxToolResultBytes <= 0)) {
17762
+ throw new TypeError("maxToolResultBytes must be a positive finite number");
17763
+ }
17764
+ const result = await this.execute(code, toolHandler, options);
17180
17765
  return this.applyStackTracePolicy(result);
17181
17766
  }
17182
17767
  /**
@@ -17197,7 +17782,7 @@ var Enclave = class {
17197
17782
  /**
17198
17783
  * Transform, validate and execute. `run` applies the stack-trace policy to what this returns.
17199
17784
  */
17200
- async execute(code, toolHandler) {
17785
+ async execute(code, toolHandler, options = {}) {
17201
17786
  const startTime = Date.now();
17202
17787
  const stats = {
17203
17788
  duration: 0,
@@ -17286,6 +17871,7 @@ ${errorMessages}`,
17286
17871
  };
17287
17872
  }
17288
17873
  }
17874
+ const codeForScoring = transformedCode;
17289
17875
  if (sidecar && this.referenceConfig) {
17290
17876
  transformedCode = this.applySidecarTransforms(transformedCode, sidecar);
17291
17877
  } else if (this.config.memoryLimit && this.config.memoryLimit > 0) {
@@ -17318,7 +17904,7 @@ ${errorMessages}`,
17318
17904
  }
17319
17905
  let scoringResult;
17320
17906
  if (this.scoringGate) {
17321
- scoringResult = await this.scoringGate.evaluate(transformedCode);
17907
+ scoringResult = await this.scoringGate.evaluate(codeForScoring);
17322
17908
  if (!scoringResult.allowed) {
17323
17909
  const hasScore = typeof scoringResult.totalScore === "number";
17324
17910
  const signalSummary = scoringResult.signals && scoringResult.signals.length > 0 ? scoringResult.signals.map((s) => `${s.id}: ${s.description}`).join("; ") : scoringResult.reason ?? "Unknown risk";
@@ -17362,6 +17948,13 @@ ${errorMessages}`,
17362
17948
  abortRequested = value;
17363
17949
  },
17364
17950
  toolHandler: hostToolHandler ? trackToolCalls(hostToolHandler, hostActivity) : void 0,
17951
+ maxToolResultBytes: options.maxToolResultBytes,
17952
+ onToolBridgeFailure: options.onToolBridgeFailure ? () => {
17953
+ try {
17954
+ options.onToolBridgeFailure?.();
17955
+ } catch {
17956
+ }
17957
+ } : void 0,
17365
17958
  hostActivity,
17366
17959
  consoleHandler: hostConsoleHandler ? (level, message) => returned ? void 0 : asyncContexts.inHostContext(() => hostConsoleHandler(level, message)) : void 0,
17367
17960
  sidecar,
@@ -18079,6 +18672,11 @@ var ReturnSignal = class {
18079
18672
  this.value = value;
18080
18673
  }
18081
18674
  };
18675
+ var ScriptThrown = class {
18676
+ constructor(value) {
18677
+ this.value = value;
18678
+ }
18679
+ };
18082
18680
  var BreakSignal = class {
18083
18681
  };
18084
18682
  var ContinueSignal = class {
@@ -18242,33 +18840,44 @@ var Interpreter = class {
18242
18840
  * For a host helper that is handed a callback (`parallel(items, fn)`): `fn` may be a function
18243
18841
  * of the script, or a built-in or host function the script passed along.
18244
18842
  */
18245
- call(fn, args) {
18246
- if (this.fatal !== void 0) throw this.fatal;
18247
- if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
18248
- if (this.interpretedFunctions.has(fn)) return fn(...args);
18249
- return this.callFunction(fn, void 0, args, this.callerDepth);
18843
+ async call(fn, args) {
18844
+ try {
18845
+ if (this.fatal !== void 0) throw this.fatal;
18846
+ if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
18847
+ if (this.interpretedFunctions.has(fn)) return await fn(...args);
18848
+ return await this.callFunction(fn, void 0, args, this.callerDepth);
18849
+ } catch (thrown) {
18850
+ if (thrown instanceof ScriptThrown) throw thrown.value;
18851
+ if (!(thrown instanceof Error)) throw new InterpreterError("Host operation failed");
18852
+ throw thrown;
18853
+ }
18250
18854
  }
18251
18855
  /** Number of AST nodes evaluated so far (for execution stats). */
18252
18856
  get stepCount() {
18253
18857
  return this.steps;
18254
18858
  }
18255
18859
  async run(program) {
18256
- const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
18257
- for (const stmt of program.body) {
18258
- if (stmt.type === "FunctionDeclaration" && stmt.id) {
18259
- root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
18860
+ try {
18861
+ const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
18862
+ for (const stmt of program.body) {
18863
+ if (stmt.type === "FunctionDeclaration" && stmt.id) {
18864
+ root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
18865
+ }
18260
18866
  }
18867
+ let last;
18868
+ for (const stmt of program.body) {
18869
+ if (stmt.type === "FunctionDeclaration") continue;
18870
+ last = await this.execStatement(stmt, root);
18871
+ }
18872
+ if (root.has("__ag_main")) {
18873
+ const main = root.get("__ag_main");
18874
+ if (typeof main === "function") return await main();
18875
+ }
18876
+ return last;
18877
+ } catch (thrown) {
18878
+ if (thrown instanceof ScriptThrown) throw thrown.value;
18879
+ throw thrown;
18261
18880
  }
18262
- let last;
18263
- for (const stmt of program.body) {
18264
- if (stmt.type === "FunctionDeclaration") continue;
18265
- last = await this.execStatement(stmt, root);
18266
- }
18267
- if (root.has("__ag_main")) {
18268
- const main = root.get("__ag_main");
18269
- if (typeof main === "function") return main();
18270
- }
18271
- return last;
18272
18881
  }
18273
18882
  /**
18274
18883
  * End the run from outside: whatever of the script is still going (a callback waiting for a
@@ -18442,7 +19051,7 @@ var Interpreter = class {
18442
19051
  case "TryStatement":
18443
19052
  return this.execTry(node, scope);
18444
19053
  case "ThrowStatement":
18445
- throw await this.evalExpr(node.argument, scope);
19054
+ throw new ScriptThrown(await this.evalExpr(node.argument, scope));
18446
19055
  case "ReturnStatement":
18447
19056
  throw new ReturnSignal(node.argument ? await this.evalReturned(node.argument, scope) : void 0);
18448
19057
  case "BreakStatement":
@@ -18564,12 +19173,12 @@ var Interpreter = class {
18564
19173
  }
18565
19174
  }
18566
19175
  /**
18567
- * What a `catch` clause receives. A value the script threw is its own. A host Error (a refusal
18568
- * by the interpreter, a failed tool call, a TypeError of a built-in) is replaced by a plain
18569
- * copy with its name, message and code.
19176
+ * What a `catch` clause receives. A value the script threw is its own. A host Error is copied
19177
+ * with its name, message and code; every other host rejection reason becomes a generic error.
18570
19178
  */
18571
19179
  toScriptValue(thrown) {
18572
- if (!(thrown instanceof Error)) return thrown;
19180
+ if (thrown instanceof ScriptThrown) return thrown.value;
19181
+ if (!(thrown instanceof Error)) return createScriptError("Error", "Host operation failed");
18573
19182
  const known = this.errorCopies.get(thrown);
18574
19183
  if (known) return known;
18575
19184
  const code = thrown.code;
@@ -19960,23 +20569,23 @@ function expandReplacement(template, text, at, matched) {
19960
20569
  function convertedOnce(value, convert) {
19961
20570
  return typeof value === "object" && value !== null ? convert(value) : value;
19962
20571
  }
19963
- function checkArrayWrite(array, key, value) {
20572
+ function checkArrayWrite(array, key, value, currentLength = array.length) {
19964
20573
  if (key === "length") value = convertedOnce(value, Number);
19965
- const length = arrayLengthAfterWrite(array, key, value);
20574
+ const length = arrayLengthAfterWrite(currentLength, key, value);
19966
20575
  if (length > MAX_ARRAY_LENGTH2) {
19967
20576
  throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH2} items`);
19968
20577
  }
19969
20578
  return { value, length };
19970
20579
  }
19971
- function arrayLengthAfterWrite(array, key, value) {
20580
+ function arrayLengthAfterWrite(currentLength, key, value) {
19972
20581
  if (key === "length") {
19973
20582
  const length = Number(value);
19974
20583
  if (!Number.isInteger(length) || length < 0) throw new InterpreterError("Invalid array length");
19975
20584
  return length;
19976
20585
  }
19977
20586
  const index = Number(key);
19978
- if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(array.length, index + 1);
19979
- return array.length;
20587
+ if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(currentLength, index + 1);
20588
+ return currentLength;
19980
20589
  }
19981
20590
 
19982
20591
  // libs/core/src/interpreter/safe-globals.ts
@@ -19998,7 +20607,7 @@ function indentationSize(value, indent, limit, depth, path2) {
19998
20607
  path2.delete(value);
19999
20608
  return size;
20000
20609
  }
20001
- function utf8Length(text) {
20610
+ function utf8Length2(text) {
20002
20611
  let bytes = 0;
20003
20612
  for (let index = 0; index < text.length; index++) {
20004
20613
  const code = text.charCodeAt(index);
@@ -20016,7 +20625,7 @@ function utf8Length(text) {
20016
20625
  }
20017
20626
  function indentOf(space) {
20018
20627
  if (typeof space === "number") return Math.max(0, Math.min(MAX_JSON_INDENT, Math.floor(space) || 0));
20019
- if (typeof space === "string") return utf8Length(space.slice(0, MAX_JSON_INDENT));
20628
+ if (typeof space === "string") return utf8Length2(space.slice(0, MAX_JSON_INDENT));
20020
20629
  return 0;
20021
20630
  }
20022
20631
  function parsedJsonCost(text) {
@@ -20112,13 +20721,26 @@ var SafeObject = frozenRecord({
20112
20721
  if (!isScriptData(target) || Object.isFrozen(target)) {
20113
20722
  throw new TypeError("Object.assign needs an object or array the script created as its target");
20114
20723
  }
20724
+ const targetIsArray = Array.isArray(target);
20725
+ const lengths = [];
20726
+ let length = targetIsArray ? target.length : 0;
20115
20727
  for (const source of sources) {
20116
20728
  if (source === null || source === void 0) continue;
20117
20729
  for (const key of dataKeys(source)) {
20118
- let value = source[key];
20730
+ const value = source[key];
20119
20731
  assertStorable(target, key, value);
20120
- if (Array.isArray(target)) value = checkArrayWrite(target, key, value).value;
20121
- target[key] = value;
20732
+ if (targetIsArray) {
20733
+ const checked = checkArrayWrite(target, key, value, length);
20734
+ length = checked.length;
20735
+ if (key === "length") lengths.push(checked.value);
20736
+ }
20737
+ }
20738
+ }
20739
+ let nextLength = 0;
20740
+ for (const source of sources) {
20741
+ if (source === null || source === void 0) continue;
20742
+ for (const key of dataKeys(source)) {
20743
+ target[key] = targetIsArray && key === "length" ? lengths[nextLength++] : source[key];
20122
20744
  }
20123
20745
  }
20124
20746
  return target;
@@ -20333,7 +20955,9 @@ init_memory_tracker();
20333
20955
  init_reference_config();
20334
20956
  init_reference_resolver();
20335
20957
  init_stack_trace();
20958
+ init_thrown_value();
20336
20959
  init_tool_bridge();
20960
+ init_bounded_json();
20337
20961
  init_value_sanitizer();
20338
20962
  var DEFAULT_MAX_STEPS = 5e6;
20339
20963
  var DEFAULT_MAX_CALL_DEPTH = 256;
@@ -20515,7 +21139,7 @@ var InterpreterAdapter = class {
20515
21139
  */
20516
21140
  runtimeGlobals(context, charge, callbacks) {
20517
21141
  const { config } = context;
20518
- const callTool = observed(this.createCallTool(context, callbacks));
21142
+ const callTool = observed(this.createCallTool(context, callbacks, charge));
20519
21143
  const resolver = context.sidecar && context.referenceConfig ? new ReferenceResolver(context.sidecar, context.referenceConfig) : void 0;
20520
21144
  const joinReferences = (parts) => {
20521
21145
  if (!resolver) {
@@ -20597,9 +21221,21 @@ var InterpreterAdapter = class {
20597
21221
  const settled = await Promise.allSettled(tasks.map(async (task) => task()));
20598
21222
  const failures = settled.filter((result) => result.status === "rejected");
20599
21223
  if (failures.length > 0) {
20600
- const messages = failures.map((failure2) => this.describe(failure2.reason).message).join("\n");
20601
- throw sandboxError(`${failures.length} of ${tasks.length} parallel operations failed:
20602
- ${messages}`);
21224
+ let messages = "";
21225
+ let listed = 0;
21226
+ for (const failure2 of failures) {
21227
+ const room = MAX_THROWN_MESSAGE_LENGTH - messages.length - (listed === 0 ? 0 : 1);
21228
+ if (room <= 0) break;
21229
+ const message = this.describe(failure2.reason).message;
21230
+ messages += (listed === 0 ? "" : "\n") + (message.length > room ? message.slice(0, room) : message);
21231
+ listed++;
21232
+ }
21233
+ const unlisted = failures.length - listed;
21234
+ throw sandboxError(
21235
+ `${failures.length} of ${tasks.length} parallel operations failed:
21236
+ ${messages}` + (unlisted > 0 ? `
21237
+ (${unlisted} more not shown)` : "")
21238
+ );
20603
21239
  }
20604
21240
  return settled.map((result) => result.value);
20605
21241
  });
@@ -20656,9 +21292,81 @@ ${messages}`);
20656
21292
  }
20657
21293
  const custom = config.globals;
20658
21294
  if (custom && typeof custom === "object") {
21295
+ const maxGlobalCalls = config.maxGlobalFunctionCalls ?? Math.max(10, config.maxToolCalls * 10);
21296
+ const payloadLimit = config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_TOOL_PAYLOAD_BYTES;
21297
+ let globalCalls = 0;
21298
+ const serialize = (value) => {
21299
+ const sanitized = sanitizeValue(value, {
21300
+ maxDepth: config.maxSanitizeDepth,
21301
+ maxProperties: config.maxSanitizeProperties,
21302
+ allowDates: false,
21303
+ allowErrors: true
21304
+ });
21305
+ const json = stringifyWithin(sanitized, payloadLimit);
21306
+ if (json === void 0) return void 0;
21307
+ if (utf8Length(json) > payloadLimit) throw sandboxError("Global function value exceeds bridge limit");
21308
+ return json;
21309
+ };
21310
+ const copy = (value) => {
21311
+ const json = serialize(value);
21312
+ return json === void 0 ? void 0 : JSON.parse(json);
21313
+ };
21314
+ const safeHostCall = (name, fn) => (...args) => {
21315
+ if (callbacks.over || context.aborted) throw executionOver();
21316
+ if (++globalCalls > maxGlobalCalls)
21317
+ throw sandboxError(`Global function call limit exceeded (${maxGlobalCalls})`);
21318
+ if (context.beforeGlobalCall && context.beforeGlobalCall() !== true) {
21319
+ throw sandboxError("Global function policy refused the call");
21320
+ }
21321
+ let safeArgs;
21322
+ try {
21323
+ safeArgs = copy(args);
21324
+ } catch {
21325
+ throw sandboxError(`Global function ${name} received unsupported arguments`, "TypeError");
21326
+ }
21327
+ let outcome;
21328
+ try {
21329
+ outcome = fn(...safeArgs);
21330
+ } catch {
21331
+ throw sandboxError("Global function failed");
21332
+ }
21333
+ const settle = (value) => {
21334
+ if (callbacks.over || context.aborted) throw executionOver();
21335
+ let json;
21336
+ try {
21337
+ json = serialize(value);
21338
+ } catch {
21339
+ throw sandboxError(`Global function ${name} returned an unsupported value`);
21340
+ }
21341
+ if (json === void 0) return void 0;
21342
+ if (value !== null && typeof value === "object") charge(Math.max(json.length * 2, utf8Length(json)));
21343
+ return JSON.parse(json);
21344
+ };
21345
+ if (outcome !== null && (typeof outcome === "object" || typeof outcome === "function")) {
21346
+ let then;
21347
+ try {
21348
+ then = outcome.then;
21349
+ } catch {
21350
+ throw sandboxError(`Global function ${name} returned an unsupported value`);
21351
+ }
21352
+ if (typeof then === "function") {
21353
+ return observed(async () => {
21354
+ let value;
21355
+ try {
21356
+ value = await Promise.resolve(outcome);
21357
+ } catch {
21358
+ throw sandboxError("Global function failed");
21359
+ }
21360
+ return settle(value);
21361
+ })();
21362
+ }
21363
+ }
21364
+ return settle(outcome);
21365
+ };
20659
21366
  for (const name of Object.keys(custom)) {
20660
21367
  if (name.startsWith("__") || Object.prototype.hasOwnProperty.call(globals, name)) continue;
20661
- globals[name] = frozenDataCopy(name, custom[name]);
21368
+ const value = custom[name];
21369
+ globals[name] = typeof value === "function" ? safeHostCall(name, value) : frozenDataCopy(name, value);
20662
21370
  }
20663
21371
  }
20664
21372
  return globals;
@@ -20668,7 +21376,7 @@ ${messages}`);
20668
21376
  * and the response cross as JSON, so the handler never receives a value of the script and the
20669
21377
  * script never receives an object of the handler.
20670
21378
  */
20671
- createCallTool(context, execution) {
21379
+ createCallTool(context, execution, charge) {
20672
21380
  const configured = context.config.toolHandler;
20673
21381
  const bridgeContext = context.toolHandler === void 0 && typeof configured === "function" ? Object.create(context, { toolHandler: { value: configured } }) : context;
20674
21382
  const bridge = createHostToolBridge(bridgeContext, { updateStats: true });
@@ -20699,9 +21407,20 @@ ${messages}`);
20699
21407
  } catch {
20700
21408
  throw sandboxError("Tool arguments must be JSON-serializable", "TypeError");
20701
21409
  }
21410
+ if (utf8Length(requestJson) > maxPayloadBytes) {
21411
+ throw sandboxError(`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`, "ToolBridgeError");
21412
+ }
21413
+ if (context.beforeToolCall) {
21414
+ const request = JSON.parse(requestJson);
21415
+ if (context.beforeToolCall(toolName, request.args) !== true) {
21416
+ throw sandboxError("Tool policy refused the call");
21417
+ }
21418
+ }
20702
21419
  let response;
21420
+ let responseJson;
20703
21421
  try {
20704
- response = JSON.parse(await bridge(requestJson));
21422
+ responseJson = await bridge(requestJson);
21423
+ response = JSON.parse(responseJson);
20705
21424
  } catch {
20706
21425
  throw sandboxError("Tool bridge returned invalid JSON");
20707
21426
  }
@@ -20710,6 +21429,15 @@ ${messages}`);
20710
21429
  }
20711
21430
  const reply = response;
20712
21431
  if (reply.ok === true) {
21432
+ try {
21433
+ charge(Math.max(responseJson.length * 2, utf8Length(responseJson)));
21434
+ } catch (error) {
21435
+ try {
21436
+ context.onToolBridgeFailure?.();
21437
+ } catch {
21438
+ }
21439
+ throw error;
21440
+ }
20713
21441
  return throwOnError ? reply.value : { success: true, data: reply.value };
20714
21442
  }
20715
21443
  if (reply.ok === false && reply.error && typeof reply.error === "object") {