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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +291 -105
  2. package/adapters/worker-pool/config.d.ts +15 -5
  3. package/adapters/worker-pool/protocol.d.ts +27 -1
  4. package/adapters/worker-pool/worker-pool-adapter.d.ts +24 -0
  5. package/adapters/worker-pool/worker-slot.d.ts +35 -6
  6. package/async-context.d.ts +34 -0
  7. package/babel/babel-wrapper.d.ts +21 -12
  8. package/babel/multi-file-transform.d.ts +3 -0
  9. package/babel/text-scan.d.ts +54 -0
  10. package/bounded-json.d.ts +33 -0
  11. package/deadline-guard.d.ts +16 -0
  12. package/dynamic-import.d.ts +25 -0
  13. package/enclave-options.d.ts +62 -0
  14. package/enclave.d.ts +35 -8
  15. package/esm/index.mjs +5520 -917
  16. package/esm/worker.mjs +2777 -195
  17. package/execution-deadline.d.ts +6 -0
  18. package/global-function-gate.d.ts +34 -1
  19. package/index.d.ts +3 -3
  20. package/index.js +5562 -959
  21. package/interpreter/interpreter.d.ts +207 -10
  22. package/memory-tracker.d.ts +7 -0
  23. package/package.json +3 -3
  24. package/portable-enclave.d.ts +51 -0
  25. package/portable-globals.d.ts +2 -0
  26. package/realm-airlock.d.ts +6 -1
  27. package/realm-memory.d.ts +89 -0
  28. package/realm-regex-backstop.d.ts +18 -0
  29. package/realm-stack.d.ts +25 -0
  30. package/safe-runtime.d.ts +2 -0
  31. package/sandbox-rejections.d.ts +3 -1
  32. package/scoring/feature-extractor.d.ts +52 -1
  33. package/scoring/index.d.ts +2 -1
  34. package/scoring/scorers/index.d.ts +2 -1
  35. package/scoring/scorers/local-llm.scorer.d.ts +9 -3
  36. package/scoring/scorers/progressive.scorer.d.ts +28 -1
  37. package/scoring/scorers/rule-based.scorer.d.ts +11 -1
  38. package/scoring/scoring-gate.d.ts +2 -0
  39. package/scoring/types.d.ts +36 -8
  40. package/secure-proxy.d.ts +17 -3
  41. package/session/session.d.ts +8 -1
  42. package/session-types.d.ts +6 -4
  43. package/sidecar/index.d.ts +1 -1
  44. package/sidecar/reference-config.d.ts +18 -1
  45. package/sidecar/reference-resolver.d.ts +26 -3
  46. package/sidecar/reference-sidecar.d.ts +37 -0
  47. package/src/adapters/worker-pool/package.json +3 -3
  48. package/src/adapters/worker-pool/worker-script.js +2835 -465
  49. package/thrown-value.d.ts +59 -0
  50. package/types.d.ts +85 -19
  51. package/value-sanitizer.d.ts +6 -1
  52. package/worker.d.ts +2 -0
  53. package/worker.js +2767 -195
package/worker.js CHANGED
@@ -30,9 +30,11 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // libs/core/src/worker.ts
31
31
  var worker_exports = {};
32
32
  __export(worker_exports, {
33
+ AgentScriptRunner: () => AgentScriptRunner,
33
34
  Interpreter: () => Interpreter,
34
35
  InterpreterAdapter: () => InterpreterAdapter,
35
36
  InterpreterError: () => InterpreterError,
37
+ PortableEnclave: () => PortableEnclave,
36
38
  StepLimitError: () => StepLimitError
37
39
  });
38
40
  module.exports = __toCommonJS(worker_exports);
@@ -84,15 +86,73 @@ var CONSOLE_FACTORY_SOURCE = `
84
86
  var toText = ''.constructor;
85
87
  var freeze = Object.freeze;
86
88
  var RealmError = Error;
89
+ var apply = Reflect.apply;
90
+ var isArray = Array.isArray;
91
+ var stringValueOf = ''.constructor.prototype.valueOf;
92
+ var numberValueOf = (0).constructor.prototype.valueOf;
87
93
 
88
- function formatArgument(value) {
94
+ // Whether a value has the internal slot that a built-in's valueOf reads.
95
+ function hasSlot(valueOf, value) {
96
+ try {
97
+ apply(valueOf, value, []);
98
+ return true;
99
+ } catch (e) {
100
+ return false;
101
+ }
102
+ }
103
+
104
+ // The JSON text of a value, given up as soon as it would be longer than limit characters. A
105
+ // value referenced many times is written as many times, so the text can be far longer than the
106
+ // value is large. What each member adds is counted as JSON.stringify writes it, and the count
107
+ // is a lower bound of its length (an escape only adds), so a text within the limit is never
108
+ // given up. The members JSON.stringify visits are counted as well, also those it leaves out (a
109
+ // function, undefined): at most as many as the limit has characters.
110
+ var TOO_LARGE = {};
111
+ function stringifyWithin(value, limit) {
112
+ var length = 0;
113
+ var visits = 0;
114
+ var root = true;
115
+ return stringify(value, function (key, member) {
116
+ if (++visits > limit) throw TOO_LARGE;
117
+ // A String or Number object is written as what it converts to; converted here, the way
118
+ // JSON.stringify converts it and once, so the count is of what is written.
119
+ if (member !== null && typeof member === 'object') {
120
+ if (hasSlot(stringValueOf, member)) member = toText(member);
121
+ else if (hasSlot(numberValueOf, member)) member = +member;
122
+ }
123
+ var added;
124
+ var kind = typeof member;
125
+ if (kind === 'string') added = member.length + 2;
126
+ else if (kind === 'number') added = member - member === 0 ? ('' + member).length : 4;
127
+ else if (kind === 'boolean') added = member ? 4 : 5;
128
+ else if (kind === 'object' || kind === 'bigint') added = member === null ? 4 : 2;
129
+ else added = 0;
130
+ if (!root) {
131
+ // An element of an array is written, as null if nothing else; a member of an object
132
+ // that is written has its key in front of it.
133
+ if (isArray(this)) added = added || 4;
134
+ else if (added > 0) added += key.length + 3;
135
+ }
136
+ root = false;
137
+ length += added;
138
+ if (length > limit) throw TOO_LARGE;
139
+ return member;
140
+ });
141
+ }
142
+
143
+ // An argument as it is written in the line, in at most room characters for an object: an
144
+ // object is written only when the line has room left, and its text within that room. TOO_LARGE
145
+ // when it does not fit.
146
+ function formatArgument(value, room) {
89
147
  if (value === undefined) return 'undefined';
90
148
  if (value === null) return 'null';
91
149
  if (typeof value === 'object') {
150
+ if (room <= 0) throw TOO_LARGE;
92
151
  try {
93
- var json = stringify(value);
152
+ var json = stringifyWithin(value, room);
94
153
  return json === undefined ? '' : json;
95
154
  } catch (e) {
155
+ if (e === TOO_LARGE) throw e;
96
156
  return toText(value);
97
157
  }
98
158
  }
@@ -103,19 +163,38 @@ var CONSOLE_FACTORY_SOURCE = `
103
163
  var callCount = 0;
104
164
  var totalBytes = 0;
105
165
 
166
+ function tooLarge() {
167
+ return new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
168
+ }
169
+
106
170
  function method(level) {
107
171
  return (...args) => {
108
172
  callCount++;
109
173
  if (callCount > maxCalls) {
110
174
  throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
111
175
  }
176
+ // The line is measured as it is built: what an argument may add is the room the limit
177
+ // leaves, so the work done on a line that does not fit is in proportion to the limit.
112
178
  var line = '';
113
179
  for (var i = 0; i < args.length; i++) {
114
- line += (i === 0 ? '' : ' ') + formatArgument(args[i]);
180
+ var separator = i === 0 ? '' : ' ';
181
+ var text;
182
+ try {
183
+ text = formatArgument(args[i], maxBytes - totalBytes - line.length - separator.length);
184
+ } catch (e) {
185
+ if (e !== TOO_LARGE) throw e;
186
+ totalBytes = maxBytes + 1;
187
+ throw tooLarge();
188
+ }
189
+ line += separator + text;
190
+ if (totalBytes + line.length > maxBytes) {
191
+ totalBytes = maxBytes + 1;
192
+ throw tooLarge();
193
+ }
115
194
  }
116
195
  totalBytes += line.length;
117
196
  if (totalBytes > maxBytes) {
118
- throw new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
197
+ throw tooLarge();
119
198
  }
120
199
  try {
121
200
  write(level, line);
@@ -155,11 +234,65 @@ function readProperty(object, key) {
155
234
  if (key === "__proto__" || BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
156
235
  return object[key];
157
236
  }
237
+ var ENGINE_CALLED_KEYS = /* @__PURE__ */ new Set(["then", "toString", "valueOf", "toJSON", "toLocaleString", "toISOString"]);
238
+ function isEngineCalledKey(key) {
239
+ return ENGINE_CALLED_KEYS.has(key);
240
+ }
241
+ function assertStorable(target, key, value) {
242
+ if (typeof value !== "function") return;
243
+ if (ENGINE_CALLED_KEYS.has(key) || key === "join" && Array.isArray(target)) {
244
+ throw new InterpreterError(
245
+ `A function cannot be stored under '${key}': the sandbox runs a function only where the script calls it`
246
+ );
247
+ }
248
+ }
158
249
  var MAX_STRING_OP_LENGTH = 1e6;
159
250
  var MAX_JOIN_LENGTH = 16e6;
160
251
  var MAX_TEXT_NESTING = 64;
161
252
  var MAX_TEXT_ITEMS = 8e6;
162
253
  var MAX_ARRAY_LENGTH = 1e6;
254
+ var CLOCK_CHECK_STEPS = 256;
255
+ var WORK_PER_STEP = 16384;
256
+ var WRITE_WORK = 8;
257
+ var LOCALE_COMPARE_WORK = 64;
258
+ var SEARCH_PIECE_WORK = 2 ** 20;
259
+ var LONG_SEARCH_TEXT = 64;
260
+ var MAX_CALL_WORK = 2 ** 33;
261
+ var MAX_BIGINT_BITS = 2 ** 20;
262
+ var MAX_BIGINT_DIGITS = Math.ceil(MAX_BIGINT_BITS * Math.log10(2)) + 1;
263
+ var WORD_BITS = 64;
264
+ var BIGINT_WORK = 64;
265
+ var BIGINT_TEXT_WORK = 1024;
266
+ var COMPARISONS = /* @__PURE__ */ new Set(["==", "!=", "<", "<=", ">", ">="]);
267
+ function bitsOf(value) {
268
+ const hex = value.toString(16);
269
+ const start = value < 0n ? 1 : 0;
270
+ return (hex.length - start - 1) * 4 + (32 - Math.clz32(Number.parseInt(hex[start], 16)));
271
+ }
272
+ function bigIntTooLarge() {
273
+ return new InterpreterError(`A BigInt cannot be larger than ${MAX_BIGINT_BITS} bits`);
274
+ }
275
+ var CONSTANT_STRING_METHODS = /* @__PURE__ */ new Set([
276
+ "at",
277
+ "charAt",
278
+ "charCodeAt",
279
+ "codePointAt",
280
+ "valueOf",
281
+ "toString",
282
+ "slice",
283
+ "substring",
284
+ "substr",
285
+ "concat",
286
+ "startsWith",
287
+ "endsWith",
288
+ "padStart",
289
+ "padEnd",
290
+ "repeat"
291
+ ]);
292
+ var CONSTANT_ARRAY_METHODS = /* @__PURE__ */ new Set(["at", "push", "pop", "slice", "keys", "values", "entries"]);
293
+ var TEXT_SEARCHES = /* @__PURE__ */ new Set(["indexOf", "lastIndexOf", "includes", "split", "replace", "replaceAll"]);
294
+ var ARRAY_SEARCHES = /* @__PURE__ */ new Set(["indexOf", "lastIndexOf", "includes"]);
295
+ var NOT_SEARCHED = /* @__PURE__ */ Symbol("not searched");
163
296
  var HIGHER_ORDER_ARRAY_METHODS = /* @__PURE__ */ new Set([
164
297
  "map",
165
298
  "flatMap",
@@ -180,10 +313,12 @@ var FunctionProtoCall = Function.prototype.call;
180
313
  var FunctionProtoApply = Function.prototype.apply;
181
314
  var FunctionProtoBind = Function.prototype.bind;
182
315
  var FunctionProtoToString = Function.prototype.toString;
316
+ var ArrayProtoToLocaleString = Array.prototype.toLocaleString;
317
+ var StringProtoIndexOf = String.prototype.indexOf;
183
318
  function methodsOf(prototype) {
184
319
  const methods = /* @__PURE__ */ new Map();
185
320
  for (const name of Object.getOwnPropertyNames(prototype)) {
186
- if (name === "constructor") continue;
321
+ if (isBlockedKey(name)) continue;
187
322
  const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
188
323
  if (descriptor && typeof descriptor.value === "function") methods.set(descriptor.value, name);
189
324
  }
@@ -191,6 +326,34 @@ function methodsOf(prototype) {
191
326
  }
192
327
  var ARRAY_METHODS = methodsOf(Array.prototype);
193
328
  var STRING_METHODS = methodsOf(String.prototype);
329
+ var OTHER_METHODS = (() => {
330
+ const prototypes = [
331
+ ["Number", Number.prototype],
332
+ ["Boolean", Boolean.prototype],
333
+ ["BigInt", BigInt.prototype],
334
+ ["Date", Date.prototype],
335
+ ["Object", Object.prototype]
336
+ ];
337
+ const methods = /* @__PURE__ */ new Map();
338
+ for (const [kind, prototype] of prototypes) {
339
+ for (const [method, name] of methodsOf(prototype)) {
340
+ if (!methods.has(method)) methods.set(method, { kind, name });
341
+ }
342
+ }
343
+ return methods;
344
+ })();
345
+ var RECEIVERS = {
346
+ Number: { noun: "a number", accepts: (receiver) => typeof receiver === "number" },
347
+ Boolean: { noun: "a boolean", accepts: (receiver) => typeof receiver === "boolean" },
348
+ BigInt: { noun: "a BigInt", accepts: (receiver) => typeof receiver === "bigint" },
349
+ Date: { noun: "a date", accepts: (receiver) => receiver instanceof Date },
350
+ Object: {
351
+ noun: "an object",
352
+ accepts: (receiver, name) => name !== "valueOf" || receiver !== null && (typeof receiver === "object" || typeof receiver === "function")
353
+ }
354
+ };
355
+ var ARRAY_ITERATOR_NEXT = Object.getPrototypeOf([][Symbol.iterator]()).next;
356
+ var LIBRARY_FUNCTIONS = /* @__PURE__ */ new WeakSet();
194
357
  var ARRAY_DATA_ARGUMENTS = /* @__PURE__ */ new Map([
195
358
  ["push", () => true],
196
359
  ["unshift", () => true],
@@ -215,13 +378,18 @@ function convertsArguments(fn, count) {
215
378
  CONVERTED_ARGUMENTS.set(fn, count);
216
379
  return fn;
217
380
  }
381
+ var ARGUMENT_CONVERSIONS = /* @__PURE__ */ new WeakMap();
382
+ function convertsBeforeCall(fn, convert) {
383
+ ARGUMENT_CONVERSIONS.set(fn, convert);
384
+ return fn;
385
+ }
218
386
  var CALL_COSTS = /* @__PURE__ */ new WeakMap();
219
387
  function chargedBeforeCall(fn, cost) {
220
388
  CALL_COSTS.set(fn, cost);
221
389
  return fn;
222
390
  }
223
391
  function newTextMeasure() {
224
- return { length: 0, items: 0, active: /* @__PURE__ */ new Set(), functions: /* @__PURE__ */ new Map() };
392
+ return { length: 0, items: 0, active: /* @__PURE__ */ new Set(), functions: /* @__PURE__ */ new Map(), work: 0 };
225
393
  }
226
394
  function scalarTextLength(item, measure) {
227
395
  switch (typeof item) {
@@ -229,8 +397,11 @@ function scalarTextLength(item, measure) {
229
397
  case "boolean":
230
398
  return 32;
231
399
  // also covers a number in the longest locale format
232
- case "bigint":
233
- return String(item).length;
400
+ case "bigint": {
401
+ const bits = bitsOf(item);
402
+ if (bits > WORD_BITS) measure.work += bits * BIGINT_TEXT_WORK;
403
+ return Math.ceil(bits * Math.log10(2)) + 2;
404
+ }
234
405
  case "function": {
235
406
  let length = measure.functions.get(item);
236
407
  if (length === void 0) {
@@ -294,6 +465,7 @@ function assertArrayTextWithinLimit(...values) {
294
465
  measureArrayText(value, 1, measure, 0);
295
466
  if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
296
467
  }
468
+ return measure?.length ?? 0;
297
469
  }
298
470
  var StepLimitError = class extends Error {
299
471
  constructor(limit) {
@@ -301,17 +473,34 @@ var StepLimitError = class extends Error {
301
473
  this.name = "StepLimitError";
302
474
  }
303
475
  };
476
+ var DeadlineError = class extends Error {
477
+ constructor() {
478
+ super("Execution deadline exceeded");
479
+ this.name = "TimeoutError";
480
+ }
481
+ };
304
482
  var InterpreterError = class extends Error {
305
483
  constructor(message) {
306
484
  super(message);
307
485
  this.name = "InterpreterError";
308
486
  }
309
487
  };
488
+ var AccumulatedText = class {
489
+ constructor(value, owed) {
490
+ this.value = value;
491
+ this.owed = owed;
492
+ }
493
+ };
310
494
  var ReturnSignal = class {
311
495
  constructor(value) {
312
496
  this.value = value;
313
497
  }
314
498
  };
499
+ var ScriptThrown = class {
500
+ constructor(value) {
501
+ this.value = value;
502
+ }
503
+ };
315
504
  var BreakSignal = class {
316
505
  };
317
506
  var ContinueSignal = class {
@@ -327,12 +516,11 @@ function createScriptError(name, message, code) {
327
516
  error["name"] = name;
328
517
  error["message"] = message;
329
518
  if (code !== void 0) error["code"] = code;
330
- Object.defineProperty(error, "toString", {
331
- value: function toString() {
332
- return message ? `${name}: ${message}` : name;
333
- },
334
- enumerable: false
335
- });
519
+ const toString = function toString2() {
520
+ return message ? `${name}: ${message}` : name;
521
+ };
522
+ LIBRARY_FUNCTIONS.add(toString);
523
+ Object.defineProperty(error, "toString", { value: toString, enumerable: false });
336
524
  SCRIPT_ERRORS.add(error);
337
525
  return Object.freeze(error);
338
526
  }
@@ -340,9 +528,10 @@ function isScriptError(value) {
340
528
  return typeof value === "object" && value !== null && SCRIPT_ERRORS.has(value);
341
529
  }
342
530
  var Scope = class _Scope {
343
- constructor(parent, depth) {
531
+ constructor(parent, depth, settle) {
344
532
  this.parent = parent;
345
533
  this.depth = depth ?? parent?.depth ?? 0;
534
+ this.settle = settle ?? parent?.settle ?? (() => void 0);
346
535
  }
347
536
  vars = /* @__PURE__ */ new Map();
348
537
  /**
@@ -350,39 +539,69 @@ var Scope = class _Scope {
350
539
  * function one more than where it was called from. A block inside has the depth around it.
351
540
  */
352
541
  depth;
542
+ /** Charges what is still owed for the value of a variable that is read */
543
+ settle;
544
+ /**
545
+ * In the body of a callback that `reduce` called with a text: the name of the parameter that
546
+ * holds it. A block inside has the name around it; a function inside does not.
547
+ */
548
+ accumulator;
353
549
  child() {
354
- return new _Scope(this);
550
+ const scope = new _Scope(this);
551
+ scope.accumulator = this.accumulator;
552
+ return scope;
355
553
  }
356
554
  /** The scope of one call of a function defined in this scope, running `depth` calls deep. */
357
555
  activation(depth) {
358
556
  return new _Scope(this, depth);
359
557
  }
360
558
  declare(name, value, mutable) {
361
- this.vars.set(name, { value, mutable });
559
+ this.vars.set(name, { value, mutable, owed: 0 });
362
560
  }
363
561
  has(name) {
364
562
  return this.vars.has(name) || (this.parent?.has(name) ?? false);
365
563
  }
564
+ /**
565
+ * The variable as it is stored, or nothing when there is none. For the few readers that
566
+ * neither keep its value nor look into a text (its length, whether it is empty, appending to
567
+ * it): everything else reads through {@link get}.
568
+ */
569
+ slot(name) {
570
+ return this.vars.get(name) ?? this.parent?.slot(name);
571
+ }
572
+ /** The value of a variable, for any use: what is still owed for it is charged first. */
366
573
  get(name) {
367
- const slot = this.vars.get(name);
368
- if (slot) return slot.value;
369
- if (this.parent) return this.parent.get(name);
370
- throw new InterpreterError(`'${name}' is not defined`);
574
+ const slot = this.slot(name);
575
+ if (!slot) throw new InterpreterError(`'${name}' is not defined`);
576
+ if (slot.owed > 0) {
577
+ const owed = slot.owed;
578
+ slot.owed = 0;
579
+ this.settle(owed);
580
+ }
581
+ return slot.value;
371
582
  }
372
583
  set(name, value) {
373
- const slot = this.vars.get(name);
374
- if (slot) {
375
- if (!slot.mutable) throw new InterpreterError(`Assignment to constant '${name}'`);
376
- slot.value = value;
377
- return;
378
- }
379
- if (this.parent) {
380
- this.parent.set(name, value);
381
- return;
382
- }
383
- throw new InterpreterError(`'${name}' is not defined`);
584
+ this.append(name, value, 0);
585
+ }
586
+ /** Assign a variable a text that was appended to its value, with what a reader still owes for it. */
587
+ append(name, value, owed) {
588
+ const slot = this.slot(name);
589
+ if (!slot) throw new InterpreterError(`'${name}' is not defined`);
590
+ if (!slot.mutable) throw new InterpreterError(`Assignment to constant '${name}'`);
591
+ slot.value = value;
592
+ slot.owed = owed;
384
593
  }
385
594
  };
595
+ function appendedTo(name, node) {
596
+ const operands = [];
597
+ let first = node;
598
+ while (first.type === "BinaryExpression" && first.operator === "+") {
599
+ operands.push(first.right);
600
+ first = first.left;
601
+ }
602
+ if (operands.length === 0 || first.type !== "Identifier" || first.name !== name) return void 0;
603
+ return operands.reverse();
604
+ }
386
605
  var DEFAULT_MAX_PENDING_CALLS = 4096;
387
606
  function ignoreRejection2() {
388
607
  }
@@ -391,6 +610,7 @@ var Interpreter = class {
391
610
  this.options = options;
392
611
  this.globals = options.globals;
393
612
  this.maxPendingCalls = options.maxPendingCalls ?? DEFAULT_MAX_PENDING_CALLS;
613
+ this.provide(this.globals, 2);
394
614
  }
395
615
  steps = 0;
396
616
  /** Calls that have not returned: the running ones and the ones waiting on an `await` */
@@ -406,50 +626,101 @@ var Interpreter = class {
406
626
  callerDepth = 0;
407
627
  maxPendingCalls;
408
628
  globals;
409
- /** The error that ended the run (step budget, abort, allocation budget); set once, never caught */
629
+ /**
630
+ * What is owed for the text `reduce` is handing to its callback, for that function to read as
631
+ * it starts (in the same synchronous step, like {@link callerDepth}); otherwise nothing.
632
+ */
633
+ accumulatorOwed;
634
+ /** The step count at which the clock is read next */
635
+ nextClockCheck = CLOCK_CHECK_STEPS;
636
+ /** What built-ins worked through that has not made a full step yet (see {@link work}) */
637
+ workDone = 0;
638
+ /** The error that ended the run (step budget, deadline, abort, allocation budget); set once, never caught */
410
639
  fatal;
411
640
  interpretedFunctions = /* @__PURE__ */ new WeakSet();
641
+ /** The functions the host provides: the globals, their members, and what `bind` made of them */
642
+ provided = /* @__PURE__ */ new WeakSet();
412
643
  errorCopies = /* @__PURE__ */ new WeakMap();
644
+ /** BigInt literals of the program that were found to be within the size a BigInt may have */
645
+ checkedLiterals = /* @__PURE__ */ new WeakSet();
646
+ /**
647
+ * Remember the functions among the properties of `holder`, `depth` levels down: a global
648
+ * (`parseInt`) or a member of one (`Math.max`, a method of a tool namespace). Read from the
649
+ * property itself, so that nothing of the host runs for it. An array holds data.
650
+ */
651
+ provide(holder, depth) {
652
+ if (holder === null || typeof holder !== "object" && typeof holder !== "function" || Array.isArray(holder))
653
+ return;
654
+ for (const name of Object.getOwnPropertyNames(holder)) {
655
+ const descriptor = Object.getOwnPropertyDescriptor(holder, name);
656
+ if (!descriptor || !("value" in descriptor)) continue;
657
+ const value = descriptor.value;
658
+ if (typeof value === "function") this.provided.add(value);
659
+ if (depth > 1) this.provide(value, depth - 1);
660
+ }
661
+ }
413
662
  /**
414
663
  * Call a function for a script, with the checks that apply to a call the script writes itself.
415
664
  * For a host helper that is handed a callback (`parallel(items, fn)`): `fn` may be a function
416
665
  * of the script, or a built-in or host function the script passed along.
417
666
  */
418
- call(fn, args) {
419
- if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
420
- if (this.interpretedFunctions.has(fn)) return fn(...args);
421
- return this.callFunction(fn, void 0, args, this.callerDepth);
667
+ async call(fn, args) {
668
+ try {
669
+ if (this.fatal !== void 0) throw this.fatal;
670
+ if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
671
+ if (this.interpretedFunctions.has(fn)) return await fn(...args);
672
+ return await this.callFunction(fn, void 0, args, this.callerDepth);
673
+ } catch (thrown) {
674
+ if (thrown instanceof ScriptThrown) throw thrown.value;
675
+ if (!(thrown instanceof Error)) throw new InterpreterError("Host operation failed");
676
+ throw thrown;
677
+ }
422
678
  }
423
679
  /** Number of AST nodes evaluated so far (for execution stats). */
424
680
  get stepCount() {
425
681
  return this.steps;
426
682
  }
427
683
  async run(program) {
428
- const root = new Scope();
429
- for (const stmt of program.body) {
430
- if (stmt.type === "FunctionDeclaration" && stmt.id) {
431
- root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
684
+ try {
685
+ const root = new Scope(void 0, 0, (bytes) => this.charge(bytes));
686
+ for (const stmt of program.body) {
687
+ if (stmt.type === "FunctionDeclaration" && stmt.id) {
688
+ root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
689
+ }
432
690
  }
691
+ let last;
692
+ for (const stmt of program.body) {
693
+ if (stmt.type === "FunctionDeclaration") continue;
694
+ last = await this.execStatement(stmt, root);
695
+ }
696
+ if (root.has("__ag_main")) {
697
+ const main = root.get("__ag_main");
698
+ if (typeof main === "function") return await main();
699
+ }
700
+ return last;
701
+ } catch (thrown) {
702
+ if (thrown instanceof ScriptThrown) throw thrown.value;
703
+ throw thrown;
433
704
  }
434
- let last;
435
- for (const stmt of program.body) {
436
- if (stmt.type === "FunctionDeclaration") continue;
437
- last = await this.execStatement(stmt, root);
438
- }
439
- if (root.has("__ag_main")) {
440
- const main = root.get("__ag_main");
441
- if (typeof main === "function") return main();
442
- }
443
- return last;
444
705
  }
445
706
  /**
446
- * End the run from outside: whatever of the script is still going (a function a built-in
447
- * started and nobody awaited, a callback waiting for a tool call) stops at its next step. The
448
- * host calls this when the execution has returned, so that no script code runs after it.
707
+ * End the run from outside: whatever of the script is still going (a callback waiting for a
708
+ * tool call, a run that timed out while it waited) stops at its next step or its next call,
709
+ * whichever comes first. The host calls this when the execution has returned, so that no
710
+ * script code runs and no host function is called after it.
449
711
  */
450
712
  stop() {
451
713
  if (this.fatal === void 0) this.fatal = new InterpreterError("Execution ended");
452
714
  }
715
+ /**
716
+ * Charge an allocation that a runtime helper of the host made for the script (the helpers a
717
+ * transformed `+` or template literal calls). The budget is one budget wherever it is asked:
718
+ * a refusal ends the run here as it does for what the interpreter charges itself, and no
719
+ * `catch` or `finally` of the script runs after it.
720
+ */
721
+ chargeAllocation(bytes) {
722
+ this.charge(bytes);
723
+ }
453
724
  /** End the run with an error no `catch` of the script can stop. */
454
725
  end(error) {
455
726
  if (this.fatal === void 0) this.fatal = error;
@@ -459,6 +730,90 @@ var Interpreter = class {
459
730
  if (this.fatal !== void 0) throw this.fatal;
460
731
  if (this.options.signal?.aborted) this.end(new InterpreterError("Execution aborted"));
461
732
  if (++this.steps > this.options.maxSteps) this.end(new StepLimitError(this.options.maxSteps));
733
+ if (this.steps >= this.nextClockCheck) this.checkClock();
734
+ }
735
+ /** End the run when its deadline has passed. */
736
+ checkClock() {
737
+ this.nextClockCheck = this.steps + CLOCK_CHECK_STEPS;
738
+ const deadline = this.options.deadline;
739
+ if (deadline !== void 0 && Date.now() >= deadline) this.end(new DeadlineError());
740
+ }
741
+ /**
742
+ * Count what a built-in works through for the script, in chars or items: the engine does it
743
+ * in one step of its own, however large the operands are. {@link WORK_PER_STEP} units are a
744
+ * step of the budget, and the clock is read whenever that adds a step.
745
+ */
746
+ work(units) {
747
+ if (!(units > 0)) return;
748
+ this.workDone += units;
749
+ if (this.workDone < WORK_PER_STEP) return;
750
+ const steps = Math.floor(this.workDone / WORK_PER_STEP);
751
+ this.workDone -= steps * WORK_PER_STEP;
752
+ this.steps += steps;
753
+ if (this.steps > this.options.maxSteps) this.end(new StepLimitError(this.options.maxSteps));
754
+ this.checkClock();
755
+ }
756
+ /** {@link assertArrayTextWithinLimit}, and the text the arrays are written as counted as work. */
757
+ arrayOperands(...values) {
758
+ let measure;
759
+ for (const value of values) {
760
+ if (!Array.isArray(value)) continue;
761
+ measure ??= newTextMeasure();
762
+ measureArrayText(value, 1, measure, 0);
763
+ if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
764
+ }
765
+ if (measure) this.work(measure.length * WRITE_WORK + measure.work);
766
+ }
767
+ /**
768
+ * Count a BigInt an operation made: it is held to the size a BigInt may have, and beyond the
769
+ * size of a number what it holds is charged to the budget and making it counts as work. Also
770
+ * for the runtime helper that adds for a transformed `+`.
771
+ *
772
+ * @throws InterpreterError when the value is larger than {@link MAX_BIGINT_BITS}
773
+ */
774
+ countBigInt(value) {
775
+ const bits = bitsOf(value);
776
+ if (bits > MAX_BIGINT_BITS) throw bigIntTooLarge();
777
+ if (bits <= WORD_BITS) return;
778
+ this.work(bits * BIGINT_WORK);
779
+ this.charge(Math.ceil(bits / 8));
780
+ }
781
+ /** Count the work of writing a value as text, when it is a BigInt: the engine writes it in decimal. */
782
+ bigIntAsText(value) {
783
+ if (typeof value !== "bigint") return;
784
+ const bits = bitsOf(value);
785
+ if (bits > WORD_BITS) this.work(bits * BIGINT_TEXT_WORK);
786
+ }
787
+ /**
788
+ * What is checked before an operator is applied to a BigInt: the operations whose result can
789
+ * be far larger than their operands are refused from the operands, and what the engine reads
790
+ * to compare a BigInt with a text is bounded and counted.
791
+ */
792
+ checkBigIntOperands(operator, left, right) {
793
+ if (typeof left === "bigint" && typeof right === "bigint") {
794
+ if (operator === "<<" || operator === ">>") {
795
+ const count = Number(operator === "<<" ? right : -right);
796
+ if (count > 0 && left !== 0n && bitsOf(left) + count > MAX_BIGINT_BITS) throw bigIntTooLarge();
797
+ } else if (operator === "**") {
798
+ const bits = bitsOf(left);
799
+ if (bits > 1 && (bits - 1) * Number(right) + 1 > MAX_BIGINT_BITS) throw bigIntTooLarge();
800
+ } else if (operator === "/" || operator === "%") {
801
+ const bits = bitsOf(left);
802
+ if (bits > WORD_BITS) this.work(bits * BIGINT_WORK);
803
+ }
804
+ return;
805
+ }
806
+ const other = typeof left === "bigint" ? right : left;
807
+ if (COMPARISONS.has(operator)) {
808
+ const chars = typeof other === "string" ? other.length : assertArrayTextWithinLimit(other);
809
+ if (chars > MAX_BIGINT_DIGITS) {
810
+ throw new InterpreterError(`A BigInt cannot be compared with a text of more than ${MAX_BIGINT_DIGITS} chars`);
811
+ }
812
+ this.work(chars * BIGINT_TEXT_WORK);
813
+ } else if (operator === "+") {
814
+ this.bigIntAsText(left);
815
+ this.bigIntAsText(right);
816
+ }
462
817
  }
463
818
  /** Charge an allocation to the host's budget. */
464
819
  charge(bytes) {
@@ -490,12 +845,19 @@ var Interpreter = class {
490
845
  case "FunctionDeclaration":
491
846
  if (node.id) scope.declare(node.id.name, this.makeFunction(node, scope), false);
492
847
  return void 0;
493
- case "ExpressionStatement":
494
- return this.evalExpr(node.expression, scope);
848
+ case "ExpressionStatement": {
849
+ const expression = node.expression;
850
+ if (expression.type === "AssignmentExpression" && expression.left.type === "Identifier") {
851
+ const name = expression.left.name;
852
+ const appended = expression.operator === "+=" ? [expression.right] : expression.operator === "=" ? appendedTo(name, expression.right) : void 0;
853
+ if (appended !== void 0 && scope.has(name)) return this.execAppend(name, appended, scope);
854
+ }
855
+ return this.evalExpr(expression, scope);
856
+ }
495
857
  case "BlockStatement":
496
858
  return this.execBlock(node.body, scope.child());
497
859
  case "IfStatement":
498
- if (truthy(await this.evalExpr(node.test, scope))) return this.execStatement(node.consequent, scope);
860
+ if (await this.evalTest(node.test, scope)) return this.execStatement(node.consequent, scope);
499
861
  if (node.alternate) return this.execStatement(node.alternate, scope);
500
862
  return void 0;
501
863
  case "ForOfStatement":
@@ -513,9 +875,9 @@ var Interpreter = class {
513
875
  case "TryStatement":
514
876
  return this.execTry(node, scope);
515
877
  case "ThrowStatement":
516
- throw await this.evalExpr(node.argument, scope);
878
+ throw new ScriptThrown(await this.evalExpr(node.argument, scope));
517
879
  case "ReturnStatement":
518
- throw new ReturnSignal(node.argument ? await this.evalExpr(node.argument, scope) : void 0);
880
+ throw new ReturnSignal(node.argument ? await this.evalReturned(node.argument, scope) : void 0);
519
881
  case "BreakStatement":
520
882
  if (node.label) throw new InterpreterError("Labeled break is not supported");
521
883
  throw new BreakSignal();
@@ -586,14 +948,14 @@ var Interpreter = class {
586
948
  if (node.init.type === "VariableDeclaration") await this.execStatement(node.init, inner);
587
949
  else await this.evalExpr(node.init, inner);
588
950
  }
589
- while (node.test ? truthy(await this.evalExpr(node.test, inner)) : true) {
951
+ while (node.test ? await this.evalTest(node.test, inner) : true) {
590
952
  this.tick();
591
953
  if (!await this.runLoopBody(node.body, inner.child())) break;
592
954
  if (node.update) await this.evalExpr(node.update, inner);
593
955
  }
594
956
  }
595
957
  async execWhile(node, scope) {
596
- while (truthy(await this.evalExpr(node.test, scope))) {
958
+ while (await this.evalTest(node.test, scope)) {
597
959
  this.tick();
598
960
  if (!await this.runLoopBody(node.body, scope.child())) break;
599
961
  }
@@ -602,7 +964,7 @@ var Interpreter = class {
602
964
  do {
603
965
  this.tick();
604
966
  if (!await this.runLoopBody(node.body, scope.child())) break;
605
- } while (truthy(await this.evalExpr(node.test, scope)));
967
+ } while (await this.evalTest(node.test, scope));
606
968
  }
607
969
  async execSwitch(node, scope) {
608
970
  const value = await this.evalExpr(node.discriminant, scope);
@@ -635,12 +997,12 @@ var Interpreter = class {
635
997
  }
636
998
  }
637
999
  /**
638
- * What a `catch` clause receives. A value the script threw is its own. A host Error (a refusal
639
- * by the interpreter, a failed tool call, a TypeError of a built-in) is replaced by a plain
640
- * copy with its name, message and code.
1000
+ * What a `catch` clause receives. A value the script threw is its own. A host Error is copied
1001
+ * with its name, message and code; every other host rejection reason becomes a generic error.
641
1002
  */
642
1003
  toScriptValue(thrown) {
643
- if (!(thrown instanceof Error)) return thrown;
1004
+ if (thrown instanceof ScriptThrown) return thrown.value;
1005
+ if (!(thrown instanceof Error)) return createScriptError("Error", "Host operation failed");
644
1006
  const known = this.errorCopies.get(thrown);
645
1007
  if (known) return known;
646
1008
  const code = thrown.code;
@@ -660,6 +1022,10 @@ var Interpreter = class {
660
1022
  if (node.regex) {
661
1023
  throw new InterpreterError("Regular expressions are not supported");
662
1024
  }
1025
+ if (typeof node.value === "bigint" && !this.checkedLiterals.has(node)) {
1026
+ if (bitsOf(node.value) > MAX_BIGINT_BITS) throw bigIntTooLarge();
1027
+ this.checkedLiterals.add(node);
1028
+ }
663
1029
  return node.value;
664
1030
  case "Identifier":
665
1031
  return scope.has(node.name) ? scope.get(node.name) : this.readGlobal(node.name);
@@ -689,6 +1055,7 @@ var Interpreter = class {
689
1055
  for (const [k, v] of Object.entries(spread)) {
690
1056
  this.tick();
691
1057
  if (!BLOCKED_KEYS.has(k)) {
1058
+ assertStorable(obj, k, v);
692
1059
  obj[k] = v;
693
1060
  count++;
694
1061
  }
@@ -699,7 +1066,9 @@ var Interpreter = class {
699
1066
  if (prop.kind !== "init") throw new InterpreterError("Getters and setters are not supported");
700
1067
  const key = await this.propKey(prop, scope);
701
1068
  if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property key: ${key}`);
702
- obj[key] = await this.evalExpr(prop.value, scope);
1069
+ const member = await this.evalExpr(prop.value, scope);
1070
+ assertStorable(obj, key, member);
1071
+ obj[key] = member;
703
1072
  count++;
704
1073
  }
705
1074
  this.charge(count * 16);
@@ -710,7 +1079,8 @@ var Interpreter = class {
710
1079
  case "UpdateExpression": {
711
1080
  const ref = await this.resolveReference(node.argument, scope);
712
1081
  const current = ref.get();
713
- assertArrayTextWithinLimit(current);
1082
+ this.arrayOperands(current);
1083
+ this.work(operandSize(current));
714
1084
  const before = Number(current);
715
1085
  const after = node.operator === "++" ? before + 1 : before - 1;
716
1086
  ref.set(after);
@@ -725,7 +1095,7 @@ var Interpreter = class {
725
1095
  return left ?? await this.evalExpr(node.right, scope);
726
1096
  }
727
1097
  case "ConditionalExpression":
728
- return truthy(await this.evalExpr(node.test, scope)) ? this.evalExpr(node.consequent, scope) : this.evalExpr(node.alternate, scope);
1098
+ return await this.evalTest(node.test, scope) ? this.evalExpr(node.consequent, scope) : this.evalExpr(node.alternate, scope);
729
1099
  case "SequenceExpression": {
730
1100
  let last;
731
1101
  for (const expression of node.expressions) last = await this.evalExpr(expression, scope);
@@ -757,17 +1127,107 @@ var Interpreter = class {
757
1127
  throw new InterpreterError(`Unsupported expression: ${node.type}`);
758
1128
  }
759
1129
  }
1130
+ /**
1131
+ * `s += x` or `s = s + x…` as a statement: append to a variable.
1132
+ *
1133
+ * The engine does not copy a text to append to it: the new text links to the old one, and is
1134
+ * written out as a text of its own when something first looks into it. A loop that appends to
1135
+ * one variable therefore allocates what it appends, and is charged that. What is not charged
1136
+ * yet, the length of the text that was appended to, stays owed on the variable: it is paid by
1137
+ * the first read that could look into the new text or keep it (`Scope.get`), because from then
1138
+ * on it can exist as a full copy next to the texts it was built from. Nothing else can get
1139
+ * hold of the new text: as a statement, the assignment has no value.
1140
+ */
1141
+ async execAppend(name, operands, scope) {
1142
+ this.tick();
1143
+ const { sum, owed } = await this.appendTo(name, operands, scope);
1144
+ scope.append(name, sum, owed);
1145
+ return sum;
1146
+ }
1147
+ /**
1148
+ * The value of the variable `name` with the operands appended, charged for what is appended.
1149
+ *
1150
+ * @returns The sum, and what is still owed for it when it is a text that was appended to a text
1151
+ */
1152
+ async appendTo(name, operands, scope) {
1153
+ const variable = scope.slot(name);
1154
+ if (!variable) throw new InterpreterError(`'${name}' is not defined`);
1155
+ const start = variable.value;
1156
+ const owedAtStart = variable.owed;
1157
+ let sum = start;
1158
+ for (const operand of operands) {
1159
+ this.tick();
1160
+ const right = await this.evalExpr(operand, scope);
1161
+ const left = sum;
1162
+ sum = this.binary("+", left, right, true);
1163
+ if (typeof sum === "string") this.charge((sum.length - (typeof left === "string" ? left.length : 0)) * 2);
1164
+ }
1165
+ let owed = 0;
1166
+ if (typeof sum === "string" && typeof start === "string") {
1167
+ owed = owedAtStart > 0 && variable.owed === owedAtStart ? owedAtStart : start.length * 2;
1168
+ }
1169
+ return { sum, owed };
1170
+ }
1171
+ /**
1172
+ * The value a function returns. In a callback that `reduce` called with a text, the
1173
+ * accumulator itself and what is appended to it (`return text + item`) are returned as an
1174
+ * {@link AccumulatedText}, without paying what is owed for them: `reduce` carries it on.
1175
+ */
1176
+ async evalReturned(node, scope) {
1177
+ const name = scope.accumulator;
1178
+ if (name === void 0) return this.evalExpr(node, scope);
1179
+ if (node.type === "ConditionalExpression") {
1180
+ this.tick();
1181
+ const branch = await this.evalTest(node.test, scope) ? node.consequent : node.alternate;
1182
+ return this.evalReturned(branch, scope);
1183
+ }
1184
+ if (node.type === "Identifier" && node.name === name) {
1185
+ const variable = scope.slot(name);
1186
+ if (variable !== void 0 && typeof variable.value === "string") {
1187
+ this.tick();
1188
+ return new AccumulatedText(variable.value, variable.owed);
1189
+ }
1190
+ } else {
1191
+ const appended = appendedTo(name, node);
1192
+ if (appended !== void 0 && scope.has(name)) {
1193
+ this.tick();
1194
+ const { sum, owed } = await this.appendTo(name, appended, scope);
1195
+ return typeof sum === "string" ? new AccumulatedText(sum, owed) : sum;
1196
+ }
1197
+ }
1198
+ return this.evalExpr(node, scope);
1199
+ }
1200
+ /**
1201
+ * The variable an identifier names when it holds an appended text that is still owed for.
1202
+ * For the readers that learn nothing but its length or that it is a text.
1203
+ */
1204
+ appendedText(node, scope) {
1205
+ if (node.type !== "Identifier") return void 0;
1206
+ const variable = scope.slot(node.name);
1207
+ return variable !== void 0 && variable.owed > 0 && typeof variable.value === "string" ? variable.value : void 0;
1208
+ }
1209
+ /** Evaluate a condition. Whether a text is empty is known from its length. */
1210
+ async evalTest(node, scope) {
1211
+ const text = this.appendedText(node, scope);
1212
+ if (text !== void 0) {
1213
+ this.tick();
1214
+ return text.length > 0;
1215
+ }
1216
+ return truthy(await this.evalExpr(node, scope));
1217
+ }
760
1218
  async evalTemplate(node, scope) {
761
1219
  let out = "";
762
1220
  for (let i = 0; i < node.quasis.length; i++) {
763
1221
  out += node.quasis[i].value.cooked ?? "";
764
1222
  if (i < node.expressions.length) {
765
1223
  const value = await this.evalExpr(node.expressions[i], scope);
766
- assertArrayTextWithinLimit(value);
1224
+ this.arrayOperands(value);
1225
+ this.bigIntAsText(value);
767
1226
  out += String(value);
768
1227
  if (out.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
769
1228
  }
770
1229
  }
1230
+ this.work(out.length * WRITE_WORK);
771
1231
  this.charge(out.length * 2);
772
1232
  return out;
773
1233
  }
@@ -782,37 +1242,67 @@ var Interpreter = class {
782
1242
  assertKeyAllowed(key);
783
1243
  return delete object[key];
784
1244
  }
1245
+ if (node.operator === "!" || node.operator === "typeof") {
1246
+ const text = this.appendedText(node.argument, scope);
1247
+ if (text !== void 0) {
1248
+ this.tick();
1249
+ return node.operator === "!" ? text.length === 0 : "string";
1250
+ }
1251
+ }
785
1252
  const v = await this.evalExpr(node.argument, scope);
786
1253
  switch (node.operator) {
787
1254
  case "!":
788
1255
  return !truthy(v);
789
- case "-":
790
- assertArrayTextWithinLimit(v);
791
- return -v;
1256
+ case "-": {
1257
+ this.numericOperand(v);
1258
+ const negated = -v;
1259
+ if (typeof negated === "bigint") this.countBigInt(negated);
1260
+ return negated;
1261
+ }
792
1262
  case "+":
793
- assertArrayTextWithinLimit(v);
1263
+ this.numericOperand(v);
794
1264
  return +v;
795
1265
  case "typeof":
796
1266
  return typeof v;
797
- case "~":
798
- assertArrayTextWithinLimit(v);
799
- return ~v;
1267
+ case "~": {
1268
+ this.numericOperand(v);
1269
+ const inverted = ~v;
1270
+ if (typeof inverted === "bigint") this.countBigInt(inverted);
1271
+ return inverted;
1272
+ }
800
1273
  case "void":
801
1274
  return void 0;
802
1275
  default:
803
1276
  throw new InterpreterError(`Unsupported unary operator: ${node.operator}`);
804
1277
  }
805
1278
  }
1279
+ /** An operand the engine reads a number from: an array is joined first, a text is read through. */
1280
+ numericOperand(value) {
1281
+ this.arrayOperands(value);
1282
+ this.work(operandSize(value));
1283
+ }
806
1284
  async evalBinary(node, scope) {
807
1285
  if (node.left.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
1286
+ if (node.operator === "+") return this.evalSum(node, scope);
1287
+ if (node.operator === "===" || node.operator === "!==") {
1288
+ const literal = node.left.type === "Literal" ? node.left : node.right.type === "Literal" ? node.right : void 0;
1289
+ const text = this.appendedText(literal === node.left ? node.right : node.left, scope);
1290
+ if (literal !== void 0 && text !== void 0 && !literal.regex) {
1291
+ const value = literal.value;
1292
+ if (typeof value !== "string" || value.length !== text.length) {
1293
+ this.tick();
1294
+ this.tick();
1295
+ return node.operator === "!==";
1296
+ }
1297
+ }
1298
+ }
808
1299
  const l = await this.evalExpr(node.left, scope);
809
1300
  const r = await this.evalExpr(node.right, scope);
810
1301
  if (node.operator === "in") {
811
1302
  if (r === null || typeof r !== "object" && typeof r !== "function") {
812
1303
  throw new InterpreterError("Cannot use 'in' on a value that is not an object");
813
1304
  }
814
- assertArrayTextWithinLimit(l);
815
- const key = String(l);
1305
+ const key = this.keyText(l);
816
1306
  if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
817
1307
  return key in r;
818
1308
  }
@@ -823,15 +1313,56 @@ var Interpreter = class {
823
1313
  }
824
1314
  return this.binary(node.operator, l, r);
825
1315
  }
826
- /** Apply a binary operator to two values. */
827
- binary(operator, left, right) {
828
- if (operator !== "===" && operator !== "!==") assertArrayTextWithinLimit(left, right);
1316
+ /**
1317
+ * `a + b + c`: the operands from left to right, and one sum after the other. Only the last
1318
+ * sum is a value the script gets hold of, and it is charged in full; the ones before it are
1319
+ * part of it.
1320
+ */
1321
+ async evalSum(node, scope) {
1322
+ const operands = [];
1323
+ let first = node;
1324
+ while (first.type === "BinaryExpression" && first.operator === "+") {
1325
+ operands.push(first.right);
1326
+ first = first.left;
1327
+ }
1328
+ if (first.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
1329
+ let sum = await this.evalExpr(first, scope);
1330
+ for (let i = operands.length - 1; i >= 0; i--) {
1331
+ if (i < operands.length - 1) this.tick();
1332
+ const right = await this.evalExpr(operands[i], scope);
1333
+ sum = this.binary("+", sum, right, i > 0);
1334
+ }
1335
+ return sum;
1336
+ }
1337
+ /**
1338
+ * Apply a binary operator to two values.
1339
+ *
1340
+ * @param partOfSum - The result of `+` is an operand of the next `+` and nothing else: the
1341
+ * caller charges for the text that comes of it
1342
+ */
1343
+ binary(operator, left, right, partOfSum = false) {
1344
+ if (typeof left !== "bigint" && typeof right !== "bigint") return this.operate(operator, left, right, partOfSum);
1345
+ this.checkBigIntOperands(operator, left, right);
1346
+ const result = this.operate(operator, left, right, partOfSum);
1347
+ if (typeof result === "bigint") this.countBigInt(result);
1348
+ return result;
1349
+ }
1350
+ operate(operator, left, right, partOfSum) {
1351
+ const strict = operator === "===" || operator === "!==";
1352
+ const loose = operator === "==" || operator === "!=";
1353
+ const convertsNextTo = (other) => !strict && (!loose || other !== null && other !== void 0 && typeof other !== "object" && typeof other !== "function");
1354
+ this.arrayOperands(convertsNextTo(right) ? left : void 0, convertsNextTo(left) ? right : void 0);
1355
+ if (operator !== "+") {
1356
+ if (typeof left === "string" && typeof right === "string") this.work(Math.min(left.length, right.length));
1357
+ else if (typeof left === "string" && convertsNextTo(right)) this.work(left.length);
1358
+ else if (typeof right === "string" && convertsNextTo(left)) this.work(right.length);
1359
+ }
829
1360
  const l = left;
830
1361
  const r = right;
831
1362
  switch (operator) {
832
1363
  case "+": {
833
1364
  const sum = l + r;
834
- if (typeof sum === "string") this.charge((sum.length - (typeof left === "string" ? left.length : 0)) * 2);
1365
+ if (typeof sum === "string" && !partOfSum) this.charge(sum.length * 2);
835
1366
  return sum;
836
1367
  }
837
1368
  case "-":
@@ -882,6 +1413,11 @@ var Interpreter = class {
882
1413
  */
883
1414
  async evalMemberTarget(node, scope) {
884
1415
  if (node.object.type === "Super") throw new InterpreterError("super is not supported");
1416
+ const text = !node.computed && node.property.type === "Identifier" && node.property.name === "length" ? this.appendedText(node.object, scope) : void 0;
1417
+ if (text !== void 0) {
1418
+ this.tick();
1419
+ return { object: text, key: "length" };
1420
+ }
885
1421
  const object = await this.evalExpr(node.object, scope);
886
1422
  if (node.optional && (object === null || object === void 0)) throw new ChainShortCircuit();
887
1423
  if (node.property.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
@@ -922,12 +1458,11 @@ var Interpreter = class {
922
1458
  writeMember(object, key, value) {
923
1459
  this.assertChangeable(object);
924
1460
  assertKeyAllowed(key);
1461
+ assertStorable(object, key, value);
925
1462
  if (Array.isArray(object)) {
926
- const grownTo = arrayLengthAfterWrite(object, key, value);
927
- if (grownTo > MAX_ARRAY_LENGTH) {
928
- throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
929
- }
930
- if (grownTo > object.length) this.charge((grownTo - object.length) * 8);
1463
+ const checked = checkArrayWrite(object, key, value);
1464
+ if (checked.length > object.length) this.charge((checked.length - object.length) * 8);
1465
+ value = checked.value;
931
1466
  }
932
1467
  object[key] = value;
933
1468
  }
@@ -956,7 +1491,10 @@ var Interpreter = class {
956
1491
  const construct = this.options.constructors?.get(callee);
957
1492
  if (!construct) throw new InterpreterError("new works with the built-in types the sandbox provides only");
958
1493
  const args = await this.evalArguments(node.arguments, scope);
959
- if (!ARRAY_DATA_FUNCTIONS.has(callee)) assertArrayTextWithinLimit(...args);
1494
+ if (!ARRAY_DATA_FUNCTIONS.has(callee)) {
1495
+ this.arrayOperands(...args);
1496
+ for (const arg of args) this.work(typeof arg === "string" ? arg.length : 0);
1497
+ }
960
1498
  const value = construct(args);
961
1499
  this.chargeValue(value);
962
1500
  return value;
@@ -991,6 +1529,7 @@ var Interpreter = class {
991
1529
  * @param depth - How many calls deep the code that makes this call runs
992
1530
  */
993
1531
  async callFunction(fn, thisArg, args, depth) {
1532
+ if (this.fatal !== void 0) throw this.fatal;
994
1533
  for (let hops = 0; fn === FunctionProtoCall || fn === FunctionProtoApply || fn === FunctionProtoBind; hops++) {
995
1534
  const name = fn === FunctionProtoCall ? "call" : fn === FunctionProtoApply ? "apply" : "bind";
996
1535
  if (typeof thisArg !== "function" || hops >= 8) {
@@ -1010,6 +1549,7 @@ var Interpreter = class {
1010
1549
  const interpreted = fn;
1011
1550
  return await this.withCallerDepth(depth, () => interpreted.apply(thisArg, args));
1012
1551
  }
1552
+ this.checkClock();
1013
1553
  const own = this.enterCall(depth);
1014
1554
  try {
1015
1555
  args = this.checkBuiltinCall(fn, thisArg, args);
@@ -1017,20 +1557,228 @@ var Interpreter = class {
1017
1557
  if (arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function") {
1018
1558
  return await this.callArrayMethod(thisArg, arrayMethod, args, own);
1019
1559
  }
1020
- const builtin = fn;
1021
- const builtinArgs = args;
1022
- const result = await this.withCallerDepth(own, () => builtin.apply(thisArg, builtinArgs));
1023
- if (arrayMethod === void 0 && STRING_METHODS.get(fn) === "split" && Array.isArray(result)) {
1560
+ if (arrayMethod === "toLocaleString") {
1561
+ const text = this.arrayLocaleText(thisArg, args, /* @__PURE__ */ new Set(), { length: 0 }, 0);
1562
+ this.chargeValue(text);
1563
+ return text;
1564
+ }
1565
+ const stringMethod = arrayMethod === void 0 ? STRING_METHODS.get(fn) : void 0;
1566
+ this.countRead(fn, arrayMethod, stringMethod, thisArg, args);
1567
+ let result = this.searchInPieces(arrayMethod, stringMethod, thisArg, args);
1568
+ if (result === NOT_SEARCHED) {
1569
+ const asIndex = stringMethod === "includes" && typeof thisArg === "string";
1570
+ const builtin = asIndex ? StringProtoIndexOf : fn;
1571
+ const builtinArgs = args;
1572
+ result = await this.withCallerDepth(own, () => builtin.apply(thisArg, builtinArgs));
1573
+ this.countSearched(arrayMethod, stringMethod, thisArg, args, result);
1574
+ if (asIndex) result = result !== -1;
1575
+ }
1576
+ if (stringMethod === "split" && Array.isArray(result)) {
1024
1577
  if (result.length > MAX_ARRAY_LENGTH) {
1025
1578
  throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
1026
1579
  }
1027
1580
  }
1581
+ this.work(typeof result === "string" ? result.length * WRITE_WORK : operandSize(result));
1028
1582
  this.chargeValue(result);
1029
1583
  return result;
1030
1584
  } finally {
1031
1585
  this.pendingCalls--;
1032
1586
  }
1033
1587
  }
1588
+ /**
1589
+ * Count what a built-in or host function reads before it is called: its receiver, where the
1590
+ * method goes through it (a search, a conversion, a copy; not a method that reads one char or
1591
+ * works at the end of an array), and the texts among the arguments it converts or searches
1592
+ * for. A value a function only keeps is not read: an item to push, the array a callback is
1593
+ * handed with every item. An array that is read as text was counted where it was measured,
1594
+ * and what the call makes is counted when it returns.
1595
+ */
1596
+ countRead(fn, arrayMethod, stringMethod, receiver, args) {
1597
+ let read = 0;
1598
+ if (typeof receiver === "string") {
1599
+ const counted = stringMethod === void 0 || !ARRAY_SEARCHES.has(stringMethod);
1600
+ if (counted && (stringMethod === void 0 || !CONSTANT_STRING_METHODS.has(stringMethod))) {
1601
+ read += receiver.length;
1602
+ }
1603
+ } else if (Array.isArray(receiver)) {
1604
+ const counted = arrayMethod !== "indexOf" && arrayMethod !== "lastIndexOf";
1605
+ if (counted && (arrayMethod === void 0 || !CONSTANT_ARRAY_METHODS.has(arrayMethod))) read += receiver.length;
1606
+ } else if (typeof receiver === "bigint") {
1607
+ this.bigIntAsText(receiver);
1608
+ }
1609
+ if (!ARRAY_DATA_FUNCTIONS.has(fn)) {
1610
+ const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
1611
+ const converted = CONVERTED_ARGUMENTS.get(fn) ?? args.length;
1612
+ for (let i = 0; i < args.length && i < converted; i++) {
1613
+ if (isData?.(i)) continue;
1614
+ const arg = args[i];
1615
+ if (typeof arg === "string") read += arg.length;
1616
+ else this.bigIntAsText(arg);
1617
+ }
1618
+ }
1619
+ if (stringMethod === "localeCompare" && typeof receiver === "string") {
1620
+ const other = args[0];
1621
+ read = Math.min(receiver.length, typeof other === "string" ? other.length : receiver.length) * LOCALE_COMPARE_WORK;
1622
+ }
1623
+ this.work(read);
1624
+ }
1625
+ /**
1626
+ * Count a search for a place by how far the engine went: from where it started to where it
1627
+ * found what it looked for, or to the end. A script that goes through a long text with
1628
+ * `indexOf(text, position)` pays for the text once, not once per call.
1629
+ *
1630
+ * @param index - What the engine answered: the place, or -1
1631
+ */
1632
+ countSearched(arrayMethod, stringMethod, receiver, args, index) {
1633
+ if (typeof index !== "number") return;
1634
+ const position = args[1];
1635
+ if (typeof receiver === "string" && stringMethod !== void 0 && ARRAY_SEARCHES.has(stringMethod)) {
1636
+ const length = receiver.length;
1637
+ if (stringMethod === "lastIndexOf") {
1638
+ const given = Number(position);
1639
+ const from = Number.isNaN(given) ? length : Math.min(Math.max(Math.trunc(given), 0), length);
1640
+ this.work(index === -1 ? from : from - index);
1641
+ } else {
1642
+ const from = Math.min(Math.max(integerOf(position), 0), length);
1643
+ this.work(index === -1 ? length - from : index - from);
1644
+ }
1645
+ } else if (Array.isArray(receiver) && (arrayMethod === "indexOf" || arrayMethod === "lastIndexOf")) {
1646
+ const length = receiver.length;
1647
+ if (arrayMethod === "lastIndexOf") {
1648
+ const given = args.length > 1 ? integerOf(position) : length - 1;
1649
+ const from = given >= 0 ? Math.min(given, length - 1) : length + given;
1650
+ this.work(index === -1 ? from + 1 : from - index);
1651
+ } else {
1652
+ const given = integerOf(position);
1653
+ const from = Math.min(given >= 0 ? given : Math.max(length + given, 0), length);
1654
+ this.work(index === -1 ? length - from : index - from);
1655
+ }
1656
+ }
1657
+ }
1658
+ /**
1659
+ * Make a search whose cost in the engine is the product of two lengths, piece by piece: a text
1660
+ * in a text (the engine can need a comparison of the whole pattern at every position of a
1661
+ * text that nearly matches everywhere), or a long text among the items of an array (every
1662
+ * item of the same length can be compared to its end). Between the pieces a step is counted
1663
+ * and the clock is read, so that one such call ends with the budget or the deadline like any
1664
+ * other code. The answer is the engine's.
1665
+ *
1666
+ * @returns The result, or {@link NOT_SEARCHED} for a call that is not such a search or small
1667
+ * enough to be one piece: the engine makes it
1668
+ */
1669
+ searchInPieces(arrayMethod, stringMethod, receiver, args) {
1670
+ const wanted = args[0];
1671
+ if (typeof wanted !== "string") return NOT_SEARCHED;
1672
+ const method = arrayMethod ?? stringMethod;
1673
+ if (typeof args[1] === "bigint" && method !== void 0 && ARRAY_SEARCHES.has(method)) return NOT_SEARCHED;
1674
+ if (stringMethod !== void 0 && typeof receiver === "string" && TEXT_SEARCHES.has(stringMethod)) {
1675
+ const small = receiver.length * wanted.length <= SEARCH_PIECE_WORK;
1676
+ if (small || wanted.length === 0 || wanted.length > receiver.length) return NOT_SEARCHED;
1677
+ return this.searchText(stringMethod, receiver, wanted, args);
1678
+ }
1679
+ if (arrayMethod !== void 0 && Array.isArray(receiver) && ARRAY_SEARCHES.has(arrayMethod)) {
1680
+ const small = receiver.length * wanted.length <= SEARCH_PIECE_WORK;
1681
+ if (small || wanted.length <= LONG_SEARCH_TEXT) return NOT_SEARCHED;
1682
+ return this.searchArray(arrayMethod, receiver, wanted, args);
1683
+ }
1684
+ return NOT_SEARCHED;
1685
+ }
1686
+ /** The first place at or after `from` where `pattern` starts in `text`, or -1. */
1687
+ findForward(text, pattern, from) {
1688
+ const last = text.length - pattern.length;
1689
+ const starts = Math.max(1, Math.floor(SEARCH_PIECE_WORK / pattern.length));
1690
+ for (let at = from; at <= last; at += starts) {
1691
+ if (at !== from) {
1692
+ this.tick();
1693
+ this.checkClock();
1694
+ }
1695
+ const end = Math.min(at + starts - 1, last) + pattern.length;
1696
+ const found = text.substring(at, end).indexOf(pattern);
1697
+ this.work(found === -1 ? end - at : found + pattern.length);
1698
+ if (found !== -1) return at + found;
1699
+ }
1700
+ return -1;
1701
+ }
1702
+ /** The last place at or before `from` where `pattern` starts in `text`, or -1. */
1703
+ findBackward(text, pattern, from) {
1704
+ const starts = Math.max(1, Math.floor(SEARCH_PIECE_WORK / pattern.length));
1705
+ for (let high = from; high >= 0; high -= starts) {
1706
+ if (high !== from) {
1707
+ this.tick();
1708
+ this.checkClock();
1709
+ }
1710
+ const low = Math.max(0, high - starts + 1);
1711
+ const end = high + pattern.length;
1712
+ const found = text.substring(low, end).lastIndexOf(pattern);
1713
+ this.work(found === -1 ? end - low : end - low - found);
1714
+ if (found !== -1) return low + found;
1715
+ }
1716
+ return -1;
1717
+ }
1718
+ /** `text.indexOf(pattern)` and the other searches for a text in a text, as the engine answers them. */
1719
+ searchText(name, text, pattern, args) {
1720
+ const length = text.length;
1721
+ const patternLength = pattern.length;
1722
+ switch (name) {
1723
+ case "indexOf":
1724
+ return this.findForward(text, pattern, Math.min(Math.max(integerOf(args[1]), 0), length));
1725
+ case "includes":
1726
+ return this.findForward(text, pattern, Math.min(Math.max(integerOf(args[1]), 0), length)) !== -1;
1727
+ case "lastIndexOf": {
1728
+ const position = Number(args[1]);
1729
+ const from = Number.isNaN(position) ? Number.POSITIVE_INFINITY : Math.trunc(position);
1730
+ return this.findBackward(text, pattern, Math.min(Math.max(from, 0), length - patternLength));
1731
+ }
1732
+ case "split": {
1733
+ const limit = args[1];
1734
+ const pieces = [];
1735
+ if (limit === 0) return pieces;
1736
+ let at = 0;
1737
+ for (let hit = this.findForward(text, pattern, 0); hit !== -1; hit = this.findForward(text, pattern, at)) {
1738
+ pieces.push(text.substring(at, hit));
1739
+ if (pieces.length >= limit) return pieces;
1740
+ at = hit + patternLength;
1741
+ }
1742
+ pieces.push(text.substring(at));
1743
+ return pieces;
1744
+ }
1745
+ default: {
1746
+ const replacement = String(args[1]);
1747
+ const parts = [];
1748
+ let at = 0;
1749
+ let hit = this.findForward(text, pattern, 0);
1750
+ while (hit !== -1) {
1751
+ parts.push(text.substring(at, hit), expandReplacement(replacement, text, hit, pattern));
1752
+ at = hit + patternLength;
1753
+ hit = name === "replace" ? -1 : this.findForward(text, pattern, at);
1754
+ }
1755
+ parts.push(text.substring(at));
1756
+ return parts.join("");
1757
+ }
1758
+ }
1759
+ }
1760
+ /** `array.indexOf(text)`, `lastIndexOf` and `includes` for a long text, as the engine answers them. */
1761
+ searchArray(name, array, wanted, args) {
1762
+ const length = array.length;
1763
+ const same = (item) => {
1764
+ if (typeof item !== "string" || item.length !== wanted.length) {
1765
+ this.work(1);
1766
+ return false;
1767
+ }
1768
+ this.work(wanted.length);
1769
+ return item === wanted;
1770
+ };
1771
+ if (name === "lastIndexOf") {
1772
+ let index2 = args.length > 1 ? integerOf(args[1]) : length - 1;
1773
+ index2 = index2 >= 0 ? Math.min(index2, length - 1) : length + index2;
1774
+ for (; index2 >= 0; index2--) if (same(array[index2])) return index2;
1775
+ return -1;
1776
+ }
1777
+ let index = integerOf(args[1]);
1778
+ if (index < 0) index = Math.max(length + index, 0);
1779
+ for (; index < length; index++) if (same(array[index])) return name === "includes" ? true : index;
1780
+ return name === "includes" ? false : -1;
1781
+ }
1034
1782
  /**
1035
1783
  * Count a call that starts `callerDepth` calls deep, until it returns.
1036
1784
  *
@@ -1073,11 +1821,13 @@ var Interpreter = class {
1073
1821
  */
1074
1822
  bindFunction(target, boundThis, boundArgs) {
1075
1823
  this.charge((boundArgs.length + 2) * 8);
1076
- return (...rest) => {
1824
+ const bound = (...rest) => {
1077
1825
  const result = this.callFunction(target, boundThis, [...boundArgs, ...rest], this.callerDepth);
1078
1826
  result.then(void 0, ignoreRejection2);
1079
1827
  return result;
1080
1828
  };
1829
+ this.provided.add(bound);
1830
+ return bound;
1081
1831
  }
1082
1832
  /**
1083
1833
  * The checks before a built-in or host function runs. The engine performs such a call in one
@@ -1089,6 +1839,15 @@ var Interpreter = class {
1089
1839
  checkBuiltinCall(fn, thisArg, args) {
1090
1840
  const arrayMethod = ARRAY_METHODS.get(fn);
1091
1841
  const stringMethod = arrayMethod === void 0 ? STRING_METHODS.get(fn) : void 0;
1842
+ const otherMethod = arrayMethod === void 0 && stringMethod === void 0 ? OTHER_METHODS.get(fn) : void 0;
1843
+ const engineMethod = arrayMethod !== void 0 || stringMethod !== void 0 || otherMethod !== void 0;
1844
+ if (!engineMethod && fn !== ARRAY_ITERATOR_NEXT && fn !== FunctionProtoToString && !this.provided.has(fn) && !LIBRARY_FUNCTIONS.has(fn)) {
1845
+ throw new InterpreterError("This built-in function is not available in the sandbox");
1846
+ }
1847
+ if (otherMethod !== void 0 && !RECEIVERS[otherMethod.kind].accepts(thisArg, otherMethod.name)) {
1848
+ const { kind, name } = otherMethod;
1849
+ throw new InterpreterError(`${kind} '${name}' works on ${RECEIVERS[kind].noun} only`);
1850
+ }
1092
1851
  let arrayText = 0;
1093
1852
  if (!ARRAY_DATA_FUNCTIONS.has(fn)) {
1094
1853
  const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
@@ -1104,10 +1863,24 @@ var Interpreter = class {
1104
1863
  if (Array.isArray(arg) && !isData?.(i)) measureArray(arg);
1105
1864
  }
1106
1865
  if (arrayMethod === void 0 && stringMethod === void 0 && Array.isArray(thisArg)) measureArray(thisArg);
1107
- arrayText = measure?.length ?? 0;
1866
+ const measured = measure;
1867
+ arrayText = measured?.length ?? 0;
1868
+ this.work(arrayText * WRITE_WORK + (measured?.work ?? 0));
1108
1869
  }
1109
1870
  if (stringMethod !== void 0) args = this.checkStringMethod(stringMethod, thisArg, args, arrayText);
1110
- else if (arrayMethod !== void 0) this.checkArrayMethod(arrayMethod, thisArg, args);
1871
+ else if (arrayMethod !== void 0) args = this.checkArrayMethod(arrayMethod, thisArg, args);
1872
+ const callbackTaken = arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function";
1873
+ if (engineMethod && !callbackTaken) {
1874
+ const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
1875
+ for (let i = 0; i < args.length; i++) {
1876
+ if (typeof args[i] !== "function" || isData?.(i)) continue;
1877
+ const kind = arrayMethod !== void 0 ? "Array" : stringMethod !== void 0 ? "String" : otherMethod?.kind;
1878
+ const name = arrayMethod ?? stringMethod ?? otherMethod?.name;
1879
+ throw new InterpreterError(`${kind} '${name}' does not take a function in the sandbox`);
1880
+ }
1881
+ }
1882
+ const convert = ARGUMENT_CONVERSIONS.get(fn);
1883
+ if (convert) args = convert(args);
1111
1884
  const cost = CALL_COSTS.get(fn);
1112
1885
  if (cost) this.charge(cost(args));
1113
1886
  return args;
@@ -1117,6 +1890,10 @@ var Interpreter = class {
1117
1890
  if (name === "match" || name === "matchAll" || name === "search") {
1118
1891
  throw new InterpreterError(`String '${name}' is not supported: it runs a regular expression`);
1119
1892
  }
1893
+ if (TEXT_SEARCHES.has(name) && args.length > 0) {
1894
+ const pattern = convertedOnce(args[0], String);
1895
+ if (pattern !== args[0]) args = [pattern, ...args.slice(1)];
1896
+ }
1120
1897
  if (name === "replace" || name === "replaceAll") {
1121
1898
  const replacement = args[1];
1122
1899
  if (typeof replacement === "function") {
@@ -1140,14 +1917,15 @@ var Interpreter = class {
1140
1917
  return args;
1141
1918
  }
1142
1919
  if (name === "repeat" || name === "padStart" || name === "padEnd") {
1143
- const n = Number(args[0]);
1920
+ const count = convertedOnce(args[0], Number);
1921
+ const n = Number(count);
1144
1922
  const produced = name === "repeat" ? receiver.length * (n > 0 ? n : 0) : Math.max(receiver.length, n > 0 ? n : 0);
1145
1923
  if (produced > MAX_STRING_OP_LENGTH) {
1146
1924
  throw new InterpreterError(
1147
1925
  `String '${name}' would produce ${produced} chars, exceeding the ${MAX_STRING_OP_LENGTH} limit`
1148
1926
  );
1149
1927
  }
1150
- return args;
1928
+ return args.length === 0 ? args : [count, ...args.slice(1)];
1151
1929
  }
1152
1930
  if (name === "concat") {
1153
1931
  let produced = receiver.length + arrayText;
@@ -1161,6 +1939,20 @@ var Interpreter = class {
1161
1939
  }
1162
1940
  return args;
1163
1941
  }
1942
+ if (name === "normalize") {
1943
+ const form = convertedOnce(args[0], String);
1944
+ const growth = form === "NFKC" || form === "NFKD" ? 18 : 4;
1945
+ if (receiver.length * growth > MAX_JOIN_LENGTH) {
1946
+ let produced = 0;
1947
+ for (let i = 0; i < receiver.length && produced <= MAX_JOIN_LENGTH; i++) {
1948
+ produced += receiver.charCodeAt(i) < 128 ? 1 : growth;
1949
+ }
1950
+ if (produced > MAX_JOIN_LENGTH) {
1951
+ throw new InterpreterError(`String 'normalize' could produce more than ${MAX_JOIN_LENGTH} chars`);
1952
+ }
1953
+ }
1954
+ return args.length === 0 ? args : [form, ...args.slice(1)];
1955
+ }
1164
1956
  if (name === "split") {
1165
1957
  const asked = args[1] === void 0 ? Number.POSITIVE_INFINITY : Number(args[1]) >>> 0;
1166
1958
  return [args[0], Math.min(asked, MAX_ARRAY_LENGTH + 1)];
@@ -1173,44 +1965,56 @@ var Interpreter = class {
1173
1965
  throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
1174
1966
  };
1175
1967
  switch (name) {
1968
+ // Written by the interpreter itself, one item at a time (see arrayLocaleText): how long
1969
+ // the text of a number or a date is depends on the locale and the options.
1970
+ case "toLocaleString":
1971
+ return args;
1176
1972
  // `join` writes every item and a separator between them into one string, in one step; so
1177
- // do the two conversions to text.
1973
+ // does the conversion to text.
1178
1974
  case "join":
1179
- case "toString":
1180
- case "toLocaleString": {
1181
- const separator = name !== "join" || args.length === 0 || args[0] === void 0 ? "," : String(args[0]);
1975
+ case "toString": {
1976
+ const given = name !== "join" || args.length === 0 ? void 0 : convertedOnce(args[0], String);
1977
+ const separator = given === void 0 ? "," : String(given);
1182
1978
  const measure = newTextMeasure();
1183
1979
  measureArrayText(receiver, separator.length, measure, 0);
1184
1980
  if (measure.length > MAX_JOIN_LENGTH) {
1185
1981
  throw new InterpreterError(`Array '${name}' would produce more than ${MAX_JOIN_LENGTH} chars`);
1186
1982
  }
1187
- return;
1983
+ this.work(measure.work);
1984
+ return name === "join" && args.length > 0 ? [given, ...args.slice(1)] : args;
1188
1985
  }
1189
1986
  // Without a comparison function the engine compares the items as text: strings as they
1190
1987
  // are, and an array among the items joined, again for every comparison.
1191
1988
  case "sort":
1192
1989
  case "toSorted": {
1193
- if (typeof args[0] === "function") return;
1990
+ if (typeof args[0] === "function") return args;
1194
1991
  const measure = newTextMeasure();
1992
+ let chars = 0;
1195
1993
  for (let i = 0; i < receiver.length && measure.length <= MAX_JOIN_LENGTH; i++) {
1196
1994
  const item = receiver[i];
1197
1995
  if (Array.isArray(item)) measureArrayText(item, 1, measure, 1);
1996
+ else chars += typeof item === "string" ? item.length : 32;
1198
1997
  }
1199
1998
  if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
1200
- return;
1999
+ const compared = (chars + measure.length) * (Math.ceil(Math.log2(receiver.length + 1)) + 6);
2000
+ if (compared > MAX_CALL_WORK) {
2001
+ throw new InterpreterError(`Array '${name}' would compare more text than one call may`);
2002
+ }
2003
+ this.work(compared);
2004
+ return args;
1201
2005
  }
1202
2006
  // Growth by the arguments (a spread makes them many): charged before it happens.
1203
2007
  case "push":
1204
2008
  case "unshift":
1205
2009
  if (receiver.length + args.length > MAX_ARRAY_LENGTH) tooLong2();
1206
2010
  this.charge(args.length * 8);
1207
- return;
2011
+ return args;
1208
2012
  case "splice":
1209
2013
  case "toSpliced": {
1210
2014
  const added = Math.max(0, args.length - 2);
1211
2015
  if (receiver.length + added > MAX_ARRAY_LENGTH) tooLong2();
1212
2016
  if (name === "splice") this.charge(added * 8);
1213
- return;
2017
+ return args;
1214
2018
  }
1215
2019
  // A new array of the receiver and every array among the arguments: one array, given many
1216
2020
  // times, is small in memory and large once copied.
@@ -1221,16 +2025,50 @@ var Interpreter = class {
1221
2025
  length += Array.isArray(arg) ? arg.length : 1;
1222
2026
  }
1223
2027
  if (length > MAX_ARRAY_LENGTH) tooLong2();
1224
- return;
2028
+ return args;
1225
2029
  }
1226
2030
  case "flat": {
1227
- const depth = args[0] === void 0 ? 1 : Number(args[0]);
2031
+ const given = convertedOnce(args[0], Number);
2032
+ const depth = given === void 0 ? 1 : Number(given);
1228
2033
  if (flatLength(receiver, Number.isNaN(depth) ? 0 : depth, MAX_ARRAY_LENGTH) > MAX_ARRAY_LENGTH) tooLong2();
1229
- return;
2034
+ return args.length === 0 ? args : [given, ...args.slice(1)];
1230
2035
  }
1231
2036
  default:
1232
- return;
2037
+ return args;
2038
+ }
2039
+ }
2040
+ /**
2041
+ * `array.toLocaleString(locales, options)`: the text of every item in the locale's format,
2042
+ * joined by commas, as the engine writes it. The engine does it in one step and the length of
2043
+ * what an item becomes is not known beforehand (a number can take hundreds of chars with the
2044
+ * right options), so the items are converted here one at a time: each counts as a step, and
2045
+ * the text is refused as soon as it is longer than a script's longest text.
2046
+ */
2047
+ arrayLocaleText(array, args, active, written, depth) {
2048
+ if (depth > MAX_TEXT_NESTING) throw new InterpreterError(TEXT_TOO_LONG);
2049
+ const parts = [];
2050
+ active.add(array);
2051
+ try {
2052
+ for (let i = 0; i < array.length; i++) {
2053
+ this.tick();
2054
+ const item = array[i];
2055
+ let text = "";
2056
+ if (Array.isArray(item) && item.toLocaleString === ArrayProtoToLocaleString) {
2057
+ if (!active.has(item)) text = this.arrayLocaleText(item, args, active, written, depth + 1);
2058
+ } else if (item !== null && item !== void 0) {
2059
+ text = String(item.toLocaleString(...args));
2060
+ written.length += text.length;
2061
+ }
2062
+ if (i > 0) written.length += 1;
2063
+ if (written.length > MAX_JOIN_LENGTH) {
2064
+ throw new InterpreterError(`Array 'toLocaleString' would produce more than ${MAX_JOIN_LENGTH} chars`);
2065
+ }
2066
+ parts.push(text);
2067
+ }
2068
+ } finally {
2069
+ active.delete(array);
1233
2070
  }
2071
+ return parts.join(",");
1234
2072
  }
1235
2073
  /**
1236
2074
  * Async implementations of the higher-order array methods, so interpreter
@@ -1303,10 +2141,30 @@ var Interpreter = class {
1303
2141
  acc = arr[order[0]];
1304
2142
  start = 1;
1305
2143
  }
2144
+ let owed = 0;
1306
2145
  for (let n = start; n < order.length; n++) {
1307
2146
  this.tick();
1308
- acc = await reducer(acc, arr[order[n]], order[n], arr);
2147
+ let pending;
2148
+ if (interpreted !== void 0 && typeof acc === "string") {
2149
+ this.accumulatorOwed = owed;
2150
+ try {
2151
+ pending = reducer(acc, arr[order[n]], order[n], arr);
2152
+ } finally {
2153
+ this.accumulatorOwed = void 0;
2154
+ }
2155
+ } else {
2156
+ pending = reducer(acc, arr[order[n]], order[n], arr);
2157
+ }
2158
+ const next = await pending;
2159
+ if (next instanceof AccumulatedText) {
2160
+ acc = next.value;
2161
+ owed = next.owed;
2162
+ } else {
2163
+ acc = next;
2164
+ owed = 0;
2165
+ }
1309
2166
  }
2167
+ if (owed > 0) this.charge(owed);
1310
2168
  return acc;
1311
2169
  }
1312
2170
  case "sort":
@@ -1404,7 +2262,9 @@ var Interpreter = class {
1404
2262
  const rest = {};
1405
2263
  for (const key2 of Object.keys(source)) {
1406
2264
  this.tick();
1407
- if (!taken.has(key2) && !BLOCKED_KEYS.has(key2)) rest[key2] = source[key2];
2265
+ if (taken.has(key2) || BLOCKED_KEYS.has(key2)) continue;
2266
+ assertStorable(rest, key2, source[key2]);
2267
+ rest[key2] = source[key2];
1408
2268
  }
1409
2269
  await this.applyPattern(prop.argument, rest, scope, mode);
1410
2270
  continue;
@@ -1429,7 +2289,7 @@ var Interpreter = class {
1429
2289
  if (node.generator) throw new InterpreterError("Generator functions are not supported");
1430
2290
  const selfName = node.type === "FunctionExpression" && node.id ? node.id.name : void 0;
1431
2291
  const outer = selfName === void 0 ? closure : closure.child();
1432
- const call = async (args, callerDepth) => {
2292
+ const call = async (args, callerDepth, accumulatorOwed) => {
1433
2293
  const fnScope = outer.activation(this.enterCall(callerDepth));
1434
2294
  try {
1435
2295
  for (let i = 0; i < node.params.length; i++) {
@@ -1440,11 +2300,19 @@ var Interpreter = class {
1440
2300
  }
1441
2301
  await this.applyPattern(param, args[i], fnScope, "let");
1442
2302
  }
2303
+ const first = node.params[0];
2304
+ if (accumulatorOwed !== void 0 && first?.type === "Identifier" && typeof args[0] === "string") {
2305
+ const accumulator = fnScope.slot(first.name);
2306
+ if (accumulator !== void 0) {
2307
+ accumulator.owed = accumulatorOwed;
2308
+ fnScope.accumulator = first.name;
2309
+ }
2310
+ }
1443
2311
  if (node.body.type === "BlockStatement") {
1444
2312
  await this.execBlock(node.body.body, fnScope);
1445
2313
  return void 0;
1446
2314
  }
1447
- return await this.evalExpr(node.body, fnScope);
2315
+ return await this.evalReturned(node.body, fnScope);
1448
2316
  } catch (e) {
1449
2317
  if (e instanceof ReturnSignal) return e.value;
1450
2318
  throw e;
@@ -1453,8 +2321,13 @@ var Interpreter = class {
1453
2321
  }
1454
2322
  };
1455
2323
  const depthOfCaller = () => this.callerDepth;
2324
+ const takeAccumulatorOwed = () => {
2325
+ const owed = this.accumulatorOwed;
2326
+ this.accumulatorOwed = void 0;
2327
+ return owed;
2328
+ };
1456
2329
  const interpreted = function interpreted2(...args) {
1457
- const result = call(args, depthOfCaller());
2330
+ const result = call(args, depthOfCaller(), takeAccumulatorOwed());
1458
2331
  result.then(void 0, ignoreRejection2);
1459
2332
  return result;
1460
2333
  };
@@ -1464,7 +2337,9 @@ var Interpreter = class {
1464
2337
  }
1465
2338
  /** A computed property key as text. An array as a key is its items, joined. */
1466
2339
  keyText(value) {
1467
- assertArrayTextWithinLimit(value);
2340
+ this.arrayOperands(value);
2341
+ this.bigIntAsText(value);
2342
+ this.work(operandSize(value));
1468
2343
  return String(value);
1469
2344
  }
1470
2345
  async propKey(prop, scope) {
@@ -1491,19 +2366,55 @@ function isScriptData(value) {
1491
2366
  const prototype = Object.getPrototypeOf(value);
1492
2367
  return prototype === Object.prototype || prototype === null;
1493
2368
  }
1494
- function arrayLengthAfterWrite(array, key, value) {
2369
+ function operandSize(value) {
2370
+ return typeof value === "string" || Array.isArray(value) ? value.length : 0;
2371
+ }
2372
+ function integerOf(value) {
2373
+ const number = Number(value);
2374
+ return Number.isNaN(number) ? 0 : Math.trunc(number);
2375
+ }
2376
+ function expandReplacement(template, text, at, matched) {
2377
+ if (!template.includes("$")) return template;
2378
+ let out = "";
2379
+ for (let i = 0; i < template.length; i++) {
2380
+ const next = template[i] === "$" ? template[i + 1] : void 0;
2381
+ if (next === "$") out += "$";
2382
+ else if (next === "&") out += matched;
2383
+ else if (next === "`") out += text.substring(0, at);
2384
+ else if (next === "'") out += text.substring(at + matched.length);
2385
+ else {
2386
+ out += template[i];
2387
+ continue;
2388
+ }
2389
+ i++;
2390
+ }
2391
+ return out;
2392
+ }
2393
+ function convertedOnce(value, convert) {
2394
+ return typeof value === "object" && value !== null ? convert(value) : value;
2395
+ }
2396
+ function checkArrayWrite(array, key, value, currentLength = array.length) {
2397
+ if (key === "length") value = convertedOnce(value, Number);
2398
+ const length = arrayLengthAfterWrite(currentLength, key, value);
2399
+ if (length > MAX_ARRAY_LENGTH) {
2400
+ throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
2401
+ }
2402
+ return { value, length };
2403
+ }
2404
+ function arrayLengthAfterWrite(currentLength, key, value) {
1495
2405
  if (key === "length") {
1496
2406
  const length = Number(value);
1497
2407
  if (!Number.isInteger(length) || length < 0) throw new InterpreterError("Invalid array length");
1498
2408
  return length;
1499
2409
  }
1500
2410
  const index = Number(key);
1501
- if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(array.length, index + 1);
1502
- return array.length;
2411
+ if (Number.isInteger(index) && index >= 0 && String(index) === key) return Math.max(currentLength, index + 1);
2412
+ return currentLength;
1503
2413
  }
1504
2414
 
1505
2415
  // libs/core/src/value-sanitizer.ts
1506
2416
  var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
2417
+ var CIRCULAR_MARKER_BYTES = 12;
1507
2418
  var ReflectApply2 = Reflect.apply;
1508
2419
  var ReflectGet = Reflect.get;
1509
2420
  var ArrayIsArray = Array.isArray;
@@ -1552,8 +2463,6 @@ function isPlainObject(value) {
1552
2463
  function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
1553
2464
  const maxDepth = options.maxDepth ?? 20;
1554
2465
  const maxProperties = options.maxProperties ?? 1e4;
1555
- const allowDates = options.allowDates ?? true;
1556
- const allowErrors = options.allowErrors ?? true;
1557
2466
  if (depth > maxDepth) {
1558
2467
  throw new Error(
1559
2468
  `Tool handler return value exceeds maximum depth (${maxDepth}). This limit prevents deeply nested objects that could cause stack overflow.`
@@ -1589,10 +2498,22 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1589
2498
  return "[Circular]";
1590
2499
  }
1591
2500
  context.visited.add(value);
2501
+ try {
2502
+ return sanitizeObjectValue(value, options, depth, context);
2503
+ } finally {
2504
+ context.visited.delete(value);
2505
+ }
1592
2506
  }
1593
- if (ArrayIsArray(value)) {
1594
- const rawLen = ReflectGet(value, "length");
1595
- const len = typeof rawLen === "number" && NumberIsFinite(rawLen) && rawLen >= 0 ? MathFloor(rawLen) : 0;
2507
+ return String(value);
2508
+ }
2509
+ function sanitizeObjectValue(value, options, depth, context) {
2510
+ const maxProperties = options.maxProperties ?? 1e4;
2511
+ const allowDates = options.allowDates ?? true;
2512
+ const allowErrors = options.allowErrors ?? true;
2513
+ const type = typeof value;
2514
+ if (ArrayIsArray(value)) {
2515
+ const rawLen = ReflectGet(value, "length");
2516
+ const len = typeof rawLen === "number" && NumberIsFinite(rawLen) && rawLen >= 0 ? MathFloor(rawLen) : 0;
1596
2517
  context.propCount.count += len;
1597
2518
  if (context.propCount.count > maxProperties) {
1598
2519
  throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
@@ -1639,9 +2560,12 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1639
2560
  const sanitizedMap = ObjectCreate(null);
1640
2561
  const entries = ReflectApply2(MapProtoEntries, inspected, []);
1641
2562
  for (const [key, val] of entries) {
2563
+ context.propCount.count++;
2564
+ if (context.propCount.count > maxProperties) {
2565
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
2566
+ }
1642
2567
  if (typeof key !== "string") continue;
1643
2568
  if (DANGEROUS_KEYS.has(key)) continue;
1644
- context.propCount.count++;
1645
2569
  sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
1646
2570
  }
1647
2571
  return sanitizedMap;
@@ -1651,6 +2575,9 @@ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: {
1651
2575
  const result = [];
1652
2576
  for (const item of iter) {
1653
2577
  context.propCount.count++;
2578
+ if (context.propCount.count > maxProperties) {
2579
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
2580
+ }
1654
2581
  result.push(sanitizeValue(item, options, depth + 1, context));
1655
2582
  }
1656
2583
  return result;
@@ -1738,7 +2665,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
1738
2665
  }
1739
2666
  if (ArrayIsArray(value)) {
1740
2667
  if (currentPath.has(value)) {
1741
- return 4;
2668
+ return CIRCULAR_MARKER_BYTES;
1742
2669
  }
1743
2670
  currentPath.add(value);
1744
2671
  try {
@@ -1764,7 +2691,7 @@ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3,
1764
2691
  if (type === "object") {
1765
2692
  const object = value;
1766
2693
  if (currentPath.has(object)) {
1767
- return 4;
2694
+ return CIRCULAR_MARKER_BYTES;
1768
2695
  }
1769
2696
  if (!isPlainObject(object)) {
1770
2697
  if (hasBrand(DateProtoGetTime, object)) {
@@ -1944,7 +2871,8 @@ var SafeJSON = frozenRecord({
1944
2871
  }
1945
2872
  const size = checkSerializedSize(value, MAX_JSON_TEXT_BYTES);
1946
2873
  if (!size.ok) throw new RangeError(`JSON.stringify: the text would be too large (${size.error})`);
1947
- const indent = indentOf(space);
2874
+ const indentation = typeof space === "number" || typeof space === "string" ? space : void 0;
2875
+ const indent = indentOf(indentation);
1948
2876
  if (indent > 0) {
1949
2877
  const budget = MAX_JSON_TEXT_BYTES - size.estimatedBytes;
1950
2878
  if (indentationSize(value, indent, budget, 0, /* @__PURE__ */ new Set()) > budget) {
@@ -1954,10 +2882,14 @@ var SafeJSON = frozenRecord({
1954
2882
  return JSON.stringify(
1955
2883
  value,
1956
2884
  Array.isArray(replacer) ? replacer : void 0,
1957
- space
2885
+ indentation
1958
2886
  );
1959
2887
  }
1960
2888
  });
2889
+ convertsBeforeCall(
2890
+ SafeJSON["parse"],
2891
+ (args) => args.length === 0 ? args : [String(args[0]), ...args.slice(1)]
2892
+ );
1961
2893
  chargedBeforeCall(SafeJSON["parse"], (args) => parsedJsonCost(String(args[0])));
1962
2894
  takesArraysAsData(SafeJSON["stringify"]);
1963
2895
  var SafeObject = frozenRecord({
@@ -1972,7 +2904,10 @@ var SafeObject = frozenRecord({
1972
2904
  if (entry === null || typeof entry !== "object") throw new TypeError("Each entry must be a [key, value] pair");
1973
2905
  assertArrayTextWithinLimit(entry[0]);
1974
2906
  const key = String(entry[0]);
1975
- if (!isBlockedKey(key)) result[key] = entry[1];
2907
+ if (isBlockedKey(key)) continue;
2908
+ const value = entry[1];
2909
+ assertStorable(result, key, value);
2910
+ result[key] = value;
1976
2911
  }
1977
2912
  return result;
1978
2913
  },
@@ -1980,10 +2915,26 @@ var SafeObject = frozenRecord({
1980
2915
  if (!isScriptData(target) || Object.isFrozen(target)) {
1981
2916
  throw new TypeError("Object.assign needs an object or array the script created as its target");
1982
2917
  }
2918
+ const targetIsArray = Array.isArray(target);
2919
+ const lengths = [];
2920
+ let length = targetIsArray ? target.length : 0;
2921
+ for (const source of sources) {
2922
+ if (source === null || source === void 0) continue;
2923
+ for (const key of dataKeys(source)) {
2924
+ const value = source[key];
2925
+ assertStorable(target, key, value);
2926
+ if (targetIsArray) {
2927
+ const checked = checkArrayWrite(target, key, value, length);
2928
+ length = checked.length;
2929
+ if (key === "length") lengths.push(checked.value);
2930
+ }
2931
+ }
2932
+ }
2933
+ let nextLength = 0;
1983
2934
  for (const source of sources) {
1984
2935
  if (source === null || source === void 0) continue;
1985
2936
  for (const key of dataKeys(source)) {
1986
- target[key] = source[key];
2937
+ target[key] = targetIsArray && key === "length" ? lengths[nextLength++] : source[key];
1987
2938
  }
1988
2939
  }
1989
2940
  return target;
@@ -2058,6 +3009,23 @@ var SafeDate = frozenFunction(() => (/* @__PURE__ */ new Date()).toString(), {
2058
3009
  parse: (text) => Date.parse(String(text)),
2059
3010
  UTC: (...parts) => Date.UTC(...parts)
2060
3011
  });
3012
+ function encodedText(encode, value) {
3013
+ const text = String(value);
3014
+ if (text.length * 9 > MAX_JOIN_LENGTH) {
3015
+ let produced = 0;
3016
+ for (let index = 0; index < text.length && produced <= MAX_JOIN_LENGTH; index++) {
3017
+ const code = text.charCodeAt(index);
3018
+ if (code >= 2048) produced += 9;
3019
+ else if (code >= 128) produced += 6;
3020
+ else if (code >= 48 && code <= 57 || code >= 65 && code <= 90 || code >= 97 && code <= 122) produced += 1;
3021
+ else produced += 3;
3022
+ }
3023
+ if (produced > MAX_JOIN_LENGTH) {
3024
+ throw new RangeError(`The encoded text would be too long (more than ${MAX_JOIN_LENGTH} chars)`);
3025
+ }
3026
+ }
3027
+ return encode(text);
3028
+ }
2061
3029
  var ERROR_TYPES = ["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError"];
2062
3030
  function errorType(name) {
2063
3031
  const make = (args) => createScriptError(name, args.length === 0 || args[0] === void 0 ? "" : toStringValue(args[0]));
@@ -2088,8 +3056,8 @@ var SAFE_GLOBALS = Object.freeze({
2088
3056
  parseInt: Object.freeze(
2089
3057
  (value, radix) => Number.parseInt(String(value), radix)
2090
3058
  ),
2091
- encodeURI: Object.freeze((value) => encodeURI(String(value))),
2092
- encodeURIComponent: Object.freeze((value) => encodeURIComponent(String(value))),
3059
+ encodeURI: Object.freeze((value) => encodedText(encodeURI, value)),
3060
+ encodeURIComponent: Object.freeze((value) => encodedText(encodeURIComponent, value)),
2093
3061
  decodeURI: Object.freeze((value) => decodeURI(String(value))),
2094
3062
  decodeURIComponent: Object.freeze((value) => decodeURIComponent(String(value)))
2095
3063
  });
@@ -2203,6 +3171,8 @@ var MemoryTracker = class {
2203
3171
  trackedBytes = 0;
2204
3172
  peakTrackedBytes = 0;
2205
3173
  allocationCount = 0;
3174
+ /** Whether this tracker has refused an allocation since it was started */
3175
+ limitExceeded = false;
2206
3176
  config;
2207
3177
  constructor(config = {}) {
2208
3178
  this.config = {
@@ -2219,6 +3189,14 @@ var MemoryTracker = class {
2219
3189
  this.trackedBytes = 0;
2220
3190
  this.peakTrackedBytes = 0;
2221
3191
  this.allocationCount = 0;
3192
+ this.limitExceeded = false;
3193
+ }
3194
+ /**
3195
+ * Whether the limit was exceeded since tracking started: the tracker itself refused an
3196
+ * allocation. An error that only says so about itself is not evidence of that.
3197
+ */
3198
+ hasExceededLimit() {
3199
+ return this.limitExceeded;
2222
3200
  }
2223
3201
  /**
2224
3202
  * Track an allocation
@@ -2229,6 +3207,7 @@ var MemoryTracker = class {
2229
3207
  track(bytes) {
2230
3208
  if (typeof bytes !== "number" || Number.isNaN(bytes)) {
2231
3209
  if (this.config.memoryLimit > 0) {
3210
+ this.limitExceeded = true;
2232
3211
  throw new MemoryLimitError(
2233
3212
  "Memory limit exceeded: allocation size is not a number",
2234
3213
  this.trackedBytes,
@@ -2244,6 +3223,7 @@ var MemoryTracker = class {
2244
3223
  this.peakTrackedBytes = this.trackedBytes;
2245
3224
  }
2246
3225
  if (this.config.memoryLimit > 0 && this.trackedBytes > this.config.memoryLimit) {
3226
+ this.limitExceeded = true;
2247
3227
  throw new MemoryLimitError(
2248
3228
  `Memory limit exceeded: ${this.formatBytes(this.trackedBytes)} used > ${this.formatBytes(
2249
3229
  this.config.memoryLimit
@@ -2430,10 +3410,270 @@ var REFERENCE_CONFIGS = {
2430
3410
  // Very deep resolution
2431
3411
  }
2432
3412
  };
3413
+ var REF_ID_PREFIX = "__REF_";
3414
+ var REF_ID_SUFFIX = "__";
2433
3415
  var REF_ID_PATTERN = /^__REF_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}__$/i;
2434
3416
  function isReferenceId(value) {
2435
3417
  return typeof value === "string" && REF_ID_PATTERN.test(value);
2436
3418
  }
3419
+ function getMaxTotalResolvedSize(config) {
3420
+ const configured = config.maxTotalResolvedSize;
3421
+ if (typeof configured === "number" && configured >= 0) {
3422
+ return configured;
3423
+ }
3424
+ return 2 * config.maxTotalSize;
3425
+ }
3426
+
3427
+ // libs/core/src/sidecar/reference-sidecar.ts
3428
+ var SidecarLimitError = class _SidecarLimitError extends Error {
3429
+ constructor(message, code, limit, current) {
3430
+ super(message);
3431
+ this.code = code;
3432
+ this.limit = limit;
3433
+ this.current = current;
3434
+ this.name = "SidecarLimitError";
3435
+ Object.setPrototypeOf(this, _SidecarLimitError.prototype);
3436
+ }
3437
+ };
3438
+ var ReferenceSidecar = class {
3439
+ constructor(config) {
3440
+ this.config = config;
3441
+ this.maxTotalResolvedSize = getMaxTotalResolvedSize(config);
3442
+ }
3443
+ storage = /* @__PURE__ */ new Map();
3444
+ metadata = /* @__PURE__ */ new Map();
3445
+ /** The stored values that were resolved for a tool call, as the string they were resolved to */
3446
+ resolved = /* @__PURE__ */ new Map();
3447
+ totalSize = 0;
3448
+ /** Bytes of resolved data built for the tool calls of this execution so far */
3449
+ resolvedSize = 0;
3450
+ maxTotalResolvedSize;
3451
+ disposed = false;
3452
+ /**
3453
+ * Store data and return a reference ID
3454
+ *
3455
+ * @param data - The data to store (string or Buffer)
3456
+ * @param source - Where this data came from
3457
+ * @param options - Optional metadata
3458
+ * @returns The reference ID (format: __REF_uuid__)
3459
+ * @throws SidecarLimitError if limits are exceeded
3460
+ */
3461
+ store(data, source, options) {
3462
+ if (this.disposed) {
3463
+ throw new Error("Cannot store: sidecar has been disposed");
3464
+ }
3465
+ const buffer = typeof data === "string" ? Buffer.from(data, "utf-8") : data;
3466
+ const size = buffer.length;
3467
+ if (this.storage.size >= this.config.maxReferenceCount) {
3468
+ throw new SidecarLimitError(
3469
+ `Maximum reference count exceeded (${this.config.maxReferenceCount})`,
3470
+ "MAX_REFERENCE_COUNT",
3471
+ this.config.maxReferenceCount,
3472
+ this.storage.size
3473
+ );
3474
+ }
3475
+ if (size > this.config.maxReferenceSize) {
3476
+ throw new SidecarLimitError(
3477
+ `Reference size ${size} bytes exceeds maximum ${this.config.maxReferenceSize} bytes`,
3478
+ "MAX_REFERENCE_SIZE",
3479
+ this.config.maxReferenceSize,
3480
+ size
3481
+ );
3482
+ }
3483
+ if (this.totalSize + size > this.config.maxTotalSize) {
3484
+ throw new SidecarLimitError(
3485
+ `Total sidecar size would exceed maximum: ${this.totalSize + size} > ${this.config.maxTotalSize}`,
3486
+ "MAX_TOTAL_SIZE",
3487
+ this.config.maxTotalSize,
3488
+ this.totalSize + size
3489
+ );
3490
+ }
3491
+ const randomUUID = globalThis.crypto?.randomUUID?.bind(globalThis.crypto);
3492
+ if (!randomUUID) throw new Error("Secure random UUID generation is unavailable");
3493
+ const refId = `${REF_ID_PREFIX}${randomUUID()}${REF_ID_SUFFIX}`;
3494
+ this.storage.set(refId, Buffer.from(buffer));
3495
+ this.totalSize += size;
3496
+ this.metadata.set(refId, {
3497
+ createdAt: Date.now(),
3498
+ size,
3499
+ source,
3500
+ mimeType: options?.mimeType,
3501
+ origin: options?.origin
3502
+ });
3503
+ return refId;
3504
+ }
3505
+ /**
3506
+ * Retrieve data by reference ID
3507
+ *
3508
+ * @param refId - The reference ID to look up
3509
+ * @returns The stored data or undefined if not found
3510
+ */
3511
+ retrieve(refId) {
3512
+ if (this.disposed) {
3513
+ return void 0;
3514
+ }
3515
+ const data = this.storage.get(refId);
3516
+ return data ? Buffer.from(data) : void 0;
3517
+ }
3518
+ /**
3519
+ * Retrieve data as a string
3520
+ *
3521
+ * @param refId - The reference ID to look up
3522
+ * @param encoding - String encoding (default: utf-8)
3523
+ * @returns The stored data as a string or undefined
3524
+ */
3525
+ retrieveString(refId, encoding = "utf-8") {
3526
+ const data = this.retrieve(refId);
3527
+ return data?.toString(encoding);
3528
+ }
3529
+ /**
3530
+ * Resolve a reference for a tool call: the stored data as a string
3531
+ *
3532
+ * A stored value is decoded once in the life of the sidecar (one execution) and counted
3533
+ * against `maxTotalResolvedSize` then. Every later resolution, in the same call or in another,
3534
+ * returns the same string and counts nothing: a string cannot be changed, so handing it out
3535
+ * again takes no memory.
3536
+ *
3537
+ * @param refId - The reference ID to resolve
3538
+ * @returns The stored data as a string, or undefined if the reference is not known
3539
+ * @throws SidecarLimitError if the execution's total of resolved data would be exceeded
3540
+ */
3541
+ resolveString(refId) {
3542
+ if (this.disposed) {
3543
+ return void 0;
3544
+ }
3545
+ const known = this.resolved.get(refId);
3546
+ if (known !== void 0) {
3547
+ return known;
3548
+ }
3549
+ const data = this.storage.get(refId);
3550
+ if (data === void 0) {
3551
+ return void 0;
3552
+ }
3553
+ this.countResolved(data.length);
3554
+ const text = data.toString("utf-8");
3555
+ this.resolved.set(refId, text);
3556
+ return text;
3557
+ }
3558
+ /**
3559
+ * Whether a reference was resolved before, so that resolving it again counts nothing
3560
+ */
3561
+ isResolved(refId) {
3562
+ return !this.disposed && this.resolved.has(refId);
3563
+ }
3564
+ /**
3565
+ * Count resolved data that is about to be built for a tool call of this execution
3566
+ *
3567
+ * @param bytes - Size of the data in bytes
3568
+ * @throws SidecarLimitError if the total would exceed `maxTotalResolvedSize`; nothing is counted then
3569
+ */
3570
+ countResolved(bytes) {
3571
+ if (!this.canResolve(bytes)) {
3572
+ throw new SidecarLimitError(
3573
+ `Total resolved size would exceed maximum: ${this.resolvedSize + bytes} > ${this.maxTotalResolvedSize}`,
3574
+ "MAX_TOTAL_RESOLVED_SIZE",
3575
+ this.maxTotalResolvedSize,
3576
+ this.resolvedSize + bytes
3577
+ );
3578
+ }
3579
+ this.resolvedSize += bytes;
3580
+ }
3581
+ /**
3582
+ * Whether `bytes` more of resolved data fit in what this execution may resolve in total
3583
+ */
3584
+ canResolve(bytes) {
3585
+ return bytes >= 0 && this.resolvedSize + bytes <= this.maxTotalResolvedSize;
3586
+ }
3587
+ /**
3588
+ * Bytes of resolved data built for the tool calls of this execution so far
3589
+ */
3590
+ getResolvedSize() {
3591
+ return this.resolvedSize;
3592
+ }
3593
+ /**
3594
+ * Check if a reference ID exists
3595
+ */
3596
+ has(refId) {
3597
+ return !this.disposed && this.storage.has(refId);
3598
+ }
3599
+ /**
3600
+ * Get metadata for a reference
3601
+ */
3602
+ getMetadata(refId) {
3603
+ if (this.disposed) {
3604
+ return void 0;
3605
+ }
3606
+ return this.metadata.get(refId);
3607
+ }
3608
+ /**
3609
+ * Get the size of a reference without retrieving data
3610
+ */
3611
+ getSize(refId) {
3612
+ return this.getMetadata(refId)?.size;
3613
+ }
3614
+ /**
3615
+ * Get total size of all stored references
3616
+ */
3617
+ getTotalSize() {
3618
+ return this.totalSize;
3619
+ }
3620
+ /**
3621
+ * Get number of stored references
3622
+ */
3623
+ getCount() {
3624
+ return this.storage.size;
3625
+ }
3626
+ /**
3627
+ * Get the configuration
3628
+ */
3629
+ getConfig() {
3630
+ return { ...this.config };
3631
+ }
3632
+ /**
3633
+ * Check if a value is a reference ID
3634
+ */
3635
+ isReference(value) {
3636
+ return isReferenceId(value);
3637
+ }
3638
+ /**
3639
+ * Get all reference IDs (for debugging/auditing)
3640
+ */
3641
+ getAllReferenceIds() {
3642
+ return Array.from(this.storage.keys());
3643
+ }
3644
+ /**
3645
+ * Get audit log of all stored references
3646
+ */
3647
+ getAuditLog() {
3648
+ const log = [];
3649
+ for (const [refId, metadata] of this.metadata) {
3650
+ log.push({ refId, metadata });
3651
+ }
3652
+ return log;
3653
+ }
3654
+ /**
3655
+ * Check if the sidecar has been disposed
3656
+ */
3657
+ isDisposed() {
3658
+ return this.disposed;
3659
+ }
3660
+ /**
3661
+ * Dispose the sidecar and release all memory
3662
+ *
3663
+ * MUST be called after each execution to prevent memory leaks.
3664
+ * After disposal, the sidecar cannot be used.
3665
+ */
3666
+ dispose() {
3667
+ if (this.disposed) {
3668
+ return;
3669
+ }
3670
+ this.storage.clear();
3671
+ this.metadata.clear();
3672
+ this.resolved.clear();
3673
+ this.totalSize = 0;
3674
+ this.disposed = true;
3675
+ }
3676
+ };
2437
3677
 
2438
3678
  // libs/core/src/sidecar/reference-resolver.ts
2439
3679
  var ReflectGet2 = Reflect.get;
@@ -2542,17 +3782,88 @@ var ReferenceResolver = class {
2542
3782
  /**
2543
3783
  * Check if resolution would exceed size limits
2544
3784
  *
3785
+ * Two limits apply: `maxResolvedSize` to what this value expands to, and
3786
+ * `maxTotalResolvedSize` to what the execution has had resolved so far plus what resolving
3787
+ * this value would add (see `predictAddedSize`).
3788
+ *
2545
3789
  * @param value - The value to check
2546
- * @returns true if resolution would exceed maxResolvedSize
3790
+ * @returns true if resolution would exceed maxResolvedSize or the execution's total
2547
3791
  */
2548
3792
  wouldExceedLimit(value) {
2549
3793
  try {
2550
3794
  const size = this.predictExpandedSize(value);
2551
- return size > this.config.maxResolvedSize;
3795
+ if (size > this.config.maxResolvedSize) {
3796
+ return true;
3797
+ }
3798
+ return !this.sidecar.canResolve(this.predictAddedSize(value, 0, /* @__PURE__ */ new Set()));
2552
3799
  } catch {
2553
3800
  return true;
2554
3801
  }
2555
3802
  }
3803
+ /**
3804
+ * Predict what resolving a value would add to the execution's total of resolved data,
3805
+ * WITHOUT allocating memory
3806
+ *
3807
+ * A stored value adds its size the first time it is resolved in the execution and nothing
3808
+ * afterwards (`counted` holds the ones this walk has seen). A composite adds the size of the
3809
+ * string it is joined into, every time, besides what its parts add.
3810
+ */
3811
+ predictAddedSize(value, depth, counted) {
3812
+ if (depth > this.config.maxResolutionDepth) {
3813
+ throw new ResolutionLimitError(
3814
+ `Maximum resolution depth exceeded (${this.config.maxResolutionDepth})`,
3815
+ "MAX_RESOLUTION_DEPTH",
3816
+ this.config.maxResolutionDepth,
3817
+ depth
3818
+ );
3819
+ }
3820
+ if (isReferenceId(value)) {
3821
+ if (counted.has(value) || this.sidecar.isResolved(value)) {
3822
+ return 0;
3823
+ }
3824
+ counted.add(value);
3825
+ return this.sidecar.getSize(value) ?? 0;
3826
+ }
3827
+ if (isCompositeHandle(value)) {
3828
+ const parts = value.__parts;
3829
+ const len = untrustedLength(parts);
3830
+ let sum = this.predictExpandedSize(value, depth);
3831
+ for (let i = 0; i < len; i++) {
3832
+ sum += this.predictAddedSize(untrustedAt(parts, i), depth + 1, counted);
3833
+ }
3834
+ return sum;
3835
+ }
3836
+ if (Array.isArray(value)) {
3837
+ const len = untrustedLength(value);
3838
+ let sum = 0;
3839
+ for (let i = 0; i < len; i++) {
3840
+ sum += this.predictAddedSize(untrustedAt(value, i), depth + 1, counted);
3841
+ }
3842
+ return sum;
3843
+ }
3844
+ if (value !== null && typeof value === "object") {
3845
+ let sum = 0;
3846
+ for (const val of Object.values(value)) {
3847
+ sum += this.predictAddedSize(val, depth + 1, counted);
3848
+ }
3849
+ return sum;
3850
+ }
3851
+ return 0;
3852
+ }
3853
+ /**
3854
+ * Run a step that counts resolved data against the execution's total; when the sidecar
3855
+ * refuses it, the refusal is thrown as the resolution error callers of `resolve` handle
3856
+ */
3857
+ withinTotal(count) {
3858
+ try {
3859
+ count();
3860
+ } catch (error) {
3861
+ if (error instanceof SidecarLimitError) {
3862
+ throw new ResolutionLimitError(error.message, error.code, error.limit, error.current);
3863
+ }
3864
+ throw error;
3865
+ }
3866
+ }
2556
3867
  /**
2557
3868
  * Resolve all reference IDs in a value tree
2558
3869
  *
@@ -2575,7 +3886,10 @@ var ReferenceResolver = class {
2575
3886
  );
2576
3887
  }
2577
3888
  if (isReferenceId(value)) {
2578
- const data = this.sidecar.retrieveString(value);
3889
+ let data;
3890
+ this.withinTotal(() => {
3891
+ data = this.sidecar.resolveString(value);
3892
+ });
2579
3893
  if (data === void 0) {
2580
3894
  throw new Error(`Unknown reference: ${value}`);
2581
3895
  }
@@ -2613,6 +3927,8 @@ var ReferenceResolver = class {
2613
3927
  * Resolve a composite handle by concatenating its parts
2614
3928
  */
2615
3929
  resolveComposite(handle, depth) {
3930
+ const joinedSize = this.predictExpandedSize(handle, depth);
3931
+ this.withinTotal(() => this.sidecar.countResolved(joinedSize));
2616
3932
  const out = [];
2617
3933
  const source = handle.__parts;
2618
3934
  const len = untrustedLength(source);
@@ -2628,28 +3944,38 @@ var ReferenceResolver = class {
2628
3944
  /**
2629
3945
  * Check if a value contains any reference IDs
2630
3946
  *
3947
+ * Every value is looked at, at any depth: a reference or composite past `maxResolutionDepth`
3948
+ * cannot be resolved, and it must still be found, so that `resolve()` refuses the call rather
3949
+ * than the handler receiving it unresolved. The value is walked with a list instead of by
3950
+ * recursion, so a deep value cannot exhaust the stack, and an object is looked at once.
3951
+ *
2631
3952
  * @param value - The value to check
2632
- * @param depth - Current recursion depth (internal)
3953
+ * @param _depth - Unused; kept for callers that pass a depth
2633
3954
  * @returns true if the value or any nested value is a reference
2634
3955
  */
2635
- containsReferences(value, depth = 0) {
2636
- if (depth > this.config.maxResolutionDepth) {
2637
- return false;
2638
- }
2639
- if (isReferenceId(value) || isCompositeHandle(value)) {
2640
- return true;
2641
- }
2642
- if (Array.isArray(value)) {
2643
- const len = untrustedLength(value);
2644
- for (let i = 0; i < len; i++) {
2645
- if (this.containsReferences(untrustedAt(value, i), depth + 1)) {
2646
- return true;
3956
+ containsReferences(value, _depth = 0) {
3957
+ const pending = [value];
3958
+ const seen = /* @__PURE__ */ new Set();
3959
+ while (pending.length > 0) {
3960
+ const current = pending.pop();
3961
+ if (isReferenceId(current) || isCompositeHandle(current)) {
3962
+ return true;
3963
+ }
3964
+ if (current === null || typeof current !== "object" || seen.has(current)) {
3965
+ continue;
3966
+ }
3967
+ seen.add(current);
3968
+ if (Array.isArray(current)) {
3969
+ const len = untrustedLength(current);
3970
+ for (let i = 0; i < len; i++) {
3971
+ pending.push(untrustedAt(current, i));
2647
3972
  }
3973
+ continue;
3974
+ }
3975
+ const members = Object.values(current);
3976
+ for (let i = 0; i < members.length; i++) {
3977
+ pending.push(members[i]);
2648
3978
  }
2649
- return false;
2650
- }
2651
- if (value !== null && typeof value === "object") {
2652
- return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
2653
3979
  }
2654
3980
  return false;
2655
3981
  }
@@ -2846,6 +4172,79 @@ function sanitizeStackTrace(stack, sanitize = true) {
2846
4172
  return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
2847
4173
  }
2848
4174
 
4175
+ // libs/core/src/thrown-value.ts
4176
+ var MAX_THROWN_MESSAGE_LENGTH = 16 * 1024;
4177
+ var MAX_THROWN_STACK_LENGTH = 64 * 1024;
4178
+
4179
+ // libs/core/src/bounded-json.ts
4180
+ var JSONStringify = JSON.stringify;
4181
+ var ReflectApply3 = Reflect.apply;
4182
+ var ArrayIsArray2 = Array.isArray;
4183
+ var StringValueOf = String.prototype.valueOf;
4184
+ var NumberValueOf = Number.prototype.valueOf;
4185
+ var JsonTooLargeError = class extends Error {
4186
+ constructor(limit) {
4187
+ super(`JSON text exceeds ${limit} bytes`);
4188
+ this.name = "JsonTooLargeError";
4189
+ }
4190
+ };
4191
+ var JsonTraversalLimitError = class extends Error {
4192
+ constructor(limit) {
4193
+ super(`JSON traversal exceeds ${limit} members`);
4194
+ this.name = "JsonTraversalLimitError";
4195
+ }
4196
+ };
4197
+ function hasSlot(valueOf, value) {
4198
+ try {
4199
+ ReflectApply3(valueOf, value, []);
4200
+ return true;
4201
+ } catch {
4202
+ return false;
4203
+ }
4204
+ }
4205
+ function stringifyWithin(value, limit) {
4206
+ let bytes = 0;
4207
+ let visits = 0;
4208
+ const maxVisits = Math.max(1e4, Math.min(1e6, limit * 10));
4209
+ let root = true;
4210
+ return JSONStringify(value, function(key, member) {
4211
+ if (++visits > maxVisits) throw new JsonTraversalLimitError(maxVisits);
4212
+ if (member !== null && typeof member === "object") {
4213
+ if (hasSlot(StringValueOf, member)) member = String(member);
4214
+ else if (hasSlot(NumberValueOf, member)) member = Number(member);
4215
+ }
4216
+ let added;
4217
+ switch (typeof member) {
4218
+ case "string":
4219
+ added = member.length + 2;
4220
+ break;
4221
+ case "number":
4222
+ added = Number.isFinite(member) ? String(member).length : 4;
4223
+ break;
4224
+ case "boolean":
4225
+ added = member ? 4 : 5;
4226
+ break;
4227
+ case "object":
4228
+ case "bigint":
4229
+ added = member === null ? 4 : 2;
4230
+ break;
4231
+ default:
4232
+ added = 0;
4233
+ }
4234
+ if (!root) {
4235
+ if (ArrayIsArray2(this)) added = added || 4;
4236
+ else if (added > 0) added += key.length + 3;
4237
+ }
4238
+ root = false;
4239
+ bytes += added;
4240
+ if (bytes > limit) throw new JsonTooLargeError(limit);
4241
+ return member;
4242
+ });
4243
+ }
4244
+ function utf8Length2(value) {
4245
+ return Buffer.byteLength(value, "utf8");
4246
+ }
4247
+
2849
4248
  // libs/core/src/tool-bridge.ts
2850
4249
  var TOOL_BRIDGE_PROTOCOL_VERSION = 1;
2851
4250
  function utf8ByteLength(value) {
@@ -3001,9 +4400,9 @@ function createHostToolBridge(executionContext, options) {
3001
4400
  if (typeof executionContext.hostToolBridge === "function") {
3002
4401
  return createRelayedToolBridge(executionContext, options, executionContext.hostToolBridge);
3003
4402
  }
3004
- const { config, stats, toolHandler, sidecar, referenceConfig } = executionContext;
4403
+ const { config, stats, toolHandler, sidecar, referenceConfig: referenceConfig2 } = executionContext;
3005
4404
  const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
3006
- const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
4405
+ const resolver = sidecar && referenceConfig2 ? new ReferenceResolver(sidecar, referenceConfig2) : void 0;
3007
4406
  return async (requestJson) => {
3008
4407
  try {
3009
4408
  if (typeof requestJson !== "string") {
@@ -3181,6 +4580,7 @@ function createHostToolBridge(executionContext, options) {
3181
4580
  "Tool returned an unsupported value",
3182
4581
  "TOOL_RESULT_NOT_SAFE"
3183
4582
  );
4583
+ executionContext.onToolBridgeFailure?.();
3184
4584
  return serializeResponse(
3185
4585
  {
3186
4586
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -3190,13 +4590,55 @@ function createHostToolBridge(executionContext, options) {
3190
4590
  maxPayloadBytes
3191
4591
  );
3192
4592
  }
3193
- if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
4593
+ const resultLimit = executionContext.maxToolResultBytes;
4594
+ if (resultLimit !== void 0 && Number.isFinite(resultLimit) && resultLimit > 0) {
4595
+ let tooLarge = false;
4596
+ let tooComplex = false;
4597
+ try {
4598
+ const resultJson = stringifyWithin(sanitizedResult, resultLimit);
4599
+ tooLarge = resultJson !== void 0 && utf8ByteLength(resultJson) > resultLimit;
4600
+ } catch (error) {
4601
+ tooLarge = error instanceof JsonTooLargeError;
4602
+ tooComplex = error instanceof JsonTraversalLimitError;
4603
+ }
4604
+ if (tooLarge || tooComplex) {
4605
+ executionContext.onToolBridgeFailure?.();
4606
+ return serializeResponse(
4607
+ {
4608
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
4609
+ ok: false,
4610
+ error: {
4611
+ name: "ToolBridgeError",
4612
+ message: tooComplex ? "Tool result exceeds the traversal limit" : `Tool result exceeds the limit of ${resultLimit} bytes`,
4613
+ code: tooComplex ? "TOOL_RESULT_TOO_COMPLEX" : "TOOL_RESULT_TOO_LARGE",
4614
+ toolError: true
4615
+ }
4616
+ },
4617
+ maxPayloadBytes
4618
+ );
4619
+ }
4620
+ }
4621
+ if (sidecar && referenceConfig2 && typeof sanitizedResult === "string") {
3194
4622
  const size = utf8ByteLength(sanitizedResult);
3195
- if (size >= referenceConfig.extractionThreshold) {
4623
+ if (size >= referenceConfig2.extractionThreshold) {
3196
4624
  try {
3197
4625
  const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
3198
4626
  sanitizedResult = refId;
3199
4627
  } catch {
4628
+ executionContext.onToolBridgeFailure?.();
4629
+ return serializeResponse(
4630
+ {
4631
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
4632
+ ok: false,
4633
+ error: {
4634
+ name: "ToolBridgeError",
4635
+ message: "Tool result could not be stored in the reference sidecar",
4636
+ code: "TOOL_RESULT_NOT_STORED",
4637
+ toolError: true
4638
+ }
4639
+ },
4640
+ maxPayloadBytes
4641
+ );
3200
4642
  }
3201
4643
  }
3202
4644
  }
@@ -3211,6 +4653,7 @@ function createHostToolBridge(executionContext, options) {
3211
4653
  "Tool result must be JSON-serializable",
3212
4654
  "TOOL_RESULT_NOT_JSON"
3213
4655
  );
4656
+ executionContext.onToolBridgeFailure?.();
3214
4657
  return serializeResponse(
3215
4658
  {
3216
4659
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -3221,6 +4664,7 @@ function createHostToolBridge(executionContext, options) {
3221
4664
  );
3222
4665
  }
3223
4666
  if (utf8ByteLength(okJson) > maxPayloadBytes) {
4667
+ executionContext.onToolBridgeFailure?.();
3224
4668
  return serializeResponse(
3225
4669
  {
3226
4670
  v: TOOL_BRIDGE_PROTOCOL_VERSION,
@@ -3258,12 +4702,29 @@ var MAX_PARALLEL_ITEMS = 100;
3258
4702
  var MAX_SERIALIZED_RESULT_BYTES = 50 * 1024 * 1024;
3259
4703
  var DEFAULT_MAX_CONSOLE_CALLS = 100;
3260
4704
  var DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;
4705
+ var DEFAULT_MAX_TOOL_PAYLOAD_BYTES = 5 * 1024 * 1024;
4706
+ function certainlyLargerThan(value, bytes) {
4707
+ if (!Number.isFinite(bytes) || bytes <= 0) return false;
4708
+ return !checkSerializedSize(value, bytes).ok;
4709
+ }
4710
+ function executionOver() {
4711
+ return sandboxError("Execution ended");
4712
+ }
3261
4713
  function sandboxError(message, name = "Error", code) {
3262
4714
  const error = new Error(message);
3263
4715
  error.name = name;
3264
4716
  if (code !== void 0) error.code = code;
3265
4717
  return error;
3266
4718
  }
4719
+ function ignoreRejection3() {
4720
+ }
4721
+ function observed(helper) {
4722
+ return (...args) => {
4723
+ const result = helper(...args);
4724
+ result.then(void 0, ignoreRejection3);
4725
+ return result;
4726
+ };
4727
+ }
3267
4728
  function frozenRecord2(members) {
3268
4729
  const record = /* @__PURE__ */ Object.create(null);
3269
4730
  for (const key of Object.keys(members)) record[key] = members[key];
@@ -3330,15 +4791,20 @@ var InterpreterAdapter = class {
3330
4791
  const allocationLimit = typeof memoryLimit === "number" && memoryLimit > 0 ? Math.min(memoryLimit, adapterLimit) : adapterLimit;
3331
4792
  const tracker = new MemoryTracker({ memoryLimit: Number.isFinite(allocationLimit) ? allocationLimit : 0 });
3332
4793
  const charge = (bytes) => tracker.track(bytes);
4794
+ let chargeForHelper = (_bytes) => {
4795
+ throw sandboxError("The interpreter is not running");
4796
+ };
4797
+ const timeout = context.config.timeout;
4798
+ const deadlineAt = timeout && timeout > 0 ? Date.now() + timeout : void 0;
3333
4799
  let interpreter;
4800
+ const callbacks = {
4801
+ call: () => {
4802
+ throw sandboxError("The interpreter is not running");
4803
+ }
4804
+ };
3334
4805
  try {
3335
4806
  const safe = createSafeGlobals();
3336
- const callbacks = {
3337
- call: () => {
3338
- throw sandboxError("The interpreter is not running");
3339
- }
3340
- };
3341
- const runtime = this.runtimeGlobals(context, charge, callbacks);
4807
+ const runtime = this.runtimeGlobals(context, (bytes) => chargeForHelper(bytes), callbacks);
3342
4808
  for (const name of Object.keys(runtime)) {
3343
4809
  if (!Object.prototype.hasOwnProperty.call(safe.globals, name)) safe.globals[name] = runtime[name];
3344
4810
  }
@@ -3350,37 +4816,40 @@ var InterpreterAdapter = class {
3350
4816
  maxCallDepth: this.options.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH,
3351
4817
  maxPendingCalls: this.options.maxPendingCalls,
3352
4818
  signal: context.abortController.signal,
4819
+ deadline: deadlineAt,
3353
4820
  charge
3354
4821
  });
3355
- const running = interpreter;
3356
- callbacks.call = (fn, args) => running.call(fn, args);
4822
+ const running2 = interpreter;
4823
+ callbacks.call = (fn, args) => running2.call(fn, args);
4824
+ callbacks.countBigInt = (value) => running2.countBigInt(value);
4825
+ chargeForHelper = (bytes) => running2.chargeAllocation(bytes);
3357
4826
  } catch (error) {
3358
4827
  return this.fail(error, startTime, stats.toolCallCount, 0, sanitizeStacks);
3359
4828
  }
3360
- const timeout = context.config.timeout;
3361
4829
  const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
3362
4830
  let timeoutHandle;
3363
4831
  const TIMED_OUT = /* @__PURE__ */ Symbol("timeout");
3364
4832
  const deadline = timeout && timeout > 0 ? new Promise((resolve) => {
3365
4833
  timeoutHandle = setTimeout(() => resolve(TIMED_OUT), timeout);
3366
4834
  }) : void 0;
4835
+ const running = interpreter;
4836
+ const timedOut = () => this.fail(
4837
+ new Error(`Execution timed out after ${timeout}ms`),
4838
+ startTime,
4839
+ stats.toolCallCount,
4840
+ running.stepCount,
4841
+ sanitizeStacks,
4842
+ "TimeoutError",
4843
+ "EXECUTION_TIMEOUT"
4844
+ );
3367
4845
  try {
3368
4846
  const run = interpreter.run(program);
3369
4847
  run.catch(() => void 0);
3370
4848
  const outcome = deadline ? await Promise.race([run, deadline]) : await run;
3371
- if (outcome === TIMED_OUT) {
3372
- return this.fail(
3373
- new Error(`Execution timed out after ${timeout}ms`),
3374
- startTime,
3375
- stats.toolCallCount,
3376
- interpreter.stepCount,
3377
- sanitizeStacks,
3378
- "TimeoutError",
3379
- "EXECUTION_TIMEOUT"
3380
- );
3381
- }
4849
+ if (outcome === TIMED_OUT) return timedOut();
3382
4850
  return this.succeed(outcome, context, startTime, stats.toolCallCount, interpreter.stepCount);
3383
4851
  } catch (error) {
4852
+ if (error instanceof DeadlineError) return timedOut();
3384
4853
  const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
3385
4854
  return this.fail(
3386
4855
  error,
@@ -3394,6 +4863,7 @@ var InterpreterAdapter = class {
3394
4863
  } finally {
3395
4864
  if (timer) clearTimeout(timer);
3396
4865
  if (timeoutHandle) clearTimeout(timeoutHandle);
4866
+ callbacks.over = true;
3397
4867
  interpreter.stop();
3398
4868
  }
3399
4869
  }
@@ -3405,7 +4875,7 @@ var InterpreterAdapter = class {
3405
4875
  */
3406
4876
  runtimeGlobals(context, charge, callbacks) {
3407
4877
  const { config } = context;
3408
- const callTool = this.createCallTool(context);
4878
+ const callTool = observed(this.createCallTool(context, callbacks, charge));
3409
4879
  const resolver = context.sidecar && context.referenceConfig ? new ReferenceResolver(context.sidecar, context.referenceConfig) : void 0;
3410
4880
  const joinReferences = (parts) => {
3411
4881
  if (!resolver) {
@@ -3423,6 +4893,8 @@ var InterpreterAdapter = class {
3423
4893
  const result = left + right;
3424
4894
  if (typeof result === "string") {
3425
4895
  charge((result.length - (typeof left === "string" ? left.length : 0)) * 2);
4896
+ } else if (typeof result === "bigint") {
4897
+ callbacks.countBigInt?.(result);
3426
4898
  }
3427
4899
  return result;
3428
4900
  };
@@ -3430,12 +4902,20 @@ var InterpreterAdapter = class {
3430
4902
  if (!Array.isArray(quasis)) throw sandboxError("Template pieces must be an array", "TypeError");
3431
4903
  const parts = [];
3432
4904
  let hasReference = false;
4905
+ let length = 0;
4906
+ const add = (part) => {
4907
+ length += part.length;
4908
+ if (length > MAX_JOIN_LENGTH) {
4909
+ throw sandboxError(`A template literal cannot produce more than ${MAX_JOIN_LENGTH} chars`, "RangeError");
4910
+ }
4911
+ parts.push(part);
4912
+ };
3433
4913
  for (let i = 0; i < quasis.length; i++) {
3434
- parts.push(String(quasis[i]));
4914
+ add(String(quasis[i]));
3435
4915
  if (i < values.length) {
3436
4916
  const value = values[i];
3437
4917
  if (typeof value === "string" && isReferenceId(value)) hasReference = true;
3438
- parts.push(String(value));
4918
+ add(String(value));
3439
4919
  }
3440
4920
  }
3441
4921
  if (hasReference) return joinReferences(parts.filter((part) => part !== ""));
@@ -3457,7 +4937,7 @@ var InterpreterAdapter = class {
3457
4937
  yield item;
3458
4938
  }
3459
4939
  }
3460
- const parallel = async (first, second) => {
4940
+ const parallel = observed(async (first, second) => {
3461
4941
  let tasks;
3462
4942
  if (typeof second === "function") {
3463
4943
  if (!Array.isArray(first)) throw sandboxError("parallel requires an array of items", "TypeError");
@@ -3477,12 +4957,24 @@ var InterpreterAdapter = class {
3477
4957
  const settled = await Promise.allSettled(tasks.map(async (task) => task()));
3478
4958
  const failures = settled.filter((result) => result.status === "rejected");
3479
4959
  if (failures.length > 0) {
3480
- const messages = failures.map((failure) => this.describe(failure.reason).message).join("\n");
3481
- throw sandboxError(`${failures.length} of ${tasks.length} parallel operations failed:
3482
- ${messages}`);
4960
+ let messages = "";
4961
+ let listed = 0;
4962
+ for (const failure of failures) {
4963
+ const room = MAX_THROWN_MESSAGE_LENGTH - messages.length - (listed === 0 ? 0 : 1);
4964
+ if (room <= 0) break;
4965
+ const message = this.describe(failure.reason).message;
4966
+ messages += (listed === 0 ? "" : "\n") + (message.length > room ? message.slice(0, room) : message);
4967
+ listed++;
4968
+ }
4969
+ const unlisted = failures.length - listed;
4970
+ throw sandboxError(
4971
+ `${failures.length} of ${tasks.length} parallel operations failed:
4972
+ ${messages}` + (unlisted > 0 ? `
4973
+ (${unlisted} more not shown)` : "")
4974
+ );
3483
4975
  }
3484
4976
  return settled.map((result) => result.value);
3485
- };
4977
+ });
3486
4978
  const globals = {
3487
4979
  __safe_callTool: callTool,
3488
4980
  __safe_concat: concat,
@@ -3500,19 +4992,23 @@ ${messages}`);
3500
4992
  let consoleCalls = 0;
3501
4993
  let consoleLength = 0;
3502
4994
  const write = (level) => (...args) => {
4995
+ if (callbacks.over) throw executionOver();
3503
4996
  consoleCalls++;
3504
4997
  if (consoleCalls > maxConsoleCalls) {
3505
4998
  throw sandboxError(
3506
4999
  `Console call limit exceeded (max: ${maxConsoleCalls}). This limit prevents I/O flood attacks.`
3507
5000
  );
3508
5001
  }
5002
+ const outputLimit = () => sandboxError(
5003
+ `Console output size limit exceeded (max: ${maxConsoleOutputBytes} bytes). This limit prevents I/O flood attacks.`
5004
+ );
5005
+ const room = (maxConsoleOutputBytes - consoleLength) * 16 + 64 * 1024;
5006
+ for (const arg of args) {
5007
+ if (arg !== null && typeof arg === "object" && certainlyLargerThan(arg, room)) throw outputLimit();
5008
+ }
3509
5009
  const line = args.map(consoleText).join(" ");
3510
5010
  consoleLength += line.length;
3511
- if (consoleLength > maxConsoleOutputBytes) {
3512
- throw sandboxError(
3513
- `Console output size limit exceeded (max: ${maxConsoleOutputBytes} bytes). This limit prevents I/O flood attacks.`
3514
- );
3515
- }
5011
+ if (consoleLength > maxConsoleOutputBytes) throw outputLimit();
3516
5012
  sink(level, line);
3517
5013
  };
3518
5014
  globals["__safe_console"] = frozenRecord2({
@@ -3525,16 +5021,88 @@ ${messages}`);
3525
5021
  for (const namespace of context.toolNamespaces ?? []) {
3526
5022
  const methods = {};
3527
5023
  for (const method of namespace.methods) {
3528
- if (isBlockedKey(method.name)) continue;
5024
+ if (isBlockedKey(method.name) || isEngineCalledKey(method.name)) continue;
3529
5025
  methods[method.name] = (args, options) => callTool(method.toolName, args === void 0 ? {} : args, options);
3530
5026
  }
3531
5027
  globals[namespace.name] = frozenRecord2(methods);
3532
5028
  }
3533
5029
  const custom = config.globals;
3534
5030
  if (custom && typeof custom === "object") {
5031
+ const maxGlobalCalls = config.maxGlobalFunctionCalls ?? Math.max(10, config.maxToolCalls * 10);
5032
+ const payloadLimit = config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_TOOL_PAYLOAD_BYTES;
5033
+ let globalCalls = 0;
5034
+ const serialize = (value) => {
5035
+ const sanitized = sanitizeValue(value, {
5036
+ maxDepth: config.maxSanitizeDepth,
5037
+ maxProperties: config.maxSanitizeProperties,
5038
+ allowDates: false,
5039
+ allowErrors: true
5040
+ });
5041
+ const json = stringifyWithin(sanitized, payloadLimit);
5042
+ if (json === void 0) return void 0;
5043
+ if (utf8Length2(json) > payloadLimit) throw sandboxError("Global function value exceeds bridge limit");
5044
+ return json;
5045
+ };
5046
+ const copy = (value) => {
5047
+ const json = serialize(value);
5048
+ return json === void 0 ? void 0 : JSON.parse(json);
5049
+ };
5050
+ const safeHostCall = (name, fn) => (...args) => {
5051
+ if (callbacks.over || context.aborted) throw executionOver();
5052
+ if (++globalCalls > maxGlobalCalls)
5053
+ throw sandboxError(`Global function call limit exceeded (${maxGlobalCalls})`);
5054
+ if (context.beforeGlobalCall && context.beforeGlobalCall() !== true) {
5055
+ throw sandboxError("Global function policy refused the call");
5056
+ }
5057
+ let safeArgs;
5058
+ try {
5059
+ safeArgs = copy(args);
5060
+ } catch {
5061
+ throw sandboxError(`Global function ${name} received unsupported arguments`, "TypeError");
5062
+ }
5063
+ let outcome;
5064
+ try {
5065
+ outcome = fn(...safeArgs);
5066
+ } catch {
5067
+ throw sandboxError("Global function failed");
5068
+ }
5069
+ const settle = (value) => {
5070
+ if (callbacks.over || context.aborted) throw executionOver();
5071
+ let json;
5072
+ try {
5073
+ json = serialize(value);
5074
+ } catch {
5075
+ throw sandboxError(`Global function ${name} returned an unsupported value`);
5076
+ }
5077
+ if (json === void 0) return void 0;
5078
+ if (value !== null && typeof value === "object") charge(Math.max(json.length * 2, utf8Length2(json)));
5079
+ return JSON.parse(json);
5080
+ };
5081
+ if (outcome !== null && (typeof outcome === "object" || typeof outcome === "function")) {
5082
+ let then;
5083
+ try {
5084
+ then = outcome.then;
5085
+ } catch {
5086
+ throw sandboxError(`Global function ${name} returned an unsupported value`);
5087
+ }
5088
+ if (typeof then === "function") {
5089
+ return observed(async () => {
5090
+ let value;
5091
+ try {
5092
+ value = await Promise.resolve(outcome);
5093
+ } catch {
5094
+ throw sandboxError("Global function failed");
5095
+ }
5096
+ return settle(value);
5097
+ })();
5098
+ }
5099
+ }
5100
+ return settle(outcome);
5101
+ };
3535
5102
  for (const name of Object.keys(custom)) {
3536
5103
  if (name.startsWith("__") || Object.prototype.hasOwnProperty.call(globals, name)) continue;
3537
- globals[name] = frozenDataCopy(name, custom[name]);
5104
+ const value = custom[name];
5105
+ globals[name] = typeof value === "function" ? safeHostCall(name, value) : frozenDataCopy(name, value);
3538
5106
  }
3539
5107
  }
3540
5108
  return globals;
@@ -3544,11 +5112,13 @@ ${messages}`);
3544
5112
  * and the response cross as JSON, so the handler never receives a value of the script and the
3545
5113
  * script never receives an object of the handler.
3546
5114
  */
3547
- createCallTool(context) {
5115
+ createCallTool(context, execution, charge) {
3548
5116
  const configured = context.config.toolHandler;
3549
5117
  const bridgeContext = context.toolHandler === void 0 && typeof configured === "function" ? Object.create(context, { toolHandler: { value: configured } }) : context;
3550
5118
  const bridge = createHostToolBridge(bridgeContext, { updateStats: true });
5119
+ const maxPayloadBytes = context.config.toolBridge?.maxPayloadBytes ?? DEFAULT_MAX_TOOL_PAYLOAD_BYTES;
3551
5120
  return async (toolName, args, options) => {
5121
+ if (execution.over) throw executionOver();
3552
5122
  let throwOnError = true;
3553
5123
  if (options !== void 0 && options !== null) {
3554
5124
  if (typeof options !== "object") throw sandboxError("callTool options must be an object", "TypeError");
@@ -3560,15 +5130,33 @@ ${messages}`);
3560
5130
  if (typeof args !== "object" || args === null || Array.isArray(args)) {
3561
5131
  throw sandboxError("Tool arguments must be an object", "TypeError");
3562
5132
  }
5133
+ if (certainlyLargerThan(args, maxPayloadBytes * 2 + 1024)) {
5134
+ throw sandboxError(
5135
+ `Tool request exceeds maximum size (${maxPayloadBytes} bytes)`,
5136
+ "ToolBridgeError",
5137
+ "TOOL_BRIDGE_REQUEST_TOO_LARGE"
5138
+ );
5139
+ }
3563
5140
  let requestJson;
3564
5141
  try {
3565
5142
  requestJson = encodeToolBridgeRequest(toolName, args);
3566
5143
  } catch {
3567
5144
  throw sandboxError("Tool arguments must be JSON-serializable", "TypeError");
3568
5145
  }
5146
+ if (utf8Length2(requestJson) > maxPayloadBytes) {
5147
+ throw sandboxError(`Tool request exceeds maximum size (${maxPayloadBytes} bytes)`, "ToolBridgeError");
5148
+ }
5149
+ if (context.beforeToolCall) {
5150
+ const request = JSON.parse(requestJson);
5151
+ if (context.beforeToolCall(toolName, request.args) !== true) {
5152
+ throw sandboxError("Tool policy refused the call");
5153
+ }
5154
+ }
3569
5155
  let response;
5156
+ let responseJson;
3570
5157
  try {
3571
- response = JSON.parse(await bridge(requestJson));
5158
+ responseJson = await bridge(requestJson);
5159
+ response = JSON.parse(responseJson);
3572
5160
  } catch {
3573
5161
  throw sandboxError("Tool bridge returned invalid JSON");
3574
5162
  }
@@ -3577,6 +5165,15 @@ ${messages}`);
3577
5165
  }
3578
5166
  const reply = response;
3579
5167
  if (reply.ok === true) {
5168
+ try {
5169
+ charge(Math.max(responseJson.length * 2, utf8Length2(responseJson)));
5170
+ } catch (error) {
5171
+ try {
5172
+ context.onToolBridgeFailure?.();
5173
+ } catch {
5174
+ }
5175
+ throw error;
5176
+ }
3580
5177
  return throwOnError ? reply.value : { success: true, data: reply.value };
3581
5178
  }
3582
5179
  if (reply.ok === false && reply.error && typeof reply.error === "object") {
@@ -3663,10 +5260,985 @@ ${messages}`);
3663
5260
  return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };
3664
5261
  }
3665
5262
  };
5263
+
5264
+ // libs/core/src/portable-enclave.ts
5265
+ var import_ast = require("@enclave-vm/ast");
5266
+ var acorn3 = __toESM(require("acorn"));
5267
+ var import_astring = require("astring");
5268
+
5269
+ // libs/core/src/types.ts
5270
+ var SECURITY_LEVEL_CONFIGS = {
5271
+ /**
5272
+ * STRICT: Maximum security for untrusted code
5273
+ *
5274
+ * Use for:
5275
+ * - AI-generated code from external sources
5276
+ * - User-submitted scripts
5277
+ * - Untrusted third-party integrations
5278
+ *
5279
+ * Characteristics:
5280
+ * - Short timeout (5s)
5281
+ * - Low iteration limits (1000)
5282
+ * - Limited tool calls (10)
5283
+ * - Deep value sanitization
5284
+ * - Full stack trace sanitization
5285
+ */
5286
+ STRICT: {
5287
+ timeout: 5e3,
5288
+ maxIterations: 1e3,
5289
+ maxToolCalls: 10,
5290
+ maxSanitizeDepth: 5,
5291
+ maxSanitizeProperties: 50,
5292
+ sanitizeStackTraces: true,
5293
+ blockTimingAPIs: true,
5294
+ allowUnboundedLoops: false,
5295
+ unicodeSecurityCheck: true,
5296
+ allowFunctionsInGlobals: false,
5297
+ maxConsoleOutputBytes: 64 * 1024,
5298
+ // 64KB - prevent I/O flood attacks
5299
+ maxConsoleCalls: 100,
5300
+ secureProxy: {
5301
+ blockConstructor: true,
5302
+ blockPrototype: true,
5303
+ blockLegacyAccessors: true,
5304
+ proxyMaxDepth: 5,
5305
+ throwOnBlocked: true
5306
+ }
5307
+ },
5308
+ /**
5309
+ * SECURE: High security with more headroom
5310
+ *
5311
+ * Use for:
5312
+ * - AI-generated code from trusted models
5313
+ * - Internal automation scripts
5314
+ * - Controlled multi-tenant environments
5315
+ *
5316
+ * Characteristics:
5317
+ * - Moderate timeout (15s)
5318
+ * - Moderate iteration limits (5000)
5319
+ * - Moderate tool calls (50)
5320
+ * - Standard value sanitization
5321
+ * - Stack trace sanitization
5322
+ */
5323
+ SECURE: {
5324
+ timeout: 15e3,
5325
+ maxIterations: 5e3,
5326
+ maxToolCalls: 50,
5327
+ maxSanitizeDepth: 10,
5328
+ maxSanitizeProperties: 100,
5329
+ sanitizeStackTraces: true,
5330
+ blockTimingAPIs: false,
5331
+ allowUnboundedLoops: false,
5332
+ unicodeSecurityCheck: true,
5333
+ allowFunctionsInGlobals: false,
5334
+ maxConsoleOutputBytes: 256 * 1024,
5335
+ // 256KB
5336
+ maxConsoleCalls: 500,
5337
+ secureProxy: {
5338
+ blockConstructor: true,
5339
+ blockPrototype: true,
5340
+ blockLegacyAccessors: true,
5341
+ proxyMaxDepth: 10,
5342
+ throwOnBlocked: true
5343
+ }
5344
+ },
5345
+ /**
5346
+ * STANDARD: Balanced security and functionality (DEFAULT)
5347
+ *
5348
+ * Use for:
5349
+ * - Internal tools and scripts
5350
+ * - Development and testing
5351
+ * - Trusted environments
5352
+ *
5353
+ * Characteristics:
5354
+ * - Standard timeout (30s)
5355
+ * - Standard iteration limits (10000)
5356
+ * - Standard tool calls (100)
5357
+ * - Basic value sanitization
5358
+ * - Minimal stack trace sanitization
5359
+ */
5360
+ STANDARD: {
5361
+ timeout: 3e4,
5362
+ maxIterations: 1e4,
5363
+ maxToolCalls: 100,
5364
+ maxSanitizeDepth: 20,
5365
+ maxSanitizeProperties: 500,
5366
+ sanitizeStackTraces: false,
5367
+ blockTimingAPIs: false,
5368
+ allowUnboundedLoops: true,
5369
+ unicodeSecurityCheck: false,
5370
+ allowFunctionsInGlobals: false,
5371
+ maxConsoleOutputBytes: 1024 * 1024,
5372
+ // 1MB
5373
+ maxConsoleCalls: 1e3,
5374
+ secureProxy: {
5375
+ blockConstructor: true,
5376
+ blockPrototype: true,
5377
+ blockLegacyAccessors: true,
5378
+ proxyMaxDepth: 15,
5379
+ throwOnBlocked: true
5380
+ }
5381
+ },
5382
+ /**
5383
+ * PERMISSIVE: Minimal restrictions
5384
+ *
5385
+ * Use for:
5386
+ * - Local development only
5387
+ * - Debugging
5388
+ * - Performance testing
5389
+ *
5390
+ * WARNING: Not recommended for production use with untrusted code
5391
+ *
5392
+ * Characteristics:
5393
+ * - Long timeout (60s)
5394
+ * - High iteration limits (100000)
5395
+ * - High tool calls (1000)
5396
+ * - Minimal sanitization
5397
+ * - No stack trace sanitization
5398
+ * - All features enabled
5399
+ */
5400
+ PERMISSIVE: {
5401
+ timeout: 6e4,
5402
+ maxIterations: 1e5,
5403
+ maxToolCalls: 1e3,
5404
+ maxSanitizeDepth: 50,
5405
+ maxSanitizeProperties: 1e3,
5406
+ sanitizeStackTraces: false,
5407
+ blockTimingAPIs: false,
5408
+ allowUnboundedLoops: true,
5409
+ unicodeSecurityCheck: false,
5410
+ allowFunctionsInGlobals: true,
5411
+ maxConsoleOutputBytes: 10 * 1024 * 1024,
5412
+ // 10MB
5413
+ maxConsoleCalls: 1e4,
5414
+ secureProxy: {
5415
+ blockConstructor: false,
5416
+ // Allow constructor access for development/debugging
5417
+ blockPrototype: true,
5418
+ // Still block prototype for safety
5419
+ blockLegacyAccessors: true,
5420
+ proxyMaxDepth: 20,
5421
+ throwOnBlocked: false
5422
+ // Return undefined instead of throwing for development
5423
+ }
5424
+ }
5425
+ };
5426
+ var DEFAULT_DOUBLE_VM_CONFIG = {
5427
+ enabled: true,
5428
+ parentTimeoutBuffer: 1e3,
5429
+ parentValidation: {
5430
+ validateOperationNames: true,
5431
+ maxOperationsPerSecond: 100,
5432
+ blockSuspiciousSequences: true,
5433
+ rapidEnumerationThreshold: 30,
5434
+ rapidEnumerationOverrides: {},
5435
+ suspiciousPatterns: []
5436
+ // Default patterns added at runtime
5437
+ }
5438
+ };
5439
+
5440
+ // libs/core/src/enclave-options.ts
5441
+ var MAX_TIMEOUT_MS = 2147483647;
5442
+ function withoutUndefined(value) {
5443
+ const result = {};
5444
+ for (const key of Object.keys(value)) {
5445
+ const member = value[key];
5446
+ if (member !== void 0) result[key] = member;
5447
+ }
5448
+ return result;
5449
+ }
5450
+ function describe(value) {
5451
+ if (value === null) return "null";
5452
+ if (typeof value === "number") return String(value);
5453
+ if (Array.isArray(value)) return "an array";
5454
+ if (typeof value === "string") return "a string";
5455
+ return `a value of type ${typeof value}`;
5456
+ }
5457
+ function assertIntegerOption(name, value, min, max = Number.MAX_SAFE_INTEGER) {
5458
+ if (typeof value !== "number" || !Number.isInteger(value) || value < min || value > max) {
5459
+ const range = max === Number.MAX_SAFE_INTEGER ? `an integer of at least ${min}` : `an integer from ${min} to ${max}`;
5460
+ throw new TypeError(`${name} must be ${range}, got ${describe(value)}`);
5461
+ }
5462
+ }
5463
+ function assertFiniteNumberOption(name, value, min) {
5464
+ if (typeof value !== "number" || !Number.isFinite(value) || value < min) {
5465
+ throw new TypeError(`${name} must be a finite number of at least ${min}, got ${describe(value)}`);
5466
+ }
5467
+ }
5468
+ function assertBooleanOption(name, value) {
5469
+ if (typeof value !== "boolean") {
5470
+ throw new TypeError(`${name} must be true or false, got ${describe(value)}`);
5471
+ }
5472
+ }
5473
+ function assertSecurityLevel(value) {
5474
+ if (typeof value !== "string" || !Object.hasOwn(SECURITY_LEVEL_CONFIGS, value)) {
5475
+ throw new TypeError(
5476
+ `securityLevel must be one of ${Object.keys(SECURITY_LEVEL_CONFIGS).join(", ")}, got ${typeof value === "string" ? JSON.stringify(value.slice(0, 40)) : describe(value)}`
5477
+ );
5478
+ }
5479
+ }
5480
+ function isPlainRecord(value) {
5481
+ return typeof value === "object" && value !== null && !Array.isArray(value);
5482
+ }
5483
+ function assertRecordOption(name, value) {
5484
+ if (!isPlainRecord(value)) {
5485
+ throw new TypeError(`${name} must be an object, got ${describe(value)}`);
5486
+ }
5487
+ }
5488
+ function assertKnownKeys(name, value, known) {
5489
+ for (const key of Object.keys(value)) {
5490
+ if (!known.includes(key)) {
5491
+ throw new TypeError(`${name} has no option ${JSON.stringify(key.slice(0, 40))}`);
5492
+ }
5493
+ }
5494
+ }
5495
+ function isOneOf(values, value) {
5496
+ return typeof value === "string" && values.includes(value);
5497
+ }
5498
+ var PRE_SCAN_PRESETS = ["agentscript", "strict", "secure", "standard", "permissive"];
5499
+ var PRE_SCAN_INTEGERS = [
5500
+ "maxInputSize",
5501
+ "maxLineLength",
5502
+ "maxLines",
5503
+ "maxNestingDepth",
5504
+ "maxConsecutiveOperators",
5505
+ "maxRegexLength",
5506
+ "maxRegexCount",
5507
+ "maxStringLength",
5508
+ "maxTotalStringContent"
5509
+ ];
5510
+ var PRE_SCAN_BOOLEANS = ["unicodePreCheck", "blockBidiPatterns", "blockInvisibleChars"];
5511
+ var PRE_SCAN_REGEX_MODES = ["allow", "analyze", "block"];
5512
+ var PRE_SCAN_REGEX_ANALYSIS_LEVELS = ["catastrophic", "polynomial"];
5513
+ var INTEGER_OPTIONS = [
5514
+ // What a timer can hold (see MAX_TIMEOUT_MS)
5515
+ ["timeout", 1, MAX_TIMEOUT_MS],
5516
+ ["maxIterations", 1],
5517
+ ["maxToolCalls", 0],
5518
+ // 0: no memory limit
5519
+ ["memoryLimit", 0],
5520
+ ["maxSanitizeDepth", 1],
5521
+ ["maxSanitizeProperties", 1],
5522
+ ["maxConsoleOutputBytes", 0],
5523
+ ["maxConsoleCalls", 0]
5524
+ ];
5525
+ var BOOLEAN_OPTIONS = [
5526
+ "validate",
5527
+ "transform",
5528
+ "sanitizeStackTraces",
5529
+ "allowFunctionsInGlobals",
5530
+ "allowBuiltins"
5531
+ ];
5532
+ var SECURE_PROXY_BOOLEANS = ["blockConstructor", "blockPrototype", "blockLegacyAccessors", "throwOnBlocked"];
5533
+ var PARENT_VALIDATION_BOOLEANS = ["validateOperationNames", "blockSuspiciousSequences"];
5534
+ function normalizeEnclaveOptions(options) {
5535
+ if (!isPlainRecord(options)) {
5536
+ throw new TypeError(`Enclave options must be an object, got ${describe(options)}`);
5537
+ }
5538
+ const result = withoutUndefined(options);
5539
+ if (result.securityLevel !== void 0) assertSecurityLevel(result.securityLevel);
5540
+ for (const [name, min, max] of INTEGER_OPTIONS) {
5541
+ if (result[name] !== void 0) assertIntegerOption(name, result[name], min, max);
5542
+ }
5543
+ for (const name of BOOLEAN_OPTIONS) {
5544
+ if (result[name] !== void 0) assertBooleanOption(name, result[name]);
5545
+ }
5546
+ if (result.secureProxyConfig !== void 0) {
5547
+ assertRecordOption("secureProxyConfig", result.secureProxyConfig);
5548
+ const proxy = withoutUndefined(result.secureProxyConfig);
5549
+ for (const name of SECURE_PROXY_BOOLEANS) {
5550
+ if (proxy[name] !== void 0) assertBooleanOption(`secureProxyConfig.${name}`, proxy[name]);
5551
+ }
5552
+ if (proxy["proxyMaxDepth"] !== void 0) {
5553
+ assertIntegerOption("secureProxyConfig.proxyMaxDepth", proxy["proxyMaxDepth"], 1);
5554
+ }
5555
+ result.secureProxyConfig = proxy;
5556
+ }
5557
+ if (result.toolBridge !== void 0) {
5558
+ assertRecordOption("toolBridge", result.toolBridge);
5559
+ const bridge = withoutUndefined(result.toolBridge);
5560
+ if (bridge["acknowledgeInsecureDirect"] !== void 0) {
5561
+ assertBooleanOption("toolBridge.acknowledgeInsecureDirect", bridge["acknowledgeInsecureDirect"]);
5562
+ }
5563
+ result.toolBridge = bridge;
5564
+ }
5565
+ if (result.preScan !== void 0) {
5566
+ assertRecordOption("preScan", result.preScan);
5567
+ const preScan = withoutUndefined(result.preScan);
5568
+ assertKnownKeys("preScan", preScan, ["preset", "config"]);
5569
+ if (preScan["preset"] !== void 0 && !isOneOf(PRE_SCAN_PRESETS, preScan["preset"])) {
5570
+ throw new TypeError(
5571
+ `preScan.preset must be one of ${PRE_SCAN_PRESETS.join(", ")}, got ${describe(preScan["preset"])}`
5572
+ );
5573
+ }
5574
+ if (preScan["config"] !== void 0) {
5575
+ assertRecordOption("preScan.config", preScan["config"]);
5576
+ const config = withoutUndefined(preScan["config"]);
5577
+ assertKnownKeys("preScan.config", config, [
5578
+ ...PRE_SCAN_INTEGERS,
5579
+ ...PRE_SCAN_BOOLEANS,
5580
+ "regexMode",
5581
+ "regexAnalysisLevel"
5582
+ ]);
5583
+ for (const name of PRE_SCAN_INTEGERS) {
5584
+ if (config[name] !== void 0) assertIntegerOption(`preScan.config.${name}`, config[name], 0);
5585
+ }
5586
+ for (const name of PRE_SCAN_BOOLEANS) {
5587
+ if (config[name] !== void 0) assertBooleanOption(`preScan.config.${name}`, config[name]);
5588
+ }
5589
+ if (config["regexMode"] !== void 0 && !isOneOf(PRE_SCAN_REGEX_MODES, config["regexMode"])) {
5590
+ throw new TypeError(
5591
+ `preScan.config.regexMode must be one of ${PRE_SCAN_REGEX_MODES.join(", ")}, got ${describe(config["regexMode"])}`
5592
+ );
5593
+ }
5594
+ if (config["regexAnalysisLevel"] !== void 0 && !isOneOf(PRE_SCAN_REGEX_ANALYSIS_LEVELS, config["regexAnalysisLevel"])) {
5595
+ throw new TypeError(
5596
+ `preScan.config.regexAnalysisLevel must be one of ${PRE_SCAN_REGEX_ANALYSIS_LEVELS.join(", ")}, got ${describe(config["regexAnalysisLevel"])}`
5597
+ );
5598
+ }
5599
+ preScan["config"] = config;
5600
+ }
5601
+ result.preScan = preScan;
5602
+ }
5603
+ if (result.doubleVm !== void 0) {
5604
+ assertRecordOption("doubleVm", result.doubleVm);
5605
+ const doubleVm = withoutUndefined(result.doubleVm);
5606
+ if (doubleVm["enabled"] !== void 0) assertBooleanOption("doubleVm.enabled", doubleVm["enabled"]);
5607
+ if (doubleVm["parentTimeoutBuffer"] !== void 0) {
5608
+ assertIntegerOption("doubleVm.parentTimeoutBuffer", doubleVm["parentTimeoutBuffer"], 0, MAX_TIMEOUT_MS);
5609
+ }
5610
+ if (doubleVm["parentValidation"] !== void 0) {
5611
+ assertRecordOption("doubleVm.parentValidation", doubleVm["parentValidation"]);
5612
+ const validation = withoutUndefined(doubleVm["parentValidation"]);
5613
+ for (const name of PARENT_VALIDATION_BOOLEANS) {
5614
+ if (validation[name] !== void 0) {
5615
+ assertBooleanOption(`doubleVm.parentValidation.${name}`, validation[name]);
5616
+ }
5617
+ }
5618
+ if (validation["maxOperationsPerSecond"] !== void 0) {
5619
+ assertFiniteNumberOption(
5620
+ "doubleVm.parentValidation.maxOperationsPerSecond",
5621
+ validation["maxOperationsPerSecond"],
5622
+ 1
5623
+ );
5624
+ }
5625
+ if (validation["rapidEnumerationThreshold"] !== void 0) {
5626
+ assertIntegerOption(
5627
+ "doubleVm.parentValidation.rapidEnumerationThreshold",
5628
+ validation["rapidEnumerationThreshold"],
5629
+ 1
5630
+ );
5631
+ }
5632
+ if (validation["rapidEnumerationOverrides"] !== void 0) {
5633
+ assertRecordOption(
5634
+ "doubleVm.parentValidation.rapidEnumerationOverrides",
5635
+ validation["rapidEnumerationOverrides"]
5636
+ );
5637
+ for (const [operation, threshold] of Object.entries(validation["rapidEnumerationOverrides"])) {
5638
+ assertIntegerOption(
5639
+ `doubleVm.parentValidation.rapidEnumerationOverrides[${JSON.stringify(operation.slice(0, 40))}]`,
5640
+ threshold,
5641
+ 1
5642
+ );
5643
+ }
5644
+ }
5645
+ doubleVm["parentValidation"] = validation;
5646
+ }
5647
+ result.doubleVm = doubleVm;
5648
+ }
5649
+ return result;
5650
+ }
5651
+
5652
+ // libs/core/src/portable-globals.ts
5653
+ var MAX_GLOBAL_DEPTH = 10;
5654
+ var MAX_GLOBAL_PROPERTIES = 1e4;
5655
+ var IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/;
5656
+ var BLOCKED_KEYS2 = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
5657
+ function copyPortableGlobals(globals, allowFunctions, maxBytes) {
5658
+ const result = /* @__PURE__ */ Object.create(null);
5659
+ if (globals === void 0) return result;
5660
+ if (globals === null || typeof globals !== "object" || Array.isArray(globals)) {
5661
+ throw new TypeError("globals must be a record");
5662
+ }
5663
+ let properties = 0;
5664
+ let bytes = 0;
5665
+ const active = /* @__PURE__ */ new Set();
5666
+ const charge = (value) => {
5667
+ bytes += value.length * 6 + 8;
5668
+ if (bytes > maxBytes) throw new TypeError("globals exceed the portable bridge size limit");
5669
+ };
5670
+ const copy = (value, depth) => {
5671
+ if (depth > MAX_GLOBAL_DEPTH) throw new TypeError("globals exceed the portable depth limit");
5672
+ if (value === null || typeof value === "boolean") return value;
5673
+ if (typeof value === "string") {
5674
+ charge(value);
5675
+ return value;
5676
+ }
5677
+ if (typeof value === "number" && Number.isFinite(value)) return value;
5678
+ if (typeof value !== "object") throw new TypeError("portable globals must contain JSON data only");
5679
+ if (active.has(value)) throw new TypeError("portable globals cannot contain cycles");
5680
+ const array = Array.isArray(value);
5681
+ if (array && value.length > MAX_GLOBAL_PROPERTIES) {
5682
+ throw new TypeError("portable globals exceed the array length limit");
5683
+ }
5684
+ const prototype = Object.getPrototypeOf(value);
5685
+ if (array ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) {
5686
+ throw new TypeError("portable globals must contain plain records or arrays");
5687
+ }
5688
+ active.add(value);
5689
+ try {
5690
+ const destination = array ? [] : /* @__PURE__ */ Object.create(null);
5691
+ const keys = Reflect.ownKeys(value);
5692
+ if (array && keys.length - 1 !== value.length) {
5693
+ throw new TypeError("portable globals cannot contain sparse arrays");
5694
+ }
5695
+ for (const key of keys) {
5696
+ if (typeof key !== "string") throw new TypeError("portable globals cannot contain symbol properties");
5697
+ if (array && key === "length") continue;
5698
+ if (BLOCKED_KEYS2.has(key)) throw new TypeError("portable globals contain a blocked property");
5699
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
5700
+ if (!descriptor || !Object.hasOwn(descriptor, "value")) {
5701
+ throw new TypeError("portable globals cannot contain accessors");
5702
+ }
5703
+ if (++properties > MAX_GLOBAL_PROPERTIES) throw new TypeError("globals exceed the portable property limit");
5704
+ charge(key);
5705
+ if (array) {
5706
+ const index = Number(key);
5707
+ if (!Number.isSafeInteger(index) || index < 0 || index >= value.length || String(index) !== key) {
5708
+ throw new TypeError("portable global arrays cannot contain named properties");
5709
+ }
5710
+ destination[index] = copy(descriptor.value, depth + 1);
5711
+ } else {
5712
+ destination[key] = copy(descriptor.value, depth + 1);
5713
+ }
5714
+ }
5715
+ return destination;
5716
+ } finally {
5717
+ active.delete(value);
5718
+ }
5719
+ };
5720
+ for (const key of Reflect.ownKeys(globals)) {
5721
+ if (typeof key !== "string" || !IDENTIFIER.test(key) || BLOCKED_KEYS2.has(key) || key.startsWith("__")) {
5722
+ throw new TypeError("portable globals contain an invalid name");
5723
+ }
5724
+ const descriptor = Object.getOwnPropertyDescriptor(globals, key);
5725
+ if (!descriptor || !Object.hasOwn(descriptor, "value")) {
5726
+ throw new TypeError("portable globals cannot contain accessors");
5727
+ }
5728
+ if (++properties > MAX_GLOBAL_PROPERTIES) throw new TypeError("globals exceed the portable property limit");
5729
+ charge(key);
5730
+ if (typeof descriptor.value === "function") {
5731
+ if (!allowFunctions) throw new TypeError("portable host functions require allowFunctionsInGlobals");
5732
+ result[key] = descriptor.value;
5733
+ } else {
5734
+ result[key] = copy(descriptor.value, 0);
5735
+ }
5736
+ }
5737
+ return result;
5738
+ }
5739
+
5740
+ // libs/core/src/double-vm/suspicious-patterns.ts
5741
+ var EXFIL_LIST_SEND = {
5742
+ id: "EXFIL_LIST_SEND",
5743
+ description: "List/query followed by send/export (potential exfiltration)",
5744
+ detect: (operationName, _args, history) => {
5745
+ const recentQueries = history.filter(
5746
+ (h) => /list|query|get|fetch|read|search|find|select/i.test(h.operationName) && Date.now() - h.timestamp < 5e3
5747
+ );
5748
+ const isSendOperation = /send|export|post|write|upload|publish|emit|transmit|forward/i.test(operationName);
5749
+ return recentQueries.length > 0 && isSendOperation;
5750
+ }
5751
+ };
5752
+ var RAPID_ENUMERATION = {
5753
+ id: "RAPID_ENUMERATION",
5754
+ description: "Rapid enumeration of resources (same operation called too many times in 5s)",
5755
+ detect: (operationName, _args, history) => {
5756
+ const now = Date.now();
5757
+ const recentSameOperation = history.filter((h) => h.operationName === operationName && now - h.timestamp < 5e3);
5758
+ let threshold = 30;
5759
+ try {
5760
+ const localConfig = typeof validationConfig !== "undefined" ? validationConfig : null;
5761
+ if (localConfig) {
5762
+ const defaultThreshold = localConfig.rapidEnumerationThreshold ?? 30;
5763
+ const overrides = localConfig.rapidEnumerationOverrides ?? {};
5764
+ const override = Object.prototype.hasOwnProperty.call(overrides, operationName) ? overrides[operationName] : void 0;
5765
+ threshold = typeof override === "number" ? override : defaultThreshold;
5766
+ }
5767
+ } catch {
5768
+ threshold = 30;
5769
+ }
5770
+ return recentSameOperation.length > threshold;
5771
+ }
5772
+ };
5773
+ var CREDENTIAL_EXFIL = {
5774
+ id: "CREDENTIAL_EXFIL",
5775
+ description: "Credential access followed by external operation",
5776
+ detect: (operationName, _args, history) => {
5777
+ const recentCredentialAccess = history.filter(
5778
+ (h) => /secret|credential|password|token|key|auth|api[_-]?key/i.test(h.operationName) && Date.now() - h.timestamp < 1e4
5779
+ );
5780
+ const isExternalOperation = /http|api|external|webhook|slack|email|sms|notification/i.test(operationName);
5781
+ return recentCredentialAccess.length > 0 && isExternalOperation;
5782
+ }
5783
+ };
5784
+ var BULK_OPERATION = {
5785
+ id: "BULK_OPERATION",
5786
+ description: "Bulk/batch operation detected",
5787
+ detect: (operationName, args, _history) => {
5788
+ const isBulkOperation = /\b(bulk|batch|mass|dump)\b|export[_-]all\b/i.test(operationName);
5789
+ if (typeof args === "object" && args !== null) {
5790
+ try {
5791
+ const argStr = JSON.stringify(args).toLowerCase();
5792
+ const firstLimit = argStr.indexOf("limit");
5793
+ const hasBulkArgs = firstLimit >= 0 && /[0-9]{4}/.test(argStr.slice(firstLimit + 5)) || argStr.indexOf('"*"') >= 0 || argStr.indexOf("nolimit") >= 0 || argStr.indexOf("no_limit") >= 0 || argStr.indexOf("no-limit") >= 0;
5794
+ if (hasBulkArgs) return true;
5795
+ } catch {
5796
+ }
5797
+ }
5798
+ return isBulkOperation;
5799
+ }
5800
+ };
5801
+ var DELETE_AFTER_ACCESS = {
5802
+ id: "DELETE_AFTER_ACCESS",
5803
+ description: "Delete operation after data access (potential cover-up)",
5804
+ detect: (operationName, _args, history) => {
5805
+ const isDeleteOperation = /delete|remove|destroy|purge|clear|wipe|erase/i.test(operationName);
5806
+ if (!isDeleteOperation) return false;
5807
+ const recentDataAccess = history.filter(
5808
+ (h) => /list|query|get|fetch|read|search|find|select/i.test(h.operationName) && Date.now() - h.timestamp < 3e4
5809
+ );
5810
+ return recentDataAccess.length > 0;
5811
+ }
5812
+ };
5813
+ var DEFAULT_SUSPICIOUS_PATTERNS = [
5814
+ EXFIL_LIST_SEND,
5815
+ RAPID_ENUMERATION,
5816
+ CREDENTIAL_EXFIL,
5817
+ BULK_OPERATION,
5818
+ DELETE_AFTER_ACCESS
5819
+ ];
5820
+
5821
+ // libs/core/src/dynamic-import.ts
5822
+ var acorn2 = __toESM(require("acorn"));
5823
+ var walk = __toESM(require("acorn-walk"));
5824
+ var DYNAMIC_IMPORT_MESSAGE = "Dynamic import() is not available in the sandbox";
5825
+ function refuseDynamicImport(code) {
5826
+ if (typeof code !== "string" || !code.includes("import")) {
5827
+ return void 0;
5828
+ }
5829
+ let ast;
5830
+ try {
5831
+ ast = acorn2.parse(code, {
5832
+ ecmaVersion: "latest",
5833
+ sourceType: "script",
5834
+ allowHashBang: true,
5835
+ allowReturnOutsideFunction: true,
5836
+ allowAwaitOutsideFunction: true
5837
+ });
5838
+ } catch {
5839
+ return `${DYNAMIC_IMPORT_MESSAGE} (the script contains the word "import" and could not be parsed to rule it out)`;
5840
+ }
5841
+ let found = false;
5842
+ try {
5843
+ walk.full(ast, (node) => {
5844
+ if (node.type === "ImportExpression") found = true;
5845
+ if (node.type === "MetaProperty" && node.meta?.name === "import") {
5846
+ found = true;
5847
+ }
5848
+ });
5849
+ } catch {
5850
+ return DYNAMIC_IMPORT_MESSAGE;
5851
+ }
5852
+ return found ? DYNAMIC_IMPORT_MESSAGE : void 0;
5853
+ }
5854
+
5855
+ // libs/core/src/portable-enclave.ts
5856
+ var MAX_SCRIPT_LENGTH = 5 * 1024 * 1024;
5857
+ var MAX_PORTABLE_ALLOCATION_BYTES = 64 * 1024 * 1024;
5858
+ var MAX_PORTABLE_STEPS = 2e7;
5859
+ var MAX_PORTABLE_PENDING_CALLS = 4096;
5860
+ var MAX_PORTABLE_CALL_DEPTH = 1024;
5861
+ var DEFAULT_BRIDGE_BYTES = 5 * 1024 * 1024;
5862
+ function boundedInteger(name, value, max) {
5863
+ if (value !== void 0 && (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > max)) {
5864
+ throw new TypeError(`${name} must be an integer from 1 to ${max}`);
5865
+ }
5866
+ }
5867
+ function referenceConfig(level, sidecar) {
5868
+ if (!sidecar?.enabled) return void 0;
5869
+ const base = REFERENCE_CONFIGS[level];
5870
+ return {
5871
+ maxTotalSize: sidecar.maxTotalSize ?? base.maxTotalSize,
5872
+ maxReferenceSize: sidecar.maxReferenceSize ?? base.maxReferenceSize,
5873
+ extractionThreshold: sidecar.extractionThreshold ?? base.extractionThreshold,
5874
+ maxResolvedSize: sidecar.maxResolvedSize ?? base.maxResolvedSize,
5875
+ maxTotalResolvedSize: sidecar.maxTotalResolvedSize ?? base.maxTotalResolvedSize,
5876
+ allowComposites: sidecar.allowComposites ?? base.allowComposites,
5877
+ maxReferenceCount: sidecar.maxReferenceCount ?? base.maxReferenceCount,
5878
+ maxResolutionDepth: base.maxResolutionDepth
5879
+ };
5880
+ }
5881
+ function validateReferenceConfig(config) {
5882
+ if (!config) return;
5883
+ for (const key of [
5884
+ "maxTotalSize",
5885
+ "maxReferenceSize",
5886
+ "extractionThreshold",
5887
+ "maxResolvedSize",
5888
+ "maxTotalResolvedSize",
5889
+ "maxReferenceCount",
5890
+ "maxResolutionDepth"
5891
+ ]) {
5892
+ const value = config[key];
5893
+ if (value !== void 0 && (!Number.isSafeInteger(value) || value <= 0)) {
5894
+ throw new TypeError(`sidecar.${key} must be a positive finite integer`);
5895
+ }
5896
+ }
5897
+ if (config.maxReferenceSize > config.maxTotalSize || config.extractionThreshold > config.maxReferenceSize) {
5898
+ throw new TypeError("sidecar size limits must be ordered: threshold <= reference <= total");
5899
+ }
5900
+ }
5901
+ var PortableOperationPolicy = class {
5902
+ constructor(config) {
5903
+ this.config = config;
5904
+ }
5905
+ history = [];
5906
+ globalCallTimes = [];
5907
+ rate(now) {
5908
+ while (this.history.length && now - this.history[0].timestamp > 6e4) this.history.shift();
5909
+ while (this.globalCallTimes.length && now - this.globalCallTimes[0] > 2e3) this.globalCallTimes.shift();
5910
+ const recentTools = this.history.filter((entry) => now - entry.timestamp < 1e3).length;
5911
+ const recentGlobals = this.globalCallTimes.filter((at) => now - at < 1e3).length;
5912
+ if (recentTools + recentGlobals >= this.config.maxOperationsPerSecond) {
5913
+ throw new Error(`Operation rate limit exceeded (${this.config.maxOperationsPerSecond} operations/second)`);
5914
+ }
5915
+ }
5916
+ globalCall() {
5917
+ const now = Date.now();
5918
+ this.rate(now);
5919
+ this.globalCallTimes.push(now);
5920
+ }
5921
+ toolCall(name, args) {
5922
+ const now = Date.now();
5923
+ this.rate(now);
5924
+ if (typeof name !== "string" || name.length === 0) throw new TypeError("Operation name must be a non-empty string");
5925
+ if (this.config.validateOperationNames) {
5926
+ const allowed = this.config.allowedOperationPattern;
5927
+ if (allowed) {
5928
+ allowed.lastIndex = 0;
5929
+ if (!allowed.test(name)) throw new Error(`Operation "${name}" does not match allowed pattern`);
5930
+ }
5931
+ for (const blocked of this.config.blockedOperationPatterns ?? []) {
5932
+ blocked.lastIndex = 0;
5933
+ if (blocked.test(name)) throw new Error(`Operation "${name}" matches blocked pattern`);
5934
+ }
5935
+ }
5936
+ if (this.config.blockSuspiciousSequences) {
5937
+ const override = Object.hasOwn(this.config.rapidEnumerationOverrides, name) ? this.config.rapidEnumerationOverrides[name] : void 0;
5938
+ const threshold = override ?? this.config.rapidEnumerationThreshold;
5939
+ const recentSame = this.history.filter((entry) => entry.operationName === name && now - entry.timestamp < 5e3);
5940
+ if (recentSame.length >= threshold) {
5941
+ throw new Error("Suspicious pattern detected: Rapid enumeration of resources [RAPID_ENUMERATION]");
5942
+ }
5943
+ for (const pattern of DEFAULT_SUSPICIOUS_PATTERNS) {
5944
+ if (pattern.id === "RAPID_ENUMERATION") continue;
5945
+ let detected = false;
5946
+ try {
5947
+ detected = pattern.detect(name, args, this.history);
5948
+ } catch {
5949
+ }
5950
+ if (detected) throw new Error(`Suspicious pattern detected: ${pattern.description} [${pattern.id}]`);
5951
+ }
5952
+ }
5953
+ this.history.push({ operationName: name, timestamp: now, argKeys: Object.keys(args) });
5954
+ }
5955
+ };
5956
+ var PortableEnclave = class {
5957
+ options;
5958
+ config;
5959
+ preScanner;
5960
+ validator;
5961
+ adapter;
5962
+ namespaces;
5963
+ references;
5964
+ policyConfig;
5965
+ customNames;
5966
+ disposed = false;
5967
+ constructor(rawOptions = {}) {
5968
+ const { interpreter, ...rawEnclaveOptions } = rawOptions;
5969
+ const options = normalizeEnclaveOptions(rawEnclaveOptions);
5970
+ const level = options.securityLevel ?? "STANDARD";
5971
+ if (level === "PERMISSIVE") throw new TypeError("Portable AgentScript requires STANDARD, SECURE or STRICT");
5972
+ if (options.preset !== void 0 && options.preset !== "agentscript") {
5973
+ throw new TypeError("PortableEnclave supports the AgentScript preset only");
5974
+ }
5975
+ if (options.validate === false || options.transform === false) {
5976
+ throw new TypeError("PortableEnclave requires validation, transformation and pre-scan");
5977
+ }
5978
+ if (options.preScan?.preset !== void 0 && options.preScan.preset !== "agentscript") {
5979
+ throw new TypeError("PortableEnclave requires the AgentScript pre-scan preset");
5980
+ }
5981
+ if (options.preScan?.config !== void 0) {
5982
+ throw new TypeError("PortableEnclave does not allow pre-scan overrides");
5983
+ }
5984
+ if (options.toolBridge?.mode === "direct") throw new TypeError("PortableEnclave requires the string tool bridge");
5985
+ if (options.toolBridge?.acknowledgeInsecureDirect === true) {
5986
+ throw new TypeError("PortableEnclave does not support direct bridge acknowledgement");
5987
+ }
5988
+ if (options.adapter || options.sandboxAdapter || options.workerPoolConfig || options.scoringGate) {
5989
+ throw new TypeError("PortableEnclave does not support VM adapters or scoring gates");
5990
+ }
5991
+ if (options.allowBuiltins === true || options.toolCallGraceMs !== void 0) {
5992
+ throw new TypeError("PortableEnclave does not support VM builtin or tool grace overrides");
5993
+ }
5994
+ if (options.secureProxyConfig || options.realmGlobals === "security-level") {
5995
+ throw new TypeError("PortableEnclave does not support VM realm proxy overrides");
5996
+ }
5997
+ if (options.doubleVm?.enabled === false || options.doubleVm?.parentTimeoutBuffer !== void 0 || options.doubleVm?.parentValidation?.suspiciousPatterns?.length) {
5998
+ throw new TypeError("PortableEnclave cannot disable or replace its tool policy");
5999
+ }
6000
+ boundedInteger("interpreter.maxSteps", interpreter?.maxSteps, MAX_PORTABLE_STEPS);
6001
+ boundedInteger("interpreter.maxCallDepth", interpreter?.maxCallDepth, MAX_PORTABLE_CALL_DEPTH);
6002
+ boundedInteger("interpreter.maxPendingCalls", interpreter?.maxPendingCalls, MAX_PORTABLE_PENDING_CALLS);
6003
+ boundedInteger("interpreter.maxAllocationBytes", interpreter?.maxAllocationBytes, MAX_PORTABLE_ALLOCATION_BYTES);
6004
+ const memoryLimit = options.memoryLimit ?? 1024 * 1024;
6005
+ boundedInteger("memoryLimit", memoryLimit, MAX_PORTABLE_ALLOCATION_BYTES);
6006
+ const maxPayloadBytes = options.toolBridge?.maxPayloadBytes ?? DEFAULT_BRIDGE_BYTES;
6007
+ boundedInteger("toolBridge.maxPayloadBytes", maxPayloadBytes, MAX_PORTABLE_ALLOCATION_BYTES);
6008
+ const security = SECURITY_LEVEL_CONFIGS[level];
6009
+ const maxToolCalls = options.maxToolCalls ?? security.maxToolCalls;
6010
+ if (maxToolCalls > 1e5) throw new TypeError("maxToolCalls cannot exceed 100000 in PortableEnclave");
6011
+ if ((options.maxIterations ?? security.maxIterations) > MAX_PORTABLE_STEPS) {
6012
+ throw new TypeError(`maxIterations cannot exceed ${MAX_PORTABLE_STEPS} in PortableEnclave`);
6013
+ }
6014
+ if ((options.maxSanitizeDepth ?? security.maxSanitizeDepth) > 100) {
6015
+ throw new TypeError("maxSanitizeDepth cannot exceed 100 in PortableEnclave");
6016
+ }
6017
+ if ((options.maxSanitizeProperties ?? security.maxSanitizeProperties) > 2e4) {
6018
+ throw new TypeError("maxSanitizeProperties cannot exceed 20000 in PortableEnclave");
6019
+ }
6020
+ const maxGlobalFunctionCalls = options.maxGlobalFunctionCalls ?? Math.max(10, maxToolCalls * 10);
6021
+ boundedInteger("maxGlobalFunctionCalls", maxGlobalFunctionCalls, 1e6);
6022
+ options.globals = copyPortableGlobals(options.globals, options.allowFunctionsInGlobals === true, maxPayloadBytes);
6023
+ const standardNames = /* @__PURE__ */ new Set([...Object.keys(createSafeGlobals().globals), "callTool", "parallel", "console"]);
6024
+ for (const name of Object.keys(options.globals)) {
6025
+ if (standardNames.has(name)) throw new TypeError(`PortableEnclave cannot replace standard global ${name}`);
6026
+ }
6027
+ this.namespaces = (0, import_ast.normalizeToolNamespaces)(options.toolNamespaces, {
6028
+ reservedNames: Object.keys(options.globals ?? {})
6029
+ });
6030
+ this.customNames = [...Object.keys(options.globals ?? {}), ...this.namespaces.map((entry) => entry.name)];
6031
+ const allowed = [
6032
+ ...(0, import_ast.getAgentScriptGlobals)(level),
6033
+ "parallel",
6034
+ "__safe_parallel",
6035
+ "__safe_concat",
6036
+ "__safe_template",
6037
+ ...options.consoleHandler ? ["console", "__safe_console"] : [],
6038
+ ...this.customNames.flatMap((name) => [name, `__safe_${name}`])
6039
+ ];
6040
+ const hostObjects = [
6041
+ ...Object.keys(options.globals ?? {}).filter((name) => typeof options.globals?.[name] !== "string"),
6042
+ ...this.namespaces.map((entry) => entry.name)
6043
+ ];
6044
+ this.preScanner = new import_ast.PreScanner({
6045
+ preset: options.preScan?.preset ?? "agentscript",
6046
+ config: options.preScan?.config
6047
+ });
6048
+ this.validator = new import_ast.JSAstValidator(
6049
+ (0, import_ast.createAgentScriptPreset)({
6050
+ securityLevel: level,
6051
+ allowedGlobals: allowed,
6052
+ hostObjectGlobals: hostObjects,
6053
+ allowDynamicArrayFill: true
6054
+ })
6055
+ );
6056
+ this.references = referenceConfig(level, options.sidecar);
6057
+ validateReferenceConfig(this.references);
6058
+ this.policyConfig = {
6059
+ ...DEFAULT_DOUBLE_VM_CONFIG.parentValidation,
6060
+ ...options.doubleVm?.parentValidation,
6061
+ rapidEnumerationOverrides: { ...options.doubleVm?.parentValidation?.rapidEnumerationOverrides },
6062
+ blockedOperationPatterns: [...options.doubleVm?.parentValidation?.blockedOperationPatterns ?? []],
6063
+ suspiciousPatterns: []
6064
+ };
6065
+ this.config = {
6066
+ timeout: options.timeout ?? security.timeout,
6067
+ maxIterations: options.maxIterations ?? security.maxIterations,
6068
+ maxToolCalls,
6069
+ memoryLimit,
6070
+ maxSanitizeDepth: options.maxSanitizeDepth ?? security.maxSanitizeDepth,
6071
+ maxSanitizeProperties: options.maxSanitizeProperties ?? security.maxSanitizeProperties,
6072
+ maxConsoleCalls: options.maxConsoleCalls ?? security.maxConsoleCalls,
6073
+ maxConsoleOutputBytes: options.maxConsoleOutputBytes ?? security.maxConsoleOutputBytes,
6074
+ sanitizeStackTraces: options.sanitizeStackTraces ?? true,
6075
+ maxGlobalFunctionCalls,
6076
+ toolBridge: { mode: "string", maxPayloadBytes },
6077
+ globals: options.globals ?? {},
6078
+ toolHandler: options.toolHandler
6079
+ };
6080
+ this.adapter = new InterpreterAdapter({
6081
+ maxSteps: interpreter?.maxSteps,
6082
+ maxCallDepth: interpreter?.maxCallDepth,
6083
+ maxPendingCalls: interpreter?.maxPendingCalls,
6084
+ maxAllocationBytes: interpreter?.maxAllocationBytes
6085
+ });
6086
+ this.options = options;
6087
+ }
6088
+ async run(code, toolHandler, runOptions = {}) {
6089
+ if (this.disposed) throw new Error("PortableEnclave has been disposed");
6090
+ boundedInteger("maxToolResultBytes", runOptions.maxToolResultBytes, MAX_PORTABLE_ALLOCATION_BYTES);
6091
+ const startTime = Date.now();
6092
+ const stats = { duration: 0, startTime, endTime: startTime, toolCallCount: 0, iterationCount: 0 };
6093
+ const failure = (name, message, code2, issues) => ({
6094
+ success: false,
6095
+ error: { name, message, code: code2, ...issues ? { data: { issues } } : {} },
6096
+ stats: { ...stats, duration: Date.now() - startTime, endTime: Date.now() }
6097
+ });
6098
+ if (typeof code !== "string" || code.length > MAX_SCRIPT_LENGTH) {
6099
+ return failure("ValidationError", "The script must be a string of at most 5 MiB", "VALIDATION_ERROR");
6100
+ }
6101
+ if (code.length > 0) {
6102
+ const scanned = this.preScanner.scan(code);
6103
+ if (!scanned.success) {
6104
+ const issues = scanned.issues.map((issue) => ({
6105
+ code: issue.code,
6106
+ severity: issue.severity === "error" ? import_ast.ValidationSeverity.ERROR : issue.severity === "warning" ? import_ast.ValidationSeverity.WARNING : import_ast.ValidationSeverity.INFO,
6107
+ message: issue.message,
6108
+ location: issue.line === void 0 ? void 0 : { line: issue.line, column: issue.column ?? 0 },
6109
+ data: issue.data
6110
+ }));
6111
+ return failure("ValidationError", "AgentScript pre-scan failed", "VALIDATION_ERROR", issues);
6112
+ }
6113
+ }
6114
+ let transformed;
6115
+ try {
6116
+ transformed = (0, import_ast.transformAgentScript)(code, {
6117
+ wrapInMain: !(0, import_ast.isWrappedInMain)(code),
6118
+ transformCallTool: true,
6119
+ transformLoops: true,
6120
+ maxIterations: this.config.maxIterations,
6121
+ additionalIdentifiers: this.customNames
6122
+ });
6123
+ } catch (error) {
6124
+ const message = error?.message;
6125
+ return failure(
6126
+ "ValidationError",
6127
+ typeof message === "string" ? message.slice(0, 2048) : "AgentScript parse failed",
6128
+ "VALIDATION_ERROR"
6129
+ );
6130
+ }
6131
+ const validation = await this.validator.validate(transformed, { preScan: { enabled: false } });
6132
+ if (!validation.valid) {
6133
+ return failure("ValidationError", "AgentScript validation failed", "VALIDATION_ERROR", validation.issues);
6134
+ }
6135
+ if (refuseDynamicImport(transformed)) {
6136
+ return failure("SecurityError", "Dynamic imports are unavailable", "SECURITY_VIOLATION");
6137
+ }
6138
+ const sidecar = this.references ? new ReferenceSidecar(this.references) : void 0;
6139
+ try {
6140
+ if (sidecar && this.references) {
6141
+ const ast = acorn3.parse(transformed, { ecmaVersion: "latest", sourceType: "script" });
6142
+ (0, import_ast.extractLargeStrings)(ast, {
6143
+ threshold: this.references.extractionThreshold,
6144
+ onExtract: (value) => sidecar.store(value, "extraction")
6145
+ });
6146
+ (0, import_ast.transformConcatenation)(ast, { arraySpread: false });
6147
+ (0, import_ast.transformTemplateLiterals)(ast);
6148
+ transformed = (0, import_astring.generate)(ast);
6149
+ }
6150
+ const policy = new PortableOperationPolicy(this.policyConfig);
6151
+ let closed = false;
6152
+ const deadline = Date.now() + this.config.timeout;
6153
+ const abortController = new AbortController();
6154
+ const context = {
6155
+ config: this.config,
6156
+ stats,
6157
+ abortController,
6158
+ get aborted() {
6159
+ return closed || abortController.signal.aborted || Date.now() >= deadline;
6160
+ },
6161
+ set aborted(value) {
6162
+ if (value) abortController.abort();
6163
+ },
6164
+ toolHandler: toolHandler ?? this.options.toolHandler,
6165
+ toolNamespaces: this.namespaces,
6166
+ beforeToolCall: (name, args) => {
6167
+ policy.toolCall(name, args);
6168
+ return true;
6169
+ },
6170
+ beforeGlobalCall: () => {
6171
+ policy.globalCall();
6172
+ return true;
6173
+ },
6174
+ maxToolResultBytes: runOptions.maxToolResultBytes,
6175
+ onToolBridgeFailure: runOptions.onToolBridgeFailure,
6176
+ sidecar,
6177
+ referenceConfig: this.references,
6178
+ consoleHandler: this.options.consoleHandler
6179
+ };
6180
+ try {
6181
+ return await this.adapter.execute(transformed, context);
6182
+ } finally {
6183
+ closed = true;
6184
+ abortController.abort();
6185
+ }
6186
+ } catch (error) {
6187
+ const message = error?.message;
6188
+ return failure(
6189
+ "ExecutionError",
6190
+ typeof message === "string" ? message.slice(0, 2048) : "Portable execution failed",
6191
+ "EXECUTION_ERROR"
6192
+ );
6193
+ } finally {
6194
+ sidecar?.dispose();
6195
+ }
6196
+ }
6197
+ dispose() {
6198
+ this.disposed = true;
6199
+ this.adapter.dispose();
6200
+ }
6201
+ };
6202
+ var AgentScriptRunner = class extends PortableEnclave {
6203
+ static capabilities = Object.freeze([
6204
+ "validated-agentscript",
6205
+ "host-functions",
6206
+ "tool-namespaces",
6207
+ "sidecar",
6208
+ "console",
6209
+ "rapid-enumeration"
6210
+ ]);
6211
+ constructor(options) {
6212
+ const {
6213
+ hostFunctions,
6214
+ maxHostFunctionCalls,
6215
+ maxSteps,
6216
+ maxCallDepth,
6217
+ maxPendingCalls,
6218
+ rapidEnumeration,
6219
+ ...enclaveOptions
6220
+ } = options;
6221
+ super({
6222
+ ...enclaveOptions,
6223
+ allowFunctionsInGlobals: true,
6224
+ globals: { ...hostFunctions },
6225
+ maxGlobalFunctionCalls: maxHostFunctionCalls,
6226
+ doubleVm: {
6227
+ parentValidation: {
6228
+ ...rapidEnumeration?.threshold !== void 0 && { rapidEnumerationThreshold: rapidEnumeration.threshold },
6229
+ ...rapidEnumeration?.overrides !== void 0 && { rapidEnumerationOverrides: rapidEnumeration.overrides }
6230
+ }
6231
+ },
6232
+ interpreter: { maxSteps, maxCallDepth, maxPendingCalls }
6233
+ });
6234
+ }
6235
+ };
3666
6236
  // Annotate the CommonJS export names for ESM import in node:
3667
6237
  0 && (module.exports = {
6238
+ AgentScriptRunner,
3668
6239
  Interpreter,
3669
6240
  InterpreterAdapter,
3670
6241
  InterpreterError,
6242
+ PortableEnclave,
3671
6243
  StepLimitError
3672
6244
  });