@enclave-vm/core 2.18.0 → 2.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/worker.js CHANGED
@@ -40,6 +40,101 @@ module.exports = __toCommonJS(worker_exports);
40
40
  // libs/core/src/adapters/interpreter-adapter.ts
41
41
  var acorn = __toESM(require("acorn"));
42
42
 
43
+ // libs/core/src/stack-reserve.ts
44
+ var ReflectApply = Reflect.apply;
45
+ var HOST_STACK_RESERVE_BYTES = 128 * 1024;
46
+ var SLOTS = [];
47
+ for (let slot = 0; slot < HOST_STACK_RESERVE_BYTES / 8; slot++) {
48
+ SLOTS[slot] = 0;
49
+ }
50
+ function nothing() {
51
+ }
52
+ function hasHostStackReserve() {
53
+ try {
54
+ ReflectApply(nothing, void 0, SLOTS);
55
+ return true;
56
+ } catch {
57
+ return false;
58
+ }
59
+ }
60
+
61
+ // libs/core/src/console-handler.ts
62
+ var CONSOLE_LEVELS = /* @__PURE__ */ new Set(["log", "info", "warn", "error", "debug"]);
63
+ var ignoreRejection = () => void 0;
64
+ function createConsoleSink(handler, limits) {
65
+ let callCount = 0;
66
+ let totalLength = 0;
67
+ return (level, message) => {
68
+ if (!CONSOLE_LEVELS.has(level) || typeof message !== "string") return;
69
+ callCount++;
70
+ totalLength += message.length;
71
+ if (callCount > limits.maxConsoleCalls || totalLength > limits.maxConsoleOutputBytes) return;
72
+ try {
73
+ if (!hasHostStackReserve()) return;
74
+ Promise.resolve(handler(level, message)).catch(ignoreRejection);
75
+ } catch {
76
+ }
77
+ };
78
+ }
79
+ var CONSOLE_FACTORY_SOURCE = `
80
+ (function () {
81
+ 'use strict';
82
+ var stringify = JSON.stringify;
83
+ // The realm's own String, even where a sandbox global shadows it.
84
+ var toText = ''.constructor;
85
+ var freeze = Object.freeze;
86
+ var RealmError = Error;
87
+
88
+ function formatArgument(value) {
89
+ if (value === undefined) return 'undefined';
90
+ if (value === null) return 'null';
91
+ if (typeof value === 'object') {
92
+ try {
93
+ var json = stringify(value);
94
+ return json === undefined ? '' : json;
95
+ } catch (e) {
96
+ return toText(value);
97
+ }
98
+ }
99
+ return toText(value);
100
+ }
101
+
102
+ return function install(write, maxCalls, maxBytes) {
103
+ var callCount = 0;
104
+ var totalBytes = 0;
105
+
106
+ function method(level) {
107
+ return (...args) => {
108
+ callCount++;
109
+ if (callCount > maxCalls) {
110
+ throw new RealmError('Console call limit exceeded (max: ' + maxCalls + '). This limit prevents I/O flood attacks.');
111
+ }
112
+ var line = '';
113
+ for (var i = 0; i < args.length; i++) {
114
+ line += (i === 0 ? '' : ' ') + formatArgument(args[i]);
115
+ }
116
+ totalBytes += line.length;
117
+ if (totalBytes > maxBytes) {
118
+ throw new RealmError('Console output size limit exceeded (max: ' + maxBytes + ' bytes). This limit prevents I/O flood attacks.');
119
+ }
120
+ try {
121
+ write(level, line);
122
+ } catch (e) {}
123
+ };
124
+ }
125
+
126
+ return freeze({
127
+ __proto__: null,
128
+ log: method('log'),
129
+ info: method('info'),
130
+ warn: method('warn'),
131
+ error: method('error'),
132
+ debug: method('debug')
133
+ });
134
+ };
135
+ })()
136
+ `.trim();
137
+
43
138
  // libs/core/src/interpreter/interpreter.ts
44
139
  var BLOCKED_KEYS = /* @__PURE__ */ new Set([
45
140
  "__proto__",
@@ -50,7 +145,21 @@ var BLOCKED_KEYS = /* @__PURE__ */ new Set([
50
145
  "__lookupGetter__",
51
146
  "__lookupSetter__"
52
147
  ]);
148
+ function isBlockedKey(key) {
149
+ return key === "__proto__" || BLOCKED_KEYS.has(key);
150
+ }
151
+ function assertKeyAllowed(key) {
152
+ if (isBlockedKey(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
153
+ }
154
+ function readProperty(object, key) {
155
+ if (key === "__proto__" || BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
156
+ return object[key];
157
+ }
53
158
  var MAX_STRING_OP_LENGTH = 1e6;
159
+ var MAX_JOIN_LENGTH = 16e6;
160
+ var MAX_TEXT_NESTING = 64;
161
+ var MAX_TEXT_ITEMS = 8e6;
162
+ var MAX_ARRAY_LENGTH = 1e6;
54
163
  var HIGHER_ORDER_ARRAY_METHODS = /* @__PURE__ */ new Set([
55
164
  "map",
56
165
  "flatMap",
@@ -60,9 +169,132 @@ var HIGHER_ORDER_ARRAY_METHODS = /* @__PURE__ */ new Set([
60
169
  "every",
61
170
  "find",
62
171
  "findIndex",
172
+ "findLast",
173
+ "findLastIndex",
63
174
  "reduce",
64
- "sort"
175
+ "reduceRight",
176
+ "sort",
177
+ "toSorted"
178
+ ]);
179
+ var FunctionProtoCall = Function.prototype.call;
180
+ var FunctionProtoApply = Function.prototype.apply;
181
+ var FunctionProtoBind = Function.prototype.bind;
182
+ var FunctionProtoToString = Function.prototype.toString;
183
+ function methodsOf(prototype) {
184
+ const methods = /* @__PURE__ */ new Map();
185
+ for (const name of Object.getOwnPropertyNames(prototype)) {
186
+ if (name === "constructor") continue;
187
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, name);
188
+ if (descriptor && typeof descriptor.value === "function") methods.set(descriptor.value, name);
189
+ }
190
+ return methods;
191
+ }
192
+ var ARRAY_METHODS = methodsOf(Array.prototype);
193
+ var STRING_METHODS = methodsOf(String.prototype);
194
+ var ARRAY_DATA_ARGUMENTS = /* @__PURE__ */ new Map([
195
+ ["push", () => true],
196
+ ["unshift", () => true],
197
+ ["concat", () => true],
198
+ ["includes", (index) => index === 0],
199
+ ["indexOf", (index) => index === 0],
200
+ ["lastIndexOf", (index) => index === 0],
201
+ ["fill", (index) => index === 0],
202
+ ["splice", (index) => index >= 2],
203
+ ["toSpliced", (index) => index >= 2],
204
+ ["with", (index) => index === 1],
205
+ ["reduce", (index) => index === 1],
206
+ ["reduceRight", (index) => index === 1]
65
207
  ]);
208
+ var ARRAY_DATA_FUNCTIONS = /* @__PURE__ */ new WeakSet();
209
+ function takesArraysAsData(fn) {
210
+ ARRAY_DATA_FUNCTIONS.add(fn);
211
+ return fn;
212
+ }
213
+ var CONVERTED_ARGUMENTS = /* @__PURE__ */ new WeakMap();
214
+ function convertsArguments(fn, count) {
215
+ CONVERTED_ARGUMENTS.set(fn, count);
216
+ return fn;
217
+ }
218
+ var CALL_COSTS = /* @__PURE__ */ new WeakMap();
219
+ function chargedBeforeCall(fn, cost) {
220
+ CALL_COSTS.set(fn, cost);
221
+ return fn;
222
+ }
223
+ function newTextMeasure() {
224
+ return { length: 0, items: 0, active: /* @__PURE__ */ new Set(), functions: /* @__PURE__ */ new Map() };
225
+ }
226
+ function scalarTextLength(item, measure) {
227
+ switch (typeof item) {
228
+ case "number":
229
+ case "boolean":
230
+ return 32;
231
+ // also covers a number in the longest locale format
232
+ case "bigint":
233
+ return String(item).length;
234
+ case "function": {
235
+ let length = measure.functions.get(item);
236
+ if (length === void 0) {
237
+ try {
238
+ length = FunctionProtoToString.call(item).length;
239
+ } catch {
240
+ length = 0;
241
+ }
242
+ measure.functions.set(item, length);
243
+ }
244
+ return length;
245
+ }
246
+ case "object": {
247
+ if (isScriptError(item)) {
248
+ const error = item;
249
+ return String(error.name).length + 2 + String(error.message).length;
250
+ }
251
+ return 96;
252
+ }
253
+ default:
254
+ return 0;
255
+ }
256
+ }
257
+ function measureArrayText(array, separatorLength, measure, depth) {
258
+ if (depth > MAX_TEXT_NESTING) {
259
+ measure.length = Number.POSITIVE_INFINITY;
260
+ return;
261
+ }
262
+ measure.length += separatorLength * Math.max(0, array.length - 1);
263
+ measure.active.add(array);
264
+ for (let i = 0; i < array.length && measure.length <= MAX_JOIN_LENGTH; i++) {
265
+ if (++measure.items > MAX_TEXT_ITEMS) {
266
+ measure.length = Number.POSITIVE_INFINITY;
267
+ break;
268
+ }
269
+ const item = array[i];
270
+ if (typeof item === "string") measure.length += item.length;
271
+ else if (item === null || item === void 0) continue;
272
+ else if (Array.isArray(item)) {
273
+ if (!measure.active.has(item)) measureArrayText(item, 1, measure, depth + 1);
274
+ } else measure.length += scalarTextLength(item, measure);
275
+ }
276
+ measure.active.delete(array);
277
+ }
278
+ function flatLength(array, depth, limit, nesting = 0) {
279
+ if (nesting > MAX_TEXT_NESTING) return Number.POSITIVE_INFINITY;
280
+ let count = 0;
281
+ for (let i = 0; i < array.length && count <= limit; i++) {
282
+ const item = array[i];
283
+ if (depth >= 1 && Array.isArray(item)) count += flatLength(item, depth - 1, limit - count, nesting + 1);
284
+ else count++;
285
+ }
286
+ return count;
287
+ }
288
+ var TEXT_TOO_LONG = `An array cannot be turned into a text of more than ${MAX_JOIN_LENGTH} chars`;
289
+ function assertArrayTextWithinLimit(...values) {
290
+ let measure;
291
+ for (const value of values) {
292
+ if (!Array.isArray(value)) continue;
293
+ measure ??= newTextMeasure();
294
+ measureArrayText(value, 1, measure, 0);
295
+ if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
296
+ }
297
+ }
66
298
  var StepLimitError = class extends Error {
67
299
  constructor(limit) {
68
300
  super(`Execution step limit exceeded (${limit})`);
@@ -84,14 +316,47 @@ var BreakSignal = class {
84
316
  };
85
317
  var ContinueSignal = class {
86
318
  };
319
+ var ChainShortCircuit = class {
320
+ };
321
+ function isControlSignal(value) {
322
+ return value instanceof ReturnSignal || value instanceof BreakSignal || value instanceof ContinueSignal || value instanceof ChainShortCircuit;
323
+ }
324
+ var SCRIPT_ERRORS = /* @__PURE__ */ new WeakSet();
325
+ function createScriptError(name, message, code) {
326
+ const error = /* @__PURE__ */ Object.create(null);
327
+ error["name"] = name;
328
+ error["message"] = message;
329
+ 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
+ });
336
+ SCRIPT_ERRORS.add(error);
337
+ return Object.freeze(error);
338
+ }
339
+ function isScriptError(value) {
340
+ return typeof value === "object" && value !== null && SCRIPT_ERRORS.has(value);
341
+ }
87
342
  var Scope = class _Scope {
88
- constructor(parent) {
343
+ constructor(parent, depth) {
89
344
  this.parent = parent;
345
+ this.depth = depth ?? parent?.depth ?? 0;
90
346
  }
91
347
  vars = /* @__PURE__ */ new Map();
348
+ /**
349
+ * How many calls deep the code of this scope runs: 0 for the program, and for the body of a
350
+ * function one more than where it was called from. A block inside has the depth around it.
351
+ */
352
+ depth;
92
353
  child() {
93
354
  return new _Scope(this);
94
355
  }
356
+ /** The scope of one call of a function defined in this scope, running `depth` calls deep. */
357
+ activation(depth) {
358
+ return new _Scope(this, depth);
359
+ }
95
360
  declare(name, value, mutable) {
96
361
  this.vars.set(name, { value, mutable });
97
362
  }
@@ -118,14 +383,43 @@ var Scope = class _Scope {
118
383
  throw new InterpreterError(`'${name}' is not defined`);
119
384
  }
120
385
  };
386
+ var DEFAULT_MAX_PENDING_CALLS = 4096;
387
+ function ignoreRejection2() {
388
+ }
121
389
  var Interpreter = class {
122
390
  constructor(options) {
123
391
  this.options = options;
124
392
  this.globals = options.globals;
393
+ this.maxPendingCalls = options.maxPendingCalls ?? DEFAULT_MAX_PENDING_CALLS;
125
394
  }
126
395
  steps = 0;
127
- callDepth = 0;
396
+ /** Calls that have not returned: the running ones and the ones waiting on an `await` */
397
+ pendingCalls = 0;
398
+ /**
399
+ * The depth of whatever is making a call right now, for the function of the script that call
400
+ * starts. A function of the script is a host function too, and a built-in, `parallel` or a
401
+ * bound function invokes it without saying how deep it is: it reads this as it starts, in the
402
+ * same synchronous step as the call, and runs one deeper. Set by {@link withCallerDepth} for
403
+ * the synchronous part of a call only; a call that is waiting does not hold it, which is what
404
+ * keeps the depth of one chain apart from the depth of another. 0 when the host itself calls.
405
+ */
406
+ callerDepth = 0;
407
+ maxPendingCalls;
128
408
  globals;
409
+ /** The error that ended the run (step budget, abort, allocation budget); set once, never caught */
410
+ fatal;
411
+ interpretedFunctions = /* @__PURE__ */ new WeakSet();
412
+ errorCopies = /* @__PURE__ */ new WeakMap();
413
+ /**
414
+ * Call a function for a script, with the checks that apply to a call the script writes itself.
415
+ * For a host helper that is handed a callback (`parallel(items, fn)`): `fn` may be a function
416
+ * of the script, or a built-in or host function the script passed along.
417
+ */
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);
422
+ }
129
423
  /** Number of AST nodes evaluated so far (for execution stats). */
130
424
  get stepCount() {
131
425
  return this.steps;
@@ -148,18 +442,48 @@ var Interpreter = class {
148
442
  }
149
443
  return last;
150
444
  }
445
+ /**
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.
449
+ */
450
+ stop() {
451
+ if (this.fatal === void 0) this.fatal = new InterpreterError("Execution ended");
452
+ }
453
+ /** End the run with an error no `catch` of the script can stop. */
454
+ end(error) {
455
+ if (this.fatal === void 0) this.fatal = error;
456
+ throw this.fatal;
457
+ }
151
458
  tick() {
152
- if (this.options.signal?.aborted) throw new InterpreterError("Execution aborted");
153
- if (++this.steps > this.options.maxSteps) throw new StepLimitError(this.options.maxSteps);
459
+ if (this.fatal !== void 0) throw this.fatal;
460
+ if (this.options.signal?.aborted) this.end(new InterpreterError("Execution aborted"));
461
+ if (++this.steps > this.options.maxSteps) this.end(new StepLimitError(this.options.maxSteps));
462
+ }
463
+ /** Charge an allocation to the host's budget. */
464
+ charge(bytes) {
465
+ const charge = this.options.charge;
466
+ if (!charge || bytes <= 0) return;
467
+ try {
468
+ charge(bytes);
469
+ } catch (error) {
470
+ this.end(error);
471
+ }
472
+ }
473
+ /** Charge what a host function returned, when that is a string or an array. */
474
+ chargeValue(value) {
475
+ if (typeof value === "string") this.charge(value.length * 2);
476
+ else if (Array.isArray(value)) this.charge(value.length * 8);
154
477
  }
155
478
  // ── Statements ─────────────────────────────────────────────────────────────
156
479
  async execStatement(node, scope) {
157
480
  this.tick();
158
481
  switch (node.type) {
159
482
  case "VariableDeclaration": {
483
+ const mode = node.kind === "const" ? "const" : "let";
160
484
  for (const d of node.declarations) {
161
485
  const value = d.init ? await this.evalExpr(d.init, scope) : void 0;
162
- this.bindPattern(d.id, value, scope, node.kind !== "const");
486
+ await this.applyPattern(d.id, value, scope, mode);
163
487
  }
164
488
  return void 0;
165
489
  }
@@ -176,15 +500,27 @@ var Interpreter = class {
176
500
  return void 0;
177
501
  case "ForOfStatement":
178
502
  return this.execForOf(node, scope);
503
+ case "ForInStatement":
504
+ return this.execForIn(node, scope);
179
505
  case "ForStatement":
180
506
  return this.execFor(node, scope);
181
507
  case "WhileStatement":
182
508
  return this.execWhile(node, scope);
509
+ case "DoWhileStatement":
510
+ return this.execDoWhile(node, scope);
511
+ case "SwitchStatement":
512
+ return this.execSwitch(node, scope);
513
+ case "TryStatement":
514
+ return this.execTry(node, scope);
515
+ case "ThrowStatement":
516
+ throw await this.evalExpr(node.argument, scope);
183
517
  case "ReturnStatement":
184
518
  throw new ReturnSignal(node.argument ? await this.evalExpr(node.argument, scope) : void 0);
185
519
  case "BreakStatement":
520
+ if (node.label) throw new InterpreterError("Labeled break is not supported");
186
521
  throw new BreakSignal();
187
522
  case "ContinueStatement":
523
+ if (node.label) throw new InterpreterError("Labeled continue is not supported");
188
524
  throw new ContinueSignal();
189
525
  case "EmptyStatement":
190
526
  return void 0;
@@ -204,25 +540,44 @@ var Interpreter = class {
204
540
  }
205
541
  return void 0;
206
542
  }
543
+ /** Bind the variable of a `for…of` / `for…in` head to the value of one iteration. */
544
+ async bindLoopVariable(left, value, scope) {
545
+ if (left.type === "VariableDeclaration") {
546
+ await this.applyPattern(left.declarations[0].id, value, scope, left.kind === "const" ? "const" : "let");
547
+ } else {
548
+ await this.applyPattern(left, value, scope, "assign");
549
+ }
550
+ }
551
+ /** Run one iteration of a loop body. @returns false when the loop is to stop */
552
+ async runLoopBody(body, scope) {
553
+ try {
554
+ await this.execStatement(body, scope);
555
+ } catch (e) {
556
+ if (e instanceof BreakSignal) return false;
557
+ if (!(e instanceof ContinueSignal)) throw e;
558
+ }
559
+ return true;
560
+ }
207
561
  async execForOf(node, scope) {
562
+ if (node.await) throw new InterpreterError("for await is not supported");
208
563
  const iterable = await this.evalExpr(node.right, scope);
209
564
  if (!isIterable(iterable)) throw new InterpreterError("for-of target is not iterable");
210
565
  for (const item of iterable) {
211
566
  this.tick();
212
567
  const inner = scope.child();
213
- const decl = node.left;
214
- if (decl.type === "VariableDeclaration") {
215
- this.bindPattern(decl.declarations[0].id, item, inner, decl.kind !== "const");
216
- } else {
217
- this.assignTo(decl, item, inner);
218
- }
219
- try {
220
- await this.execStatement(node.body, inner);
221
- } catch (e) {
222
- if (e instanceof BreakSignal) break;
223
- if (e instanceof ContinueSignal) continue;
224
- throw e;
225
- }
568
+ await this.bindLoopVariable(node.left, item, inner);
569
+ if (!await this.runLoopBody(node.body, inner)) break;
570
+ }
571
+ }
572
+ async execForIn(node, scope) {
573
+ const object = await this.evalExpr(node.right, scope);
574
+ if (object === null || object === void 0) return;
575
+ for (const key of Object.keys(object)) {
576
+ this.tick();
577
+ if (BLOCKED_KEYS.has(key)) continue;
578
+ const inner = scope.child();
579
+ await this.bindLoopVariable(node.left, key, inner);
580
+ if (!await this.runLoopBody(node.body, inner)) break;
226
581
  }
227
582
  }
228
583
  async execFor(node, scope) {
@@ -233,31 +588,78 @@ var Interpreter = class {
233
588
  }
234
589
  while (node.test ? truthy(await this.evalExpr(node.test, inner)) : true) {
235
590
  this.tick();
236
- try {
237
- await this.execStatement(node.body, inner.child());
238
- } catch (e) {
239
- if (e instanceof BreakSignal) break;
240
- if (!(e instanceof ContinueSignal)) throw e;
241
- }
591
+ if (!await this.runLoopBody(node.body, inner.child())) break;
242
592
  if (node.update) await this.evalExpr(node.update, inner);
243
593
  }
244
594
  }
245
595
  async execWhile(node, scope) {
246
596
  while (truthy(await this.evalExpr(node.test, scope))) {
247
597
  this.tick();
248
- try {
249
- await this.execStatement(node.body, scope.child());
250
- } catch (e) {
251
- if (e instanceof BreakSignal) break;
252
- if (!(e instanceof ContinueSignal)) throw e;
598
+ if (!await this.runLoopBody(node.body, scope.child())) break;
599
+ }
600
+ }
601
+ async execDoWhile(node, scope) {
602
+ do {
603
+ this.tick();
604
+ if (!await this.runLoopBody(node.body, scope.child())) break;
605
+ } while (truthy(await this.evalExpr(node.test, scope)));
606
+ }
607
+ async execSwitch(node, scope) {
608
+ const value = await this.evalExpr(node.discriminant, scope);
609
+ const inner = scope.child();
610
+ let start = -1;
611
+ for (let i = 0; i < node.cases.length && start === -1; i++) {
612
+ const test = node.cases[i].test;
613
+ if (test && await this.evalExpr(test, inner) === value) start = i;
614
+ }
615
+ if (start === -1) start = node.cases.findIndex((clause) => !clause.test);
616
+ if (start === -1) return;
617
+ try {
618
+ for (let i = start; i < node.cases.length; i++) {
619
+ for (const stmt of node.cases[i].consequent) await this.execStatement(stmt, inner);
253
620
  }
621
+ } catch (e) {
622
+ if (!(e instanceof BreakSignal)) throw e;
623
+ }
624
+ }
625
+ async execTry(node, scope) {
626
+ try {
627
+ await this.execBlock(node.block.body, scope.child());
628
+ } catch (thrown) {
629
+ if (!node.handler || isControlSignal(thrown) || this.fatal !== void 0) throw thrown;
630
+ const inner = scope.child();
631
+ if (node.handler.param) await this.applyPattern(node.handler.param, this.toScriptValue(thrown), inner, "let");
632
+ await this.execBlock(node.handler.body.body, inner);
633
+ } finally {
634
+ if (node.finalizer && this.fatal === void 0) await this.execBlock(node.finalizer.body, scope.child());
254
635
  }
255
636
  }
637
+ /**
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.
641
+ */
642
+ toScriptValue(thrown) {
643
+ if (!(thrown instanceof Error)) return thrown;
644
+ const known = this.errorCopies.get(thrown);
645
+ if (known) return known;
646
+ const code = thrown.code;
647
+ const copy = createScriptError(
648
+ typeof thrown.name === "string" ? thrown.name : "Error",
649
+ typeof thrown.message === "string" ? thrown.message : "",
650
+ typeof code === "string" ? code : void 0
651
+ );
652
+ this.errorCopies.set(thrown, copy);
653
+ return copy;
654
+ }
256
655
  // ── Expressions ──────────────────────────────────────────────────────────--
257
656
  async evalExpr(node, scope) {
258
657
  this.tick();
259
658
  switch (node.type) {
260
659
  case "Literal":
660
+ if (node.regex) {
661
+ throw new InterpreterError("Regular expressions are not supported");
662
+ }
261
663
  return node.value;
262
664
  case "Identifier":
263
665
  return scope.has(node.name) ? scope.get(node.name) : this.readGlobal(node.name);
@@ -269,49 +671,50 @@ var Interpreter = class {
269
671
  if (el == null) {
270
672
  arr.push(void 0);
271
673
  } else if (el.type === "SpreadElement") {
272
- const spread = await this.evalExpr(el.argument, scope);
273
- if (!isIterable(spread)) throw new InterpreterError("Spread target is not iterable");
274
- for (const v of spread) arr.push(v);
674
+ this.spreadInto(arr, await this.evalExpr(el.argument, scope));
275
675
  } else {
276
676
  arr.push(await this.evalExpr(el, scope));
277
677
  }
278
678
  }
679
+ this.charge(arr.length * 8);
279
680
  return arr;
280
681
  }
281
682
  case "ObjectExpression": {
282
683
  const obj = {};
684
+ let count = 0;
283
685
  for (const prop of node.properties) {
284
686
  if (prop.type === "SpreadElement") {
285
687
  const spread = await this.evalExpr(prop.argument, scope);
286
688
  if (spread && typeof spread === "object") {
287
689
  for (const [k, v] of Object.entries(spread)) {
288
- if (!BLOCKED_KEYS.has(k)) obj[k] = v;
690
+ this.tick();
691
+ if (!BLOCKED_KEYS.has(k)) {
692
+ obj[k] = v;
693
+ count++;
694
+ }
289
695
  }
290
696
  }
291
697
  continue;
292
698
  }
699
+ if (prop.kind !== "init") throw new InterpreterError("Getters and setters are not supported");
293
700
  const key = await this.propKey(prop, scope);
294
701
  if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property key: ${key}`);
295
702
  obj[key] = await this.evalExpr(prop.value, scope);
703
+ count++;
296
704
  }
705
+ this.charge(count * 16);
297
706
  return obj;
298
707
  }
299
- case "UnaryExpression": {
300
- const v = await this.evalExpr(node.argument, scope);
301
- switch (node.operator) {
302
- case "!":
303
- return !truthy(v);
304
- case "-":
305
- return -v;
306
- case "+":
307
- return +v;
308
- case "typeof":
309
- return typeof v;
310
- case "~":
311
- return ~v;
312
- default:
313
- throw new InterpreterError(`Unsupported unary operator: ${node.operator}`);
314
- }
708
+ case "UnaryExpression":
709
+ return this.evalUnary(node, scope);
710
+ case "UpdateExpression": {
711
+ const ref = await this.resolveReference(node.argument, scope);
712
+ const current = ref.get();
713
+ assertArrayTextWithinLimit(current);
714
+ const before = Number(current);
715
+ const after = node.operator === "++" ? before + 1 : before - 1;
716
+ ref.set(after);
717
+ return node.prefix ? after : before;
315
718
  }
316
719
  case "BinaryExpression":
317
720
  return this.evalBinary(node, scope);
@@ -323,10 +726,26 @@ var Interpreter = class {
323
726
  }
324
727
  case "ConditionalExpression":
325
728
  return truthy(await this.evalExpr(node.test, scope)) ? this.evalExpr(node.consequent, scope) : this.evalExpr(node.alternate, scope);
326
- case "MemberExpression":
327
- return (await this.evalMember(node, scope)).value;
729
+ case "SequenceExpression": {
730
+ let last;
731
+ for (const expression of node.expressions) last = await this.evalExpr(expression, scope);
732
+ return last;
733
+ }
734
+ case "ChainExpression":
735
+ try {
736
+ return await this.evalExpr(node.expression, scope);
737
+ } catch (e) {
738
+ if (e instanceof ChainShortCircuit) return void 0;
739
+ throw e;
740
+ }
741
+ case "MemberExpression": {
742
+ const { object, key } = await this.evalMemberTarget(node, scope);
743
+ return readProperty(object, key);
744
+ }
328
745
  case "CallExpression":
329
746
  return this.evalCall(node, scope);
747
+ case "NewExpression":
748
+ return this.evalNew(node, scope);
330
749
  case "AwaitExpression":
331
750
  return await this.evalExpr(node.argument, scope);
332
751
  case "AssignmentExpression":
@@ -342,16 +761,79 @@ var Interpreter = class {
342
761
  let out = "";
343
762
  for (let i = 0; i < node.quasis.length; i++) {
344
763
  out += node.quasis[i].value.cooked ?? "";
345
- if (i < node.expressions.length) out += String(await this.evalExpr(node.expressions[i], scope));
764
+ if (i < node.expressions.length) {
765
+ const value = await this.evalExpr(node.expressions[i], scope);
766
+ assertArrayTextWithinLimit(value);
767
+ out += String(value);
768
+ if (out.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
769
+ }
346
770
  }
771
+ this.charge(out.length * 2);
347
772
  return out;
348
773
  }
774
+ async evalUnary(node, scope) {
775
+ if (node.operator === "typeof" && node.argument.type === "Identifier" && !scope.has(node.argument.name) && !Object.prototype.hasOwnProperty.call(this.globals, node.argument.name)) {
776
+ return "undefined";
777
+ }
778
+ if (node.operator === "delete") {
779
+ if (node.argument.type !== "MemberExpression") throw new InterpreterError("Only a property can be deleted");
780
+ const { object, key } = await this.evalMemberTarget(node.argument, scope);
781
+ this.assertChangeable(object);
782
+ assertKeyAllowed(key);
783
+ return delete object[key];
784
+ }
785
+ const v = await this.evalExpr(node.argument, scope);
786
+ switch (node.operator) {
787
+ case "!":
788
+ return !truthy(v);
789
+ case "-":
790
+ assertArrayTextWithinLimit(v);
791
+ return -v;
792
+ case "+":
793
+ assertArrayTextWithinLimit(v);
794
+ return +v;
795
+ case "typeof":
796
+ return typeof v;
797
+ case "~":
798
+ assertArrayTextWithinLimit(v);
799
+ return ~v;
800
+ case "void":
801
+ return void 0;
802
+ default:
803
+ throw new InterpreterError(`Unsupported unary operator: ${node.operator}`);
804
+ }
805
+ }
349
806
  async evalBinary(node, scope) {
807
+ if (node.left.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
350
808
  const l = await this.evalExpr(node.left, scope);
351
809
  const r = await this.evalExpr(node.right, scope);
352
- switch (node.operator) {
353
- case "+":
354
- return l + r;
810
+ if (node.operator === "in") {
811
+ if (r === null || typeof r !== "object" && typeof r !== "function") {
812
+ throw new InterpreterError("Cannot use 'in' on a value that is not an object");
813
+ }
814
+ assertArrayTextWithinLimit(l);
815
+ const key = String(l);
816
+ if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
817
+ return key in r;
818
+ }
819
+ if (node.operator === "instanceof") {
820
+ const check = this.options.instanceChecks?.get(r);
821
+ if (!check) throw new InterpreterError("instanceof works with the built-in types the sandbox provides only");
822
+ return check(l);
823
+ }
824
+ return this.binary(node.operator, l, r);
825
+ }
826
+ /** Apply a binary operator to two values. */
827
+ binary(operator, left, right) {
828
+ if (operator !== "===" && operator !== "!==") assertArrayTextWithinLimit(left, right);
829
+ const l = left;
830
+ const r = right;
831
+ switch (operator) {
832
+ case "+": {
833
+ const sum = l + r;
834
+ if (typeof sum === "string") this.charge((sum.length - (typeof left === "string" ? left.length : 0)) * 2);
835
+ return sum;
836
+ }
355
837
  case "-":
356
838
  return l - r;
357
839
  case "*":
@@ -391,60 +873,363 @@ var Interpreter = class {
391
873
  case ">>>":
392
874
  return l >>> r;
393
875
  default:
394
- throw new InterpreterError(`Unsupported binary operator: ${node.operator}`);
876
+ throw new InterpreterError(`Unsupported binary operator: ${operator}`);
395
877
  }
396
878
  }
397
- /** Resolve a member access to `{ object, key, value }`, blocking escape keys. */
398
- async evalMember(node, scope) {
879
+ /**
880
+ * Resolve a member expression to the object and the key it names, blocking escape keys.
881
+ * Inside an optional chain, a `?.` on `null` or `undefined` ends the chain.
882
+ */
883
+ async evalMemberTarget(node, scope) {
884
+ if (node.object.type === "Super") throw new InterpreterError("super is not supported");
399
885
  const object = await this.evalExpr(node.object, scope);
400
- const key = node.computed ? String(await this.evalExpr(node.property, scope)) : node.property.name;
886
+ if (node.optional && (object === null || object === void 0)) throw new ChainShortCircuit();
887
+ if (node.property.type === "PrivateIdentifier") throw new InterpreterError("Private names are not supported");
888
+ const key = node.computed ? this.keyText(await this.evalExpr(node.property, scope)) : node.property.name;
401
889
  if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
402
890
  if (object == null) throw new InterpreterError(`Cannot read '${key}' of ${String(object)}`);
403
- const value = object[key];
404
- return { object, key, value };
891
+ return { object, key };
405
892
  }
406
- async evalCall(node, scope) {
407
- const args = [];
408
- for (const a of node.arguments) {
409
- if (a.type === "SpreadElement") {
410
- const spread = await this.evalExpr(a.argument, scope);
411
- if (!isIterable(spread)) throw new InterpreterError("Spread target is not iterable");
412
- for (const v of spread) args.push(v);
413
- } else {
414
- args.push(await this.evalExpr(a, scope));
893
+ /** A variable or a member as something that can be read and assigned. */
894
+ async resolveReference(node, scope) {
895
+ if (node.type === "Identifier") {
896
+ const name = node.name;
897
+ return {
898
+ get: () => scope.get(name),
899
+ set: (value) => scope.set(name, value)
900
+ };
901
+ }
902
+ if (node.type === "MemberExpression") {
903
+ const { object, key } = await this.evalMemberTarget(node, scope);
904
+ return {
905
+ get: () => readProperty(object, key),
906
+ set: (value) => this.writeMember(object, key, value)
907
+ };
908
+ }
909
+ throw new InterpreterError(`Unsupported assignment target: ${node.type}`);
910
+ }
911
+ /**
912
+ * Only data a script owns can be changed: arrays and plain objects that are not frozen. The
913
+ * globals, functions (the host's built-ins among them, which the whole process shares), dates
914
+ * and the error copies are not: a property set on one of them would be seen by host code.
915
+ */
916
+ assertChangeable(object) {
917
+ if (!isScriptData(object)) {
918
+ throw new InterpreterError("Only objects and arrays the script created can be changed");
919
+ }
920
+ if (Object.isFrozen(object)) throw new InterpreterError("Cannot change a read-only value");
921
+ }
922
+ writeMember(object, key, value) {
923
+ this.assertChangeable(object);
924
+ assertKeyAllowed(key);
925
+ 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);
931
+ }
932
+ object[key] = value;
933
+ }
934
+ /** Append what an iterable yields to an array, one step and one length check per item. */
935
+ spreadInto(target, iterable) {
936
+ if (!isIterable(iterable)) throw new InterpreterError("Spread target is not iterable");
937
+ for (const value of iterable) {
938
+ this.tick();
939
+ if (target.length >= MAX_ARRAY_LENGTH) {
940
+ throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
415
941
  }
942
+ target.push(value);
943
+ }
944
+ }
945
+ async evalArguments(nodes, scope) {
946
+ const args = [];
947
+ for (const a of nodes) {
948
+ if (a.type === "SpreadElement") this.spreadInto(args, await this.evalExpr(a.argument, scope));
949
+ else args.push(await this.evalExpr(a, scope));
416
950
  }
951
+ return args;
952
+ }
953
+ async evalNew(node, scope) {
954
+ if (node.callee.type === "Super") throw new InterpreterError("super is not supported");
955
+ const callee = await this.evalExpr(node.callee, scope);
956
+ const construct = this.options.constructors?.get(callee);
957
+ if (!construct) throw new InterpreterError("new works with the built-in types the sandbox provides only");
958
+ const args = await this.evalArguments(node.arguments, scope);
959
+ if (!ARRAY_DATA_FUNCTIONS.has(callee)) assertArrayTextWithinLimit(...args);
960
+ const value = construct(args);
961
+ this.chargeValue(value);
962
+ return value;
963
+ }
964
+ async evalCall(node, scope) {
417
965
  let fn;
418
966
  let thisArg;
967
+ let member;
419
968
  if (node.callee.type === "MemberExpression") {
420
- const m = await this.evalMember(node.callee, scope);
421
- if (Array.isArray(m.object) && HIGHER_ORDER_ARRAY_METHODS.has(m.key) && typeof args[0] === "function") {
422
- return this.callArrayMethod(m.object, m.key, args);
423
- }
424
- if (typeof m.object === "string" && (m.key === "repeat" || m.key === "padStart" || m.key === "padEnd")) {
425
- const n = Number(args[0]);
426
- const produced = m.key === "repeat" ? m.object.length * (n > 0 ? n : 0) : Math.max(m.object.length, n > 0 ? n : 0);
427
- if (produced > MAX_STRING_OP_LENGTH) {
428
- throw new InterpreterError(
429
- `String '${m.key}' would produce ${produced} chars, exceeding the ${MAX_STRING_OP_LENGTH} limit`
430
- );
431
- }
432
- }
433
- fn = m.value;
434
- thisArg = m.object;
969
+ const target = await this.evalMemberTarget(node.callee, scope);
970
+ member = { ...target, value: readProperty(target.object, target.key) };
971
+ fn = member.value;
972
+ thisArg = member.object;
973
+ } else if (node.callee.type === "Super") {
974
+ throw new InterpreterError("super is not supported");
435
975
  } else {
436
976
  fn = await this.evalExpr(node.callee, scope);
437
977
  thisArg = void 0;
438
978
  }
979
+ if (node.optional && (fn === null || fn === void 0)) {
980
+ throw new ChainShortCircuit();
981
+ }
982
+ const args = await this.evalArguments(node.arguments, scope);
983
+ if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
984
+ return this.callFunction(fn, thisArg, args, scope.depth);
985
+ }
986
+ /**
987
+ * Call a function with a receiver and arguments: an interpreted function, or a built-in or host
988
+ * function after the checks that apply to it. `call` and `apply` are resolved to the function
989
+ * they invoke first, so those checks cannot be passed by the way a call is written.
990
+ *
991
+ * @param depth - How many calls deep the code that makes this call runs
992
+ */
993
+ async callFunction(fn, thisArg, args, depth) {
994
+ for (let hops = 0; fn === FunctionProtoCall || fn === FunctionProtoApply || fn === FunctionProtoBind; hops++) {
995
+ const name = fn === FunctionProtoCall ? "call" : fn === FunctionProtoApply ? "apply" : "bind";
996
+ if (typeof thisArg !== "function" || hops >= 8) {
997
+ throw new InterpreterError(`'${name}' works on a function only`);
998
+ }
999
+ if (typeof args[0] === "function") {
1000
+ throw new InterpreterError(`'${name}' cannot make a function the receiver of a call`);
1001
+ }
1002
+ const target = thisArg;
1003
+ if (fn === FunctionProtoBind) return this.bindFunction(target, args[0], args.slice(1));
1004
+ thisArg = args[0];
1005
+ args = fn === FunctionProtoCall ? args.slice(1) : this.argumentList(args[1]);
1006
+ fn = target;
1007
+ }
439
1008
  if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
440
- if (++this.callDepth > this.options.maxCallDepth) {
441
- this.callDepth--;
1009
+ if (this.interpretedFunctions.has(fn)) {
1010
+ const interpreted = fn;
1011
+ return await this.withCallerDepth(depth, () => interpreted.apply(thisArg, args));
1012
+ }
1013
+ const own = this.enterCall(depth);
1014
+ try {
1015
+ args = this.checkBuiltinCall(fn, thisArg, args);
1016
+ const arrayMethod = ARRAY_METHODS.get(fn);
1017
+ if (arrayMethod !== void 0 && HIGHER_ORDER_ARRAY_METHODS.has(arrayMethod) && typeof args[0] === "function") {
1018
+ return await this.callArrayMethod(thisArg, arrayMethod, args, own);
1019
+ }
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)) {
1024
+ if (result.length > MAX_ARRAY_LENGTH) {
1025
+ throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
1026
+ }
1027
+ }
1028
+ this.chargeValue(result);
1029
+ return result;
1030
+ } finally {
1031
+ this.pendingCalls--;
1032
+ }
1033
+ }
1034
+ /**
1035
+ * Count a call that starts `callerDepth` calls deep, until it returns.
1036
+ *
1037
+ * @returns The depth the call itself runs at
1038
+ */
1039
+ enterCall(callerDepth) {
1040
+ const depth = callerDepth + 1;
1041
+ if (depth > this.options.maxCallDepth) {
442
1042
  throw new InterpreterError(`Max call depth exceeded (${this.options.maxCallDepth})`);
443
1043
  }
1044
+ if (this.pendingCalls >= this.maxPendingCalls) {
1045
+ throw new InterpreterError(`Too many calls in progress at once (${this.maxPendingCalls})`);
1046
+ }
1047
+ this.pendingCalls++;
1048
+ return depth;
1049
+ }
1050
+ /**
1051
+ * Make a call with `depth` as the depth a function of the script is called from, if one starts
1052
+ * during it. It covers the synchronous part of the call, which is where a function starts.
1053
+ */
1054
+ withCallerDepth(depth, call) {
1055
+ const previous = this.callerDepth;
1056
+ this.callerDepth = depth;
444
1057
  try {
445
- return await fn.apply(thisArg, args);
1058
+ return call();
446
1059
  } finally {
447
- this.callDepth--;
1060
+ this.callerDepth = previous;
1061
+ }
1062
+ }
1063
+ /** The argument list of `apply`: an array, or nothing. */
1064
+ argumentList(value) {
1065
+ if (value === null || value === void 0) return [];
1066
+ if (!Array.isArray(value)) throw new InterpreterError("'apply' takes its arguments as an array");
1067
+ this.charge(value.length * 8);
1068
+ return [...value];
1069
+ }
1070
+ /**
1071
+ * `fn.bind(receiver, ...args)`: a function that calls `fn` through {@link callFunction}, so
1072
+ * that what is checked for a call of `fn` is checked for a call of the bound function too.
1073
+ */
1074
+ bindFunction(target, boundThis, boundArgs) {
1075
+ this.charge((boundArgs.length + 2) * 8);
1076
+ return (...rest) => {
1077
+ const result = this.callFunction(target, boundThis, [...boundArgs, ...rest], this.callerDepth);
1078
+ result.then(void 0, ignoreRejection2);
1079
+ return result;
1080
+ };
1081
+ }
1082
+ /**
1083
+ * The checks before a built-in or host function runs. The engine performs such a call in one
1084
+ * step, out of reach of the step budget, and what the call allocates is only known to the
1085
+ * budget when it exists: whatever could make that large is refused here, from the arguments.
1086
+ *
1087
+ * @returns The arguments to call the function with
1088
+ */
1089
+ checkBuiltinCall(fn, thisArg, args) {
1090
+ const arrayMethod = ARRAY_METHODS.get(fn);
1091
+ const stringMethod = arrayMethod === void 0 ? STRING_METHODS.get(fn) : void 0;
1092
+ let arrayText = 0;
1093
+ if (!ARRAY_DATA_FUNCTIONS.has(fn)) {
1094
+ const isData = arrayMethod === void 0 ? void 0 : ARRAY_DATA_ARGUMENTS.get(arrayMethod);
1095
+ const converted = CONVERTED_ARGUMENTS.get(fn) ?? args.length;
1096
+ let measure;
1097
+ const measureArray = (value) => {
1098
+ measure ??= newTextMeasure();
1099
+ measureArrayText(value, 1, measure, 0);
1100
+ if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
1101
+ };
1102
+ for (let i = 0; i < args.length && i < converted; i++) {
1103
+ const arg = args[i];
1104
+ if (Array.isArray(arg) && !isData?.(i)) measureArray(arg);
1105
+ }
1106
+ if (arrayMethod === void 0 && stringMethod === void 0 && Array.isArray(thisArg)) measureArray(thisArg);
1107
+ arrayText = measure?.length ?? 0;
1108
+ }
1109
+ if (stringMethod !== void 0) args = this.checkStringMethod(stringMethod, thisArg, args, arrayText);
1110
+ else if (arrayMethod !== void 0) this.checkArrayMethod(arrayMethod, thisArg, args);
1111
+ const cost = CALL_COSTS.get(fn);
1112
+ if (cost) this.charge(cost(args));
1113
+ return args;
1114
+ }
1115
+ checkStringMethod(name, receiver, args, arrayText) {
1116
+ if (typeof receiver !== "string") throw new InterpreterError(`String '${name}' works on a string only`);
1117
+ if (name === "match" || name === "matchAll" || name === "search") {
1118
+ throw new InterpreterError(`String '${name}' is not supported: it runs a regular expression`);
1119
+ }
1120
+ if (name === "replace" || name === "replaceAll") {
1121
+ const replacement = args[1];
1122
+ if (typeof replacement === "function") {
1123
+ throw new InterpreterError(`String '${name}' does not take a function in the sandbox`);
1124
+ }
1125
+ if (typeof replacement === "object" && replacement !== null) {
1126
+ throw new InterpreterError(`String '${name}' takes a text as the replacement`);
1127
+ }
1128
+ const text = String(replacement);
1129
+ const search = args[0];
1130
+ const searchLength = typeof search === "string" ? search.length : 0;
1131
+ const matches = name === "replace" ? 1 : searchLength > 0 ? Math.floor(receiver.length / searchLength) : receiver.length + 1;
1132
+ let dollars = 0;
1133
+ for (let at = text.indexOf("$"); at !== -1; at = text.indexOf("$", at + 1)) dollars++;
1134
+ const perMatch = text.length + dollars * receiver.length;
1135
+ if (matches * perMatch > MAX_STRING_OP_LENGTH) {
1136
+ throw new InterpreterError(
1137
+ `String '${name}' could produce more than ${MAX_STRING_OP_LENGTH} chars with this replacement`
1138
+ );
1139
+ }
1140
+ return args;
1141
+ }
1142
+ if (name === "repeat" || name === "padStart" || name === "padEnd") {
1143
+ const n = Number(args[0]);
1144
+ const produced = name === "repeat" ? receiver.length * (n > 0 ? n : 0) : Math.max(receiver.length, n > 0 ? n : 0);
1145
+ if (produced > MAX_STRING_OP_LENGTH) {
1146
+ throw new InterpreterError(
1147
+ `String '${name}' would produce ${produced} chars, exceeding the ${MAX_STRING_OP_LENGTH} limit`
1148
+ );
1149
+ }
1150
+ return args;
1151
+ }
1152
+ if (name === "concat") {
1153
+ let produced = receiver.length + arrayText;
1154
+ for (let i = 0; i < args.length && produced <= MAX_JOIN_LENGTH; i++) {
1155
+ const arg = args[i];
1156
+ if (typeof arg === "string") produced += arg.length;
1157
+ else if (!Array.isArray(arg)) produced += scalarTextLength(arg, newTextMeasure());
1158
+ }
1159
+ if (produced > MAX_JOIN_LENGTH) {
1160
+ throw new InterpreterError(`String 'concat' would produce more than ${MAX_JOIN_LENGTH} chars`);
1161
+ }
1162
+ return args;
1163
+ }
1164
+ if (name === "split") {
1165
+ const asked = args[1] === void 0 ? Number.POSITIVE_INFINITY : Number(args[1]) >>> 0;
1166
+ return [args[0], Math.min(asked, MAX_ARRAY_LENGTH + 1)];
1167
+ }
1168
+ return args;
1169
+ }
1170
+ checkArrayMethod(name, receiver, args) {
1171
+ if (!Array.isArray(receiver)) throw new InterpreterError(`Array '${name}' works on an array only`);
1172
+ const tooLong2 = () => {
1173
+ throw new InterpreterError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
1174
+ };
1175
+ switch (name) {
1176
+ // `join` writes every item and a separator between them into one string, in one step; so
1177
+ // do the two conversions to text.
1178
+ case "join":
1179
+ case "toString":
1180
+ case "toLocaleString": {
1181
+ const separator = name !== "join" || args.length === 0 || args[0] === void 0 ? "," : String(args[0]);
1182
+ const measure = newTextMeasure();
1183
+ measureArrayText(receiver, separator.length, measure, 0);
1184
+ if (measure.length > MAX_JOIN_LENGTH) {
1185
+ throw new InterpreterError(`Array '${name}' would produce more than ${MAX_JOIN_LENGTH} chars`);
1186
+ }
1187
+ return;
1188
+ }
1189
+ // Without a comparison function the engine compares the items as text: strings as they
1190
+ // are, and an array among the items joined, again for every comparison.
1191
+ case "sort":
1192
+ case "toSorted": {
1193
+ if (typeof args[0] === "function") return;
1194
+ const measure = newTextMeasure();
1195
+ for (let i = 0; i < receiver.length && measure.length <= MAX_JOIN_LENGTH; i++) {
1196
+ const item = receiver[i];
1197
+ if (Array.isArray(item)) measureArrayText(item, 1, measure, 1);
1198
+ }
1199
+ if (measure.length > MAX_JOIN_LENGTH) throw new InterpreterError(TEXT_TOO_LONG);
1200
+ return;
1201
+ }
1202
+ // Growth by the arguments (a spread makes them many): charged before it happens.
1203
+ case "push":
1204
+ case "unshift":
1205
+ if (receiver.length + args.length > MAX_ARRAY_LENGTH) tooLong2();
1206
+ this.charge(args.length * 8);
1207
+ return;
1208
+ case "splice":
1209
+ case "toSpliced": {
1210
+ const added = Math.max(0, args.length - 2);
1211
+ if (receiver.length + added > MAX_ARRAY_LENGTH) tooLong2();
1212
+ if (name === "splice") this.charge(added * 8);
1213
+ return;
1214
+ }
1215
+ // A new array of the receiver and every array among the arguments: one array, given many
1216
+ // times, is small in memory and large once copied.
1217
+ case "concat": {
1218
+ let length = receiver.length;
1219
+ for (let i = 0; i < args.length && length <= MAX_ARRAY_LENGTH; i++) {
1220
+ const arg = args[i];
1221
+ length += Array.isArray(arg) ? arg.length : 1;
1222
+ }
1223
+ if (length > MAX_ARRAY_LENGTH) tooLong2();
1224
+ return;
1225
+ }
1226
+ case "flat": {
1227
+ const depth = args[0] === void 0 ? 1 : Number(args[0]);
1228
+ if (flatLength(receiver, Number.isNaN(depth) ? 0 : depth, MAX_ARRAY_LENGTH) > MAX_ARRAY_LENGTH) tooLong2();
1229
+ return;
1230
+ }
1231
+ default:
1232
+ return;
448
1233
  }
449
1234
  }
450
1235
  /**
@@ -452,8 +1237,11 @@ var Interpreter = class {
452
1237
  * callbacks (which are async — they may `await` tool calls) are awaited. Each
453
1238
  * iteration ticks the step budget.
454
1239
  */
455
- async callArrayMethod(arr, method, args) {
456
- const cb = args[0];
1240
+ async callArrayMethod(arr, method, args, depth) {
1241
+ const callback = args[0];
1242
+ const interpreted = this.interpretedFunctions.has(callback) ? callback : void 0;
1243
+ const invoke = interpreted ? (...callbackArgs) => this.withCallerDepth(depth, () => interpreted(...callbackArgs)) : (...callbackArgs) => this.callFunction(callback, void 0, callbackArgs, depth);
1244
+ const cb = invoke;
457
1245
  const each = (i) => {
458
1246
  this.tick();
459
1247
  return cb(arr[i], i, arr);
@@ -462,20 +1250,23 @@ var Interpreter = class {
462
1250
  case "map": {
463
1251
  const out = [];
464
1252
  for (let i = 0; i < arr.length; i++) out.push(await each(i));
1253
+ this.charge(out.length * 8);
465
1254
  return out;
466
1255
  }
467
1256
  case "flatMap": {
468
1257
  const out = [];
469
1258
  for (let i = 0; i < arr.length; i++) {
470
1259
  const v = await each(i);
471
- if (Array.isArray(v)) out.push(...v);
1260
+ if (Array.isArray(v)) this.spreadInto(out, v);
472
1261
  else out.push(v);
473
1262
  }
1263
+ this.charge(out.length * 8);
474
1264
  return out;
475
1265
  }
476
1266
  case "filter": {
477
1267
  const out = [];
478
1268
  for (let i = 0; i < arr.length; i++) if (truthy(await each(i))) out.push(arr[i]);
1269
+ this.charge(out.length * 8);
479
1270
  return out;
480
1271
  }
481
1272
  case "forEach":
@@ -493,116 +1284,197 @@ var Interpreter = class {
493
1284
  case "findIndex":
494
1285
  for (let i = 0; i < arr.length; i++) if (truthy(await each(i))) return i;
495
1286
  return -1;
496
- case "reduce": {
1287
+ case "findLast":
1288
+ for (let i = arr.length - 1; i >= 0; i--) if (truthy(await each(i))) return arr[i];
1289
+ return void 0;
1290
+ case "findLastIndex":
1291
+ for (let i = arr.length - 1; i >= 0; i--) if (truthy(await each(i))) return i;
1292
+ return -1;
1293
+ case "reduce":
1294
+ case "reduceRight": {
497
1295
  const reducer = cb;
1296
+ const fromRight = method === "reduceRight";
1297
+ const order = arr.map((_, i) => fromRight ? arr.length - 1 - i : i);
498
1298
  let acc;
499
1299
  let start = 0;
500
1300
  if (args.length > 1) acc = args[1];
501
1301
  else {
502
1302
  if (arr.length === 0) throw new InterpreterError("Reduce of empty array with no initial value");
503
- acc = arr[0];
1303
+ acc = arr[order[0]];
504
1304
  start = 1;
505
1305
  }
506
- for (let i = start; i < arr.length; i++) {
1306
+ for (let n = start; n < order.length; n++) {
507
1307
  this.tick();
508
- acc = await reducer(acc, arr[i], i, arr);
1308
+ acc = await reducer(acc, arr[order[n]], order[n], arr);
509
1309
  }
510
1310
  return acc;
511
1311
  }
512
- case "sort": {
1312
+ case "sort":
1313
+ case "toSorted": {
1314
+ const target = method === "sort" ? arr : [...arr];
1315
+ if (method === "sort") this.assertChangeable(arr);
1316
+ else this.charge(target.length * 8);
513
1317
  const cmp = cb;
514
- for (let i = 1; i < arr.length; i++) {
1318
+ for (let i = 1; i < target.length; i++) {
515
1319
  let j = i;
516
1320
  while (j > 0) {
517
1321
  this.tick();
518
- if (await cmp(arr[j - 1], arr[j]) <= 0) break;
519
- [arr[j - 1], arr[j]] = [arr[j], arr[j - 1]];
1322
+ if (await cmp(target[j - 1], target[j]) <= 0) break;
1323
+ [target[j - 1], target[j]] = [target[j], target[j - 1]];
520
1324
  j--;
521
1325
  }
522
1326
  }
523
- return arr;
1327
+ return target;
524
1328
  }
525
1329
  default:
526
1330
  throw new InterpreterError(`Unsupported array method: ${method}`);
527
1331
  }
528
1332
  }
529
1333
  async evalAssignment(node, scope) {
530
- const value = await this.evalExpr(node.right, scope);
531
1334
  if (node.operator === "=") {
532
- this.assignTo(node.left, value, scope);
1335
+ if (node.left.type === "MemberExpression") {
1336
+ const { object, key } = await this.evalMemberTarget(node.left, scope);
1337
+ const assigned = await this.evalExpr(node.right, scope);
1338
+ this.writeMember(object, key, assigned);
1339
+ return assigned;
1340
+ }
1341
+ const value = await this.evalExpr(node.right, scope);
1342
+ await this.applyPattern(node.left, value, scope, "assign");
533
1343
  return value;
534
1344
  }
535
- const current = await this.evalExpr(node.left, scope);
536
- const op = node.operator.slice(0, -1);
537
- const next = applyBinary(op, current, value);
538
- this.assignTo(node.left, next, scope);
539
- return next;
540
- }
541
- /** Assign to an Identifier or MemberExpression target (blocking escape keys). */
542
- assignTo(target, value, scope) {
543
- if (target.type === "Identifier") {
544
- scope.set(target.name, value);
545
- return;
546
- }
547
- if (target.type === "MemberExpression") {
548
- throw new InterpreterError("Member assignment is not supported in AgentScript");
1345
+ const ref = await this.resolveReference(node.left, scope);
1346
+ const current = ref.get();
1347
+ if (node.operator === "||=" || node.operator === "&&=" || node.operator === "??=") {
1348
+ const assign = node.operator === "||=" ? !truthy(current) : node.operator === "&&=" ? truthy(current) : current === null || current === void 0;
1349
+ if (!assign) return current;
1350
+ const value = await this.evalExpr(node.right, scope);
1351
+ ref.set(value);
1352
+ return value;
549
1353
  }
550
- throw new InterpreterError(`Unsupported assignment target: ${target.type}`);
1354
+ const next = this.binary(node.operator.slice(0, -1), current, await this.evalExpr(node.right, scope));
1355
+ ref.set(next);
1356
+ return next;
551
1357
  }
552
- bindPattern(pattern, value, scope, mutable) {
553
- if (pattern.type === "Identifier") {
554
- scope.declare(pattern.name, value, mutable);
555
- return;
556
- }
557
- if (pattern.type === "ArrayPattern") {
558
- const arr = isIterable(value) ? [...value] : [];
559
- pattern.elements.forEach((el, i) => {
560
- if (el) this.bindPattern(el, arr[i], scope, mutable);
561
- });
562
- return;
563
- }
564
- if (pattern.type === "ObjectPattern") {
565
- const obj = value ?? {};
566
- for (const prop of pattern.properties) {
567
- if (prop.type === "RestElement") continue;
568
- if (prop.computed) throw new InterpreterError("Computed destructuring keys are not allowed");
569
- let key;
570
- if (prop.key.type === "Identifier") key = prop.key.name;
571
- else if (prop.key.type === "Literal") key = String(prop.key.value);
572
- else throw new InterpreterError("Unsupported destructuring key");
573
- if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden destructured key: ${key}`);
574
- this.bindPattern(prop.value, obj[key], scope, mutable);
1358
+ /**
1359
+ * Give the names in a pattern their values: a declaration (`const` / `let`), a parameter list
1360
+ * or an assignment (`[a, o.b] = …`). Defaults and rest elements are handled here.
1361
+ */
1362
+ async applyPattern(pattern, value, scope, mode) {
1363
+ switch (pattern.type) {
1364
+ case "Identifier":
1365
+ if (mode === "assign") scope.set(pattern.name, value);
1366
+ else scope.declare(pattern.name, value, mode === "let");
1367
+ return;
1368
+ case "MemberExpression": {
1369
+ if (mode !== "assign") throw new InterpreterError("Unsupported binding pattern: MemberExpression");
1370
+ const { object, key } = await this.evalMemberTarget(pattern, scope);
1371
+ this.writeMember(object, key, value);
1372
+ return;
575
1373
  }
576
- return;
1374
+ case "AssignmentPattern":
1375
+ await this.applyPattern(
1376
+ pattern.left,
1377
+ value === void 0 ? await this.evalExpr(pattern.right, scope) : value,
1378
+ scope,
1379
+ mode
1380
+ );
1381
+ return;
1382
+ case "ArrayPattern": {
1383
+ const items = [];
1384
+ this.spreadInto(items, value);
1385
+ for (let i = 0; i < pattern.elements.length; i++) {
1386
+ const element = pattern.elements[i];
1387
+ if (!element) continue;
1388
+ if (element.type === "RestElement") {
1389
+ await this.applyPattern(element.argument, items.slice(i), scope, mode);
1390
+ break;
1391
+ }
1392
+ await this.applyPattern(element, items[i], scope, mode);
1393
+ }
1394
+ return;
1395
+ }
1396
+ case "ObjectPattern": {
1397
+ if (value === null || value === void 0) {
1398
+ throw new InterpreterError(`Cannot destructure ${String(value)}`);
1399
+ }
1400
+ const source = value;
1401
+ const taken = /* @__PURE__ */ new Set();
1402
+ for (const prop of pattern.properties) {
1403
+ if (prop.type === "RestElement") {
1404
+ const rest = {};
1405
+ for (const key2 of Object.keys(source)) {
1406
+ this.tick();
1407
+ if (!taken.has(key2) && !BLOCKED_KEYS.has(key2)) rest[key2] = source[key2];
1408
+ }
1409
+ await this.applyPattern(prop.argument, rest, scope, mode);
1410
+ continue;
1411
+ }
1412
+ if (prop.computed) throw new InterpreterError("Computed destructuring keys are not allowed");
1413
+ let key;
1414
+ if (prop.key.type === "Identifier") key = prop.key.name;
1415
+ else if (prop.key.type === "Literal") key = String(prop.key.value);
1416
+ else throw new InterpreterError("Unsupported destructuring key");
1417
+ if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden destructured key: ${key}`);
1418
+ taken.add(key);
1419
+ await this.applyPattern(prop.value, readProperty(source, key), scope, mode);
1420
+ }
1421
+ return;
1422
+ }
1423
+ default:
1424
+ throw new InterpreterError(`Unsupported binding pattern: ${pattern.type}`);
577
1425
  }
578
- throw new InterpreterError(`Unsupported binding pattern: ${pattern.type}`);
579
1426
  }
580
1427
  /** Build an interpreter-backed function (declaration / arrow / expression). */
581
1428
  makeFunction(node, closure) {
582
- const self = this;
583
- return async function interpreted(...args) {
584
- const fnScope = closure.child();
585
- node.params.forEach((p, i) => self.bindPattern(p, args[i], fnScope, true));
1429
+ if (node.generator) throw new InterpreterError("Generator functions are not supported");
1430
+ const selfName = node.type === "FunctionExpression" && node.id ? node.id.name : void 0;
1431
+ const outer = selfName === void 0 ? closure : closure.child();
1432
+ const call = async (args, callerDepth) => {
1433
+ const fnScope = outer.activation(this.enterCall(callerDepth));
586
1434
  try {
1435
+ for (let i = 0; i < node.params.length; i++) {
1436
+ const param = node.params[i];
1437
+ if (param.type === "RestElement") {
1438
+ await this.applyPattern(param.argument, args.slice(i), fnScope, "let");
1439
+ break;
1440
+ }
1441
+ await this.applyPattern(param, args[i], fnScope, "let");
1442
+ }
587
1443
  if (node.body.type === "BlockStatement") {
588
- await self.execBlock(node.body.body, fnScope);
1444
+ await this.execBlock(node.body.body, fnScope);
589
1445
  return void 0;
590
1446
  }
591
- return await self.evalExpr(node.body, fnScope);
1447
+ return await this.evalExpr(node.body, fnScope);
592
1448
  } catch (e) {
593
1449
  if (e instanceof ReturnSignal) return e.value;
594
1450
  throw e;
1451
+ } finally {
1452
+ this.pendingCalls--;
595
1453
  }
596
1454
  };
1455
+ const depthOfCaller = () => this.callerDepth;
1456
+ const interpreted = function interpreted2(...args) {
1457
+ const result = call(args, depthOfCaller());
1458
+ result.then(void 0, ignoreRejection2);
1459
+ return result;
1460
+ };
1461
+ this.interpretedFunctions.add(interpreted);
1462
+ if (selfName !== void 0) outer.declare(selfName, interpreted, false);
1463
+ return interpreted;
1464
+ }
1465
+ /** A computed property key as text. An array as a key is its items, joined. */
1466
+ keyText(value) {
1467
+ assertArrayTextWithinLimit(value);
1468
+ return String(value);
597
1469
  }
598
1470
  async propKey(prop, scope) {
599
- if (prop.computed) return String(await this.evalExpr(prop.key, scope));
1471
+ if (prop.computed) return this.keyText(await this.evalExpr(prop.key, scope));
600
1472
  if (prop.key.type === "Identifier") return prop.key.name;
601
1473
  if (prop.key.type === "Literal") return String(prop.key.value);
602
1474
  throw new InterpreterError("Unsupported property key");
603
1475
  }
604
1476
  readGlobal(name) {
605
- if (Object.prototype.hasOwnProperty.call(this.globals, name)) return this.globals[name];
1477
+ if (name !== "__proto__" && Object.prototype.hasOwnProperty.call(this.globals, name)) return this.globals[name];
606
1478
  throw new InterpreterError(`'${name}' is not defined`);
607
1479
  }
608
1480
  };
@@ -612,26 +1484,1218 @@ function truthy(v) {
612
1484
  function isIterable(v) {
613
1485
  return v != null && typeof v[Symbol.iterator] === "function";
614
1486
  }
615
- function applyBinary(op, l, r) {
616
- switch (op) {
617
- case "+":
618
- return l + r;
619
- case "-":
620
- return l - r;
621
- case "*":
622
- return l * r;
623
- case "/":
624
- return l / r;
625
- case "%":
626
- return l % r;
627
- case "**":
628
- return l ** r;
629
- default:
630
- throw new InterpreterError(`Unsupported compound operator: ${op}=`);
1487
+ function isScriptData(value) {
1488
+ if (value === Object.prototype || value === Array.prototype) return false;
1489
+ if (Array.isArray(value)) return true;
1490
+ if (value === null || typeof value !== "object") return false;
1491
+ const prototype = Object.getPrototypeOf(value);
1492
+ return prototype === Object.prototype || prototype === null;
1493
+ }
1494
+ function arrayLengthAfterWrite(array, key, value) {
1495
+ if (key === "length") {
1496
+ const length = Number(value);
1497
+ if (!Number.isInteger(length) || length < 0) throw new InterpreterError("Invalid array length");
1498
+ return length;
631
1499
  }
1500
+ 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;
632
1503
  }
633
1504
 
634
- // libs/core/src/stack-trace.ts
1505
+ // libs/core/src/value-sanitizer.ts
1506
+ var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor"]);
1507
+ var ReflectApply2 = Reflect.apply;
1508
+ var ReflectGet = Reflect.get;
1509
+ var ArrayIsArray = Array.isArray;
1510
+ var ObjectKeys = Object.keys;
1511
+ var ObjectCreate = Object.create;
1512
+ var ObjectGetPrototypeOf = Object.getPrototypeOf;
1513
+ var NumberIsFinite = Number.isFinite;
1514
+ var MathFloor = Math.floor;
1515
+ var MapProtoEntries = Map.prototype.entries;
1516
+ var SetProtoValues = Set.prototype.values;
1517
+ var DateProtoGetTime = Date.prototype.getTime;
1518
+ var DateProtoToISOString = Date.prototype.toISOString;
1519
+ var RegExpProtoSourceGetter = Object.getOwnPropertyDescriptor(RegExp.prototype, "source")?.get;
1520
+ var RegExpFlagGetters = [
1521
+ ["d", "hasIndices"],
1522
+ ["g", "global"],
1523
+ ["i", "ignoreCase"],
1524
+ ["m", "multiline"],
1525
+ ["s", "dotAll"],
1526
+ ["u", "unicode"],
1527
+ ["v", "unicodeSets"],
1528
+ ["y", "sticky"]
1529
+ ].map(([flag, property]) => [flag, Object.getOwnPropertyDescriptor(RegExp.prototype, property)?.get]);
1530
+ var MapProtoSizeGetter = Object.getOwnPropertyDescriptor(Map.prototype, "size")?.get;
1531
+ var SetProtoSizeGetter = Object.getOwnPropertyDescriptor(Set.prototype, "size")?.get;
1532
+ function hasBrand(builtin, value) {
1533
+ if (!builtin) return false;
1534
+ try {
1535
+ ReflectApply2(builtin, value, []);
1536
+ return true;
1537
+ } catch {
1538
+ return false;
1539
+ }
1540
+ }
1541
+ function regExpToString(value) {
1542
+ let flags = "";
1543
+ for (const [flag, getter] of RegExpFlagGetters) {
1544
+ if (getter && ReflectApply2(getter, value, [])) flags += flag;
1545
+ }
1546
+ return `/${ReflectApply2(RegExpProtoSourceGetter, value, [])}/${flags}`;
1547
+ }
1548
+ function isPlainObject(value) {
1549
+ const prototype = ObjectGetPrototypeOf(value);
1550
+ return prototype === null || ObjectGetPrototypeOf(prototype) === null;
1551
+ }
1552
+ function sanitizeValue(value, options = {}, depth = 0, context = { propCount: { count: 0 }, visited: /* @__PURE__ */ new WeakSet() }) {
1553
+ const maxDepth = options.maxDepth ?? 20;
1554
+ const maxProperties = options.maxProperties ?? 1e4;
1555
+ const allowDates = options.allowDates ?? true;
1556
+ const allowErrors = options.allowErrors ?? true;
1557
+ if (depth > maxDepth) {
1558
+ throw new Error(
1559
+ `Tool handler return value exceeds maximum depth (${maxDepth}). This limit prevents deeply nested objects that could cause stack overflow.`
1560
+ );
1561
+ }
1562
+ if (context.propCount.count > maxProperties) {
1563
+ throw new Error(
1564
+ `Tool handler return value exceeds maximum properties (${maxProperties}). This limit prevents memory exhaustion from large object graphs.`
1565
+ );
1566
+ }
1567
+ if (value === null || value === void 0) {
1568
+ return value;
1569
+ }
1570
+ const type = typeof value;
1571
+ if (type === "string" || type === "number" || type === "boolean") {
1572
+ return value;
1573
+ }
1574
+ if (type === "bigint") {
1575
+ return String(value);
1576
+ }
1577
+ if (type === "function") {
1578
+ throw new Error(
1579
+ "Tool handler returned a function. Functions cannot be returned to sandbox code as they could be used for code injection or host scope access."
1580
+ );
1581
+ }
1582
+ if (type === "symbol") {
1583
+ throw new Error(
1584
+ "Tool handler returned a symbol. Symbols cannot be returned to sandbox code as they could be used for prototype manipulation."
1585
+ );
1586
+ }
1587
+ if (type === "object" && value !== null) {
1588
+ if (context.visited.has(value)) {
1589
+ return "[Circular]";
1590
+ }
1591
+ context.visited.add(value);
1592
+ }
1593
+ if (ArrayIsArray(value)) {
1594
+ const rawLen = ReflectGet(value, "length");
1595
+ const len = typeof rawLen === "number" && NumberIsFinite(rawLen) && rawLen >= 0 ? MathFloor(rawLen) : 0;
1596
+ context.propCount.count += len;
1597
+ if (context.propCount.count > maxProperties) {
1598
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
1599
+ }
1600
+ const result = [];
1601
+ for (let i = 0; i < len; i++) {
1602
+ let item;
1603
+ try {
1604
+ item = ReflectGet(value, i);
1605
+ } catch {
1606
+ item = void 0;
1607
+ }
1608
+ result[i] = sanitizeValue(item, options, depth + 1, context);
1609
+ }
1610
+ return result;
1611
+ }
1612
+ const inspected = options.unwrap ? options.unwrap(value) : value;
1613
+ const isPlain = isPlainObject(inspected);
1614
+ if (!isPlain && hasBrand(DateProtoGetTime, inspected)) {
1615
+ const time = ReflectApply2(DateProtoGetTime, inspected, []);
1616
+ if (allowDates) {
1617
+ return new Date(time);
1618
+ }
1619
+ return ReflectApply2(DateProtoToISOString, inspected, []);
1620
+ }
1621
+ if (value instanceof Error) {
1622
+ const rawName = ReflectGet(value, "name");
1623
+ const rawMessage = ReflectGet(value, "message");
1624
+ const name = typeof rawName === "string" ? rawName : "Error";
1625
+ const message = typeof rawMessage === "string" ? rawMessage : "";
1626
+ if (allowErrors) {
1627
+ return {
1628
+ name,
1629
+ message
1630
+ // Do NOT include stack trace - could leak host information
1631
+ };
1632
+ }
1633
+ return { error: message };
1634
+ }
1635
+ if (!isPlain && hasBrand(RegExpProtoSourceGetter, inspected)) {
1636
+ return regExpToString(inspected);
1637
+ }
1638
+ if (!isPlain && hasBrand(MapProtoSizeGetter, inspected)) {
1639
+ const sanitizedMap = ObjectCreate(null);
1640
+ const entries = ReflectApply2(MapProtoEntries, inspected, []);
1641
+ for (const [key, val] of entries) {
1642
+ if (typeof key !== "string") continue;
1643
+ if (DANGEROUS_KEYS.has(key)) continue;
1644
+ context.propCount.count++;
1645
+ sanitizedMap[key] = sanitizeValue(val, options, depth + 1, context);
1646
+ }
1647
+ return sanitizedMap;
1648
+ }
1649
+ if (!isPlain && hasBrand(SetProtoSizeGetter, inspected)) {
1650
+ const iter = ReflectApply2(SetProtoValues, inspected, []);
1651
+ const result = [];
1652
+ for (const item of iter) {
1653
+ context.propCount.count++;
1654
+ result.push(sanitizeValue(item, options, depth + 1, context));
1655
+ }
1656
+ return result;
1657
+ }
1658
+ if (type === "object") {
1659
+ const sanitized = ObjectCreate(null);
1660
+ const keys = ObjectKeys(value);
1661
+ context.propCount.count += keys.length;
1662
+ if (context.propCount.count > maxProperties) {
1663
+ throw new Error(`Tool handler return value exceeds maximum properties (${maxProperties}).`);
1664
+ }
1665
+ for (const key of keys) {
1666
+ if (DANGEROUS_KEYS.has(key)) {
1667
+ continue;
1668
+ }
1669
+ let propValue;
1670
+ try {
1671
+ propValue = ReflectGet(value, key);
1672
+ } catch {
1673
+ continue;
1674
+ }
1675
+ sanitized[key] = sanitizeValue(propValue, options, depth + 1, context);
1676
+ }
1677
+ return sanitized;
1678
+ }
1679
+ return String(value);
1680
+ }
1681
+ function estimateStringSize(str) {
1682
+ let bytes = 2;
1683
+ for (let i = 0; i < str.length; i++) {
1684
+ const code = str.charCodeAt(i);
1685
+ if (code < 128) {
1686
+ if (code === 34 || code === 92) {
1687
+ bytes += 2;
1688
+ } else if (code < 32) {
1689
+ bytes += 6;
1690
+ } else {
1691
+ bytes += 1;
1692
+ }
1693
+ } else if (code < 2048) {
1694
+ bytes += 2;
1695
+ } else if (code >= 55296 && code <= 57343) {
1696
+ const nextCode = code <= 56319 && i + 1 < str.length ? str.charCodeAt(i + 1) : 0;
1697
+ if (nextCode >= 56320 && nextCode <= 57343) {
1698
+ bytes += 4;
1699
+ i++;
1700
+ } else {
1701
+ bytes += 6;
1702
+ }
1703
+ } else {
1704
+ bytes += 3;
1705
+ }
1706
+ }
1707
+ return bytes;
1708
+ }
1709
+ function estimateSerializedSize(value, maxBytes = 0, depth = 0, maxDepth = 2e3, currentPath = /* @__PURE__ */ new Set()) {
1710
+ if (depth > maxDepth) {
1711
+ throw new Error(
1712
+ `Structure exceeds maximum nesting depth (${maxDepth}). Deeply nested structures are rejected to prevent stack overflow attacks.`
1713
+ );
1714
+ }
1715
+ if (value === null) return 4;
1716
+ if (value === void 0) return 0;
1717
+ const type = typeof value;
1718
+ if (type === "string") {
1719
+ const bytes = estimateStringSize(value);
1720
+ if (maxBytes > 0 && bytes > maxBytes) {
1721
+ throw new Error(`String serialization would exceed limit: ${bytes} > ${maxBytes} bytes`);
1722
+ }
1723
+ return bytes;
1724
+ }
1725
+ if (type === "number") {
1726
+ const num = value;
1727
+ if (!NumberIsFinite(num)) return 4;
1728
+ return String(num).length;
1729
+ }
1730
+ if (type === "boolean") {
1731
+ return value ? 4 : 5;
1732
+ }
1733
+ if (type === "bigint") {
1734
+ return String(value).length + 2;
1735
+ }
1736
+ if (type === "function" || type === "symbol") {
1737
+ return 0;
1738
+ }
1739
+ if (ArrayIsArray(value)) {
1740
+ if (currentPath.has(value)) {
1741
+ return 4;
1742
+ }
1743
+ currentPath.add(value);
1744
+ try {
1745
+ const rawLength = readProperty2(value, "length");
1746
+ const length = typeof rawLength === "number" && NumberIsFinite(rawLength) && rawLength >= 0 ? MathFloor(rawLength) : 0;
1747
+ let size = 2;
1748
+ for (let i = 0; i < length; i++) {
1749
+ if (i > 0) size += 1;
1750
+ let elementSize = estimateSerializedSize(readProperty2(value, i), maxBytes, depth + 1, maxDepth, currentPath);
1751
+ if (elementSize === 0) elementSize = 4;
1752
+ size += elementSize;
1753
+ if (maxBytes > 0 && size > maxBytes) {
1754
+ throw new Error(
1755
+ `Array serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
1756
+ );
1757
+ }
1758
+ }
1759
+ return size;
1760
+ } finally {
1761
+ currentPath.delete(value);
1762
+ }
1763
+ }
1764
+ if (type === "object") {
1765
+ const object = value;
1766
+ if (currentPath.has(object)) {
1767
+ return 4;
1768
+ }
1769
+ if (!isPlainObject(object)) {
1770
+ if (hasBrand(DateProtoGetTime, object)) {
1771
+ return 26;
1772
+ }
1773
+ if (hasBrand(RegExpProtoSourceGetter, object)) {
1774
+ return estimateStringSize(regExpToString(object));
1775
+ }
1776
+ const isMap = hasBrand(MapProtoSizeGetter, object);
1777
+ if (isMap || hasBrand(SetProtoSizeGetter, object)) {
1778
+ currentPath.add(object);
1779
+ try {
1780
+ let size = 2;
1781
+ let first = true;
1782
+ const add = (bytes) => {
1783
+ size += bytes;
1784
+ if (maxBytes > 0 && size > maxBytes) {
1785
+ throw new Error(
1786
+ `${isMap ? "Map" : "Set"} serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
1787
+ );
1788
+ }
1789
+ };
1790
+ if (isMap) {
1791
+ const entries = ReflectApply2(MapProtoEntries, object, []);
1792
+ for (const [key, entryValue] of entries) {
1793
+ if (typeof key !== "string" || DANGEROUS_KEYS.has(key)) continue;
1794
+ if (!first) size += 1;
1795
+ first = false;
1796
+ add(estimateStringSize(key) + 1);
1797
+ add(estimateSerializedSize(entryValue, maxBytes, depth + 1, maxDepth, currentPath));
1798
+ }
1799
+ } else {
1800
+ const items = ReflectApply2(SetProtoValues, object, []);
1801
+ for (const item of items) {
1802
+ if (!first) size += 1;
1803
+ first = false;
1804
+ add(estimateSerializedSize(item, maxBytes, depth + 1, maxDepth, currentPath) || 4);
1805
+ }
1806
+ }
1807
+ return size;
1808
+ } finally {
1809
+ currentPath.delete(object);
1810
+ }
1811
+ }
1812
+ }
1813
+ currentPath.add(object);
1814
+ try {
1815
+ let size = 2;
1816
+ const keys = ObjectKeys(object);
1817
+ let first = true;
1818
+ for (const key of keys) {
1819
+ if (DANGEROUS_KEYS.has(key)) continue;
1820
+ let propValue;
1821
+ try {
1822
+ propValue = ReflectGet(object, key);
1823
+ } catch {
1824
+ continue;
1825
+ }
1826
+ if (!first) size += 1;
1827
+ first = false;
1828
+ size += estimateStringSize(key) + 1;
1829
+ size += estimateSerializedSize(propValue, maxBytes, depth + 1, maxDepth, currentPath);
1830
+ if (maxBytes > 0 && size > maxBytes) {
1831
+ throw new Error(
1832
+ `Object serialization would exceed limit: estimated ${size}+ > ${maxBytes} bytes. This often indicates repeated references to large strings that expand during JSON serialization.`
1833
+ );
1834
+ }
1835
+ }
1836
+ return size;
1837
+ } finally {
1838
+ currentPath.delete(object);
1839
+ }
1840
+ }
1841
+ return 0;
1842
+ }
1843
+ function readProperty2(target, key) {
1844
+ try {
1845
+ return ReflectGet(target, key);
1846
+ } catch {
1847
+ return void 0;
1848
+ }
1849
+ }
1850
+ function checkSerializedSize(value, maxBytes) {
1851
+ try {
1852
+ const estimatedBytes = estimateSerializedSize(value, maxBytes);
1853
+ return { ok: true, estimatedBytes };
1854
+ } catch (err) {
1855
+ return { ok: false, error: err instanceof Error ? err.message : "Unknown error" };
1856
+ }
1857
+ }
1858
+
1859
+ // libs/core/src/interpreter/safe-globals.ts
1860
+ var MAX_JSON_TEXT_BYTES = 32 * 1024 * 1024;
1861
+ var MAX_JSON_INDENT = 10;
1862
+ function indentationSize(value, indent, limit, depth, path) {
1863
+ if (value === null || typeof value !== "object" || path.has(value)) return 0;
1864
+ const isArray = Array.isArray(value);
1865
+ const keys = isArray ? void 0 : Object.keys(value);
1866
+ const count = isArray ? value.length : keys.length;
1867
+ if (count === 0) return 0;
1868
+ let size = count * (1 + indent * (depth + 1) + (isArray ? 0 : 1)) + 1 + indent * depth;
1869
+ path.add(value);
1870
+ for (let index = 0; index < count && size <= limit; index++) {
1871
+ const item = isArray ? value[index] : value[keys[index]];
1872
+ size += indentationSize(item, indent, limit - size, depth + 1, path);
1873
+ }
1874
+ path.delete(value);
1875
+ return size;
1876
+ }
1877
+ function utf8Length(text) {
1878
+ let bytes = 0;
1879
+ for (let index = 0; index < text.length; index++) {
1880
+ const code = text.charCodeAt(index);
1881
+ if (code < 128) bytes += 1;
1882
+ else if (code < 2048) bytes += 2;
1883
+ else if (code >= 55296 && code <= 56319 && index + 1 < text.length) {
1884
+ const next = text.charCodeAt(index + 1);
1885
+ if (next >= 56320 && next <= 57343) {
1886
+ bytes += 4;
1887
+ index++;
1888
+ } else bytes += 3;
1889
+ } else bytes += 3;
1890
+ }
1891
+ return bytes;
1892
+ }
1893
+ function indentOf(space) {
1894
+ if (typeof space === "number") return Math.max(0, Math.min(MAX_JSON_INDENT, Math.floor(space) || 0));
1895
+ if (typeof space === "string") return utf8Length(space.slice(0, MAX_JSON_INDENT));
1896
+ return 0;
1897
+ }
1898
+ function parsedJsonCost(text) {
1899
+ let structural = 0;
1900
+ for (let index = 0; index < text.length; index++) {
1901
+ const code = text.charCodeAt(index);
1902
+ if (code === 44 || code === 58 || code === 91 || code === 123) structural++;
1903
+ }
1904
+ return text.length * 2 + structural * 16;
1905
+ }
1906
+ function frozenRecord(members) {
1907
+ const record = /* @__PURE__ */ Object.create(null);
1908
+ for (const key of Object.keys(members)) record[key] = members[key];
1909
+ return Object.freeze(record);
1910
+ }
1911
+ function frozenFunction(fn, members) {
1912
+ for (const key of Object.keys(members)) {
1913
+ Object.defineProperty(fn, key, { value: members[key], enumerable: true });
1914
+ }
1915
+ return Object.freeze(fn);
1916
+ }
1917
+ function tooLong() {
1918
+ throw new RangeError(`An array cannot be longer than ${MAX_ARRAY_LENGTH} items`);
1919
+ }
1920
+ function checkedLength(value) {
1921
+ const length = Number(value);
1922
+ if (!Number.isInteger(length) || length < 0) throw new RangeError("Invalid array length");
1923
+ if (length > MAX_ARRAY_LENGTH) tooLong();
1924
+ return length;
1925
+ }
1926
+ function dataKeys(value) {
1927
+ return Object.keys(value).filter((key) => !isBlockedKey(key));
1928
+ }
1929
+ var SafeMath = (() => {
1930
+ const members = {};
1931
+ for (const key of Object.getOwnPropertyNames(Math)) {
1932
+ members[key] = Math[key];
1933
+ }
1934
+ return frozenRecord(members);
1935
+ })();
1936
+ var SafeJSON = frozenRecord({
1937
+ parse(text, reviver) {
1938
+ if (reviver !== void 0) throw new TypeError("JSON.parse does not take a reviver in the sandbox");
1939
+ return JSON.parse(String(text));
1940
+ },
1941
+ stringify(value, replacer, space) {
1942
+ if (typeof replacer === "function") {
1943
+ throw new TypeError("JSON.stringify does not take a replacer function in the sandbox");
1944
+ }
1945
+ const size = checkSerializedSize(value, MAX_JSON_TEXT_BYTES);
1946
+ if (!size.ok) throw new RangeError(`JSON.stringify: the text would be too large (${size.error})`);
1947
+ const indent = indentOf(space);
1948
+ if (indent > 0) {
1949
+ const budget = MAX_JSON_TEXT_BYTES - size.estimatedBytes;
1950
+ if (indentationSize(value, indent, budget, 0, /* @__PURE__ */ new Set()) > budget) {
1951
+ throw new RangeError("JSON.stringify: the text would be too large with this indentation");
1952
+ }
1953
+ }
1954
+ return JSON.stringify(
1955
+ value,
1956
+ Array.isArray(replacer) ? replacer : void 0,
1957
+ space
1958
+ );
1959
+ }
1960
+ });
1961
+ chargedBeforeCall(SafeJSON["parse"], (args) => parsedJsonCost(String(args[0])));
1962
+ takesArraysAsData(SafeJSON["stringify"]);
1963
+ var SafeObject = frozenRecord({
1964
+ keys: (value) => dataKeys(value),
1965
+ values: (value) => dataKeys(value).map((key) => value[key]),
1966
+ entries: (value) => dataKeys(value).map((key) => [key, value[key]]),
1967
+ fromEntries(entries) {
1968
+ const result = {};
1969
+ let count = 0;
1970
+ for (const entry of entries) {
1971
+ if (++count > MAX_ARRAY_LENGTH) tooLong();
1972
+ if (entry === null || typeof entry !== "object") throw new TypeError("Each entry must be a [key, value] pair");
1973
+ assertArrayTextWithinLimit(entry[0]);
1974
+ const key = String(entry[0]);
1975
+ if (!isBlockedKey(key)) result[key] = entry[1];
1976
+ }
1977
+ return result;
1978
+ },
1979
+ assign(target, ...sources) {
1980
+ if (!isScriptData(target) || Object.isFrozen(target)) {
1981
+ throw new TypeError("Object.assign needs an object or array the script created as its target");
1982
+ }
1983
+ for (const source of sources) {
1984
+ if (source === null || source === void 0) continue;
1985
+ for (const key of dataKeys(source)) {
1986
+ target[key] = source[key];
1987
+ }
1988
+ }
1989
+ return target;
1990
+ },
1991
+ freeze: (value) => isScriptData(value) ? Object.freeze(value) : value,
1992
+ isFrozen: (value) => Object.isFrozen(value),
1993
+ is: (left, right) => Object.is(left, right),
1994
+ hasOwn(value, key) {
1995
+ assertArrayTextWithinLimit(key);
1996
+ const name = String(key);
1997
+ return !isBlockedKey(name) && Object.prototype.hasOwnProperty.call(Object(value), name);
1998
+ }
1999
+ });
2000
+ for (const key of Object.keys(SafeObject)) takesArraysAsData(SafeObject[key]);
2001
+ function makeArray(args) {
2002
+ if (args.length === 1 && typeof args[0] === "number") return new Array(checkedLength(args[0]));
2003
+ return [...args];
2004
+ }
2005
+ var SafeArray = frozenFunction((...args) => makeArray(args), {
2006
+ isArray: (value) => Array.isArray(value),
2007
+ of: (...items) => [...items],
2008
+ from(source, map) {
2009
+ if (map !== void 0) throw new TypeError("Array.from does not take a function in the sandbox");
2010
+ if (source === null || source === void 0) throw new TypeError("Array.from needs a value");
2011
+ const result = [];
2012
+ if (typeof source[Symbol.iterator] === "function") {
2013
+ for (const item of source) {
2014
+ if (result.length >= MAX_ARRAY_LENGTH) tooLong();
2015
+ result.push(item);
2016
+ }
2017
+ return result;
2018
+ }
2019
+ const length = checkedLength(source.length ?? 0);
2020
+ for (let index = 0; index < length; index++) result.push(source[index]);
2021
+ return result;
2022
+ }
2023
+ });
2024
+ takesArraysAsData(SafeArray);
2025
+ for (const key of Object.keys(SafeArray)) {
2026
+ takesArraysAsData(SafeArray[key]);
2027
+ }
2028
+ function toStringValue(value) {
2029
+ return typeof value === "function" ? "function () { [sandboxed code] }" : String(value);
2030
+ }
2031
+ var SafeString = frozenFunction((...args) => args.length === 0 ? "" : toStringValue(args[0]), {
2032
+ fromCharCode: (...codes) => String.fromCharCode(...codes),
2033
+ fromCodePoint: (...codes) => String.fromCodePoint(...codes)
2034
+ });
2035
+ var SafeNumber = frozenFunction((...args) => args.length === 0 ? 0 : Number(args[0]), {
2036
+ isFinite: (value) => Number.isFinite(value),
2037
+ isInteger: (value) => Number.isInteger(value),
2038
+ isNaN: (value) => Number.isNaN(value),
2039
+ isSafeInteger: (value) => Number.isSafeInteger(value),
2040
+ parseFloat: (value) => Number.parseFloat(String(value)),
2041
+ parseInt: (value, radix) => Number.parseInt(String(value), radix),
2042
+ EPSILON: Number.EPSILON,
2043
+ MAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER,
2044
+ MIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER,
2045
+ MAX_VALUE: Number.MAX_VALUE,
2046
+ MIN_VALUE: Number.MIN_VALUE,
2047
+ POSITIVE_INFINITY: Number.POSITIVE_INFINITY,
2048
+ NEGATIVE_INFINITY: Number.NEGATIVE_INFINITY,
2049
+ NaN: Number.NaN
2050
+ });
2051
+ function makeDate(args) {
2052
+ if (args.length === 0) return /* @__PURE__ */ new Date();
2053
+ if (args.length === 1) return new Date(args[0]);
2054
+ return new Date(...args);
2055
+ }
2056
+ var SafeDate = frozenFunction(() => (/* @__PURE__ */ new Date()).toString(), {
2057
+ now: () => Date.now(),
2058
+ parse: (text) => Date.parse(String(text)),
2059
+ UTC: (...parts) => Date.UTC(...parts)
2060
+ });
2061
+ var ERROR_TYPES = ["Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError", "EvalError", "URIError"];
2062
+ function errorType(name) {
2063
+ const make = (args) => createScriptError(name, args.length === 0 || args[0] === void 0 ? "" : toStringValue(args[0]));
2064
+ return {
2065
+ facade: frozenFunction((...args) => make(args), {}),
2066
+ make,
2067
+ // Every error is an `Error`; the other types are told apart by their name.
2068
+ isInstance: (value) => isScriptError(value) && (name === "Error" || value.name === name)
2069
+ };
2070
+ }
2071
+ var SAFE_ERRORS = ERROR_TYPES.map((name) => [name, errorType(name)]);
2072
+ var SAFE_GLOBALS = Object.freeze({
2073
+ Math: SafeMath,
2074
+ JSON: SafeJSON,
2075
+ Object: SafeObject,
2076
+ Array: SafeArray,
2077
+ String: SafeString,
2078
+ Number: SafeNumber,
2079
+ Date: SafeDate,
2080
+ ...Object.fromEntries(SAFE_ERRORS.map(([name, type]) => [name, type.facade])),
2081
+ ...Object.fromEntries(SAFE_ERRORS.map(([name, type]) => [`__safe_${name}`, type.facade])),
2082
+ NaN: Number.NaN,
2083
+ Infinity: Number.POSITIVE_INFINITY,
2084
+ undefined: void 0,
2085
+ isNaN: Object.freeze((value) => Number.isNaN(Number(value))),
2086
+ isFinite: Object.freeze((value) => Number.isFinite(Number(value))),
2087
+ parseFloat: Object.freeze((value) => Number.parseFloat(String(value))),
2088
+ parseInt: Object.freeze(
2089
+ (value, radix) => Number.parseInt(String(value), radix)
2090
+ ),
2091
+ encodeURI: Object.freeze((value) => encodeURI(String(value))),
2092
+ encodeURIComponent: Object.freeze((value) => encodeURIComponent(String(value))),
2093
+ decodeURI: Object.freeze((value) => decodeURI(String(value))),
2094
+ decodeURIComponent: Object.freeze((value) => decodeURIComponent(String(value)))
2095
+ });
2096
+ convertsArguments(SafeString, 1);
2097
+ convertsArguments(SafeNumber, 1);
2098
+ convertsArguments(SafeDate, 0);
2099
+ for (const [name, count] of [
2100
+ ["isFinite", 0],
2101
+ ["isInteger", 0],
2102
+ ["isNaN", 0],
2103
+ ["isSafeInteger", 0],
2104
+ ["parseFloat", 1],
2105
+ ["parseInt", 2]
2106
+ ]) {
2107
+ convertsArguments(SafeNumber[name], count);
2108
+ }
2109
+ convertsArguments(SafeDate["now"], 0);
2110
+ convertsArguments(SafeDate["parse"], 1);
2111
+ for (const [name, count] of [
2112
+ ["isNaN", 1],
2113
+ ["isFinite", 1],
2114
+ ["parseFloat", 1],
2115
+ ["parseInt", 2],
2116
+ ["encodeURI", 1],
2117
+ ["encodeURIComponent", 1],
2118
+ ["decodeURI", 1],
2119
+ ["decodeURIComponent", 1]
2120
+ ]) {
2121
+ convertsArguments(SAFE_GLOBALS[name], count);
2122
+ }
2123
+ for (const [, type] of SAFE_ERRORS) convertsArguments(type.facade, 1);
2124
+ var MATH_PARAMETERS = {
2125
+ abs: 1,
2126
+ acos: 1,
2127
+ acosh: 1,
2128
+ asin: 1,
2129
+ asinh: 1,
2130
+ atan: 1,
2131
+ atanh: 1,
2132
+ atan2: 2,
2133
+ cbrt: 1,
2134
+ ceil: 1,
2135
+ clz32: 1,
2136
+ cos: 1,
2137
+ cosh: 1,
2138
+ exp: 1,
2139
+ expm1: 1,
2140
+ floor: 1,
2141
+ fround: 1,
2142
+ imul: 2,
2143
+ log: 1,
2144
+ log1p: 1,
2145
+ log10: 1,
2146
+ log2: 1,
2147
+ pow: 2,
2148
+ random: 0,
2149
+ round: 1,
2150
+ sign: 1,
2151
+ sin: 1,
2152
+ sinh: 1,
2153
+ sqrt: 1,
2154
+ tan: 1,
2155
+ tanh: 1,
2156
+ trunc: 1
2157
+ };
2158
+ for (const name of Object.keys(MATH_PARAMETERS)) {
2159
+ const fn = SafeMath[name];
2160
+ if (typeof fn === "function") convertsArguments(fn, MATH_PARAMETERS[name]);
2161
+ }
2162
+ function createSafeGlobals() {
2163
+ return {
2164
+ globals: { ...SAFE_GLOBALS },
2165
+ constructors: new Map([
2166
+ [SafeDate, makeDate],
2167
+ [SafeArray, makeArray],
2168
+ ...SAFE_ERRORS.map(([, type]) => [type.facade, type.make])
2169
+ ]),
2170
+ instanceChecks: new Map([
2171
+ [SafeDate, (value) => value instanceof Date],
2172
+ [SafeArray, (value) => Array.isArray(value)],
2173
+ [SafeObject, (value) => typeof value === "object" && value !== null || typeof value === "function"],
2174
+ ...SAFE_ERRORS.map(([, type]) => [type.facade, type.isInstance])
2175
+ ])
2176
+ };
2177
+ }
2178
+
2179
+ // libs/core/src/memory-tracker.ts
2180
+ var MemoryLimitError = class _MemoryLimitError extends Error {
2181
+ constructor(message, usedBytes, limitBytes) {
2182
+ super(message);
2183
+ this.usedBytes = usedBytes;
2184
+ this.limitBytes = limitBytes;
2185
+ this.name = "MemoryLimitError";
2186
+ if (Error.captureStackTrace) {
2187
+ Error.captureStackTrace(this, _MemoryLimitError);
2188
+ }
2189
+ }
2190
+ /** Error code for identification */
2191
+ code = "MEMORY_LIMIT_EXCEEDED";
2192
+ };
2193
+ function estimateStringSize2(str) {
2194
+ return str.length * 2 + 40;
2195
+ }
2196
+ function estimateArraySize(length, elementEstimate = 8) {
2197
+ return 32 + length * elementEstimate;
2198
+ }
2199
+ function estimateObjectSize(propertyCount) {
2200
+ return 56 + propertyCount * 32;
2201
+ }
2202
+ var MemoryTracker = class {
2203
+ trackedBytes = 0;
2204
+ peakTrackedBytes = 0;
2205
+ allocationCount = 0;
2206
+ config;
2207
+ constructor(config = {}) {
2208
+ this.config = {
2209
+ memoryLimit: config.memoryLimit ?? 0,
2210
+ trackStrings: config.trackStrings ?? true,
2211
+ trackArrays: config.trackArrays ?? true,
2212
+ trackObjects: config.trackObjects ?? true
2213
+ };
2214
+ }
2215
+ /**
2216
+ * Start tracking (resets all counters)
2217
+ */
2218
+ start() {
2219
+ this.trackedBytes = 0;
2220
+ this.peakTrackedBytes = 0;
2221
+ this.allocationCount = 0;
2222
+ }
2223
+ /**
2224
+ * Track an allocation
2225
+ *
2226
+ * @param bytes Number of bytes allocated
2227
+ * @throws {MemoryLimitError} If memory limit is exceeded
2228
+ */
2229
+ track(bytes) {
2230
+ if (typeof bytes !== "number" || Number.isNaN(bytes)) {
2231
+ if (this.config.memoryLimit > 0) {
2232
+ throw new MemoryLimitError(
2233
+ "Memory limit exceeded: allocation size is not a number",
2234
+ this.trackedBytes,
2235
+ this.config.memoryLimit
2236
+ );
2237
+ }
2238
+ return;
2239
+ }
2240
+ if (bytes <= 0) return;
2241
+ this.trackedBytes += bytes;
2242
+ this.allocationCount++;
2243
+ if (this.trackedBytes > this.peakTrackedBytes) {
2244
+ this.peakTrackedBytes = this.trackedBytes;
2245
+ }
2246
+ if (this.config.memoryLimit > 0 && this.trackedBytes > this.config.memoryLimit) {
2247
+ throw new MemoryLimitError(
2248
+ `Memory limit exceeded: ${this.formatBytes(this.trackedBytes)} used > ${this.formatBytes(
2249
+ this.config.memoryLimit
2250
+ )} limit`,
2251
+ this.trackedBytes,
2252
+ this.config.memoryLimit
2253
+ );
2254
+ }
2255
+ }
2256
+ /**
2257
+ * Track a string allocation
2258
+ *
2259
+ * @param str String that was allocated
2260
+ * @throws {MemoryLimitError} If memory limit is exceeded
2261
+ */
2262
+ trackString(str) {
2263
+ if (!this.config.trackStrings) return;
2264
+ this.track(estimateStringSize2(str));
2265
+ }
2266
+ /**
2267
+ * Track an array allocation
2268
+ *
2269
+ * @param length Array length
2270
+ * @param elementEstimate Optional per-element size estimate
2271
+ * @throws {MemoryLimitError} If memory limit is exceeded
2272
+ */
2273
+ trackArray(length, elementEstimate) {
2274
+ if (!this.config.trackArrays) return;
2275
+ this.track(estimateArraySize(length, elementEstimate));
2276
+ }
2277
+ /**
2278
+ * Track an object allocation
2279
+ *
2280
+ * @param propertyCount Number of properties
2281
+ * @throws {MemoryLimitError} If memory limit is exceeded
2282
+ */
2283
+ trackObject(propertyCount) {
2284
+ if (!this.config.trackObjects) return;
2285
+ this.track(estimateObjectSize(propertyCount));
2286
+ }
2287
+ /**
2288
+ * Release tracked memory (for GC simulation)
2289
+ *
2290
+ * @param bytes Number of bytes to release
2291
+ */
2292
+ release(bytes) {
2293
+ if (typeof bytes !== "number" || !(bytes > 0)) return;
2294
+ this.trackedBytes = Math.max(0, this.trackedBytes - bytes);
2295
+ }
2296
+ /**
2297
+ * Get current memory usage snapshot
2298
+ *
2299
+ * @returns Snapshot of memory usage
2300
+ */
2301
+ getSnapshot() {
2302
+ return {
2303
+ trackedBytes: this.trackedBytes,
2304
+ peakTrackedBytes: this.peakTrackedBytes,
2305
+ allocationCount: this.allocationCount
2306
+ };
2307
+ }
2308
+ /**
2309
+ * Get configured memory limit
2310
+ *
2311
+ * @returns Memory limit in bytes (0 = unlimited)
2312
+ */
2313
+ getLimit() {
2314
+ return this.config.memoryLimit;
2315
+ }
2316
+ /**
2317
+ * Check if tracking is enabled
2318
+ *
2319
+ * @returns True if any tracking is enabled
2320
+ */
2321
+ isEnabled() {
2322
+ return this.config.trackStrings || this.config.trackArrays || this.config.trackObjects;
2323
+ }
2324
+ /**
2325
+ * Format bytes as human-readable string
2326
+ *
2327
+ * @param bytes Number of bytes
2328
+ * @returns Formatted string (e.g., "10.5MB")
2329
+ */
2330
+ formatBytes(bytes) {
2331
+ if (bytes >= 1024 * 1024 * 1024) return `${(bytes / 1024 / 1024 / 1024).toFixed(2)}GB`;
2332
+ if (bytes >= 1024 * 1024) return `${(bytes / 1024 / 1024).toFixed(2)}MB`;
2333
+ if (bytes >= 1024) return `${(bytes / 1024).toFixed(2)}KB`;
2334
+ return `${bytes}B`;
2335
+ }
2336
+ };
2337
+
2338
+ // libs/core/src/sidecar/reference-config.ts
2339
+ var REFERENCE_CONFIGS = {
2340
+ /**
2341
+ * STRICT: Maximum security for untrusted code
2342
+ *
2343
+ * - Very small limits to prevent any memory-based attacks
2344
+ * - No composite handles (references cannot be concatenated)
2345
+ * - Aggressive extraction threshold
2346
+ */
2347
+ STRICT: {
2348
+ maxTotalSize: 16 * 1024 * 1024,
2349
+ // 16MB total
2350
+ maxReferenceSize: 4 * 1024 * 1024,
2351
+ // 4MB per reference
2352
+ extractionThreshold: 64 * 1024,
2353
+ // 64KB extraction threshold
2354
+ maxResolvedSize: 8 * 1024 * 1024,
2355
+ // 8MB max resolved
2356
+ allowComposites: false,
2357
+ // No concatenation of references
2358
+ maxReferenceCount: 50,
2359
+ // Max 50 references
2360
+ maxResolutionDepth: 5
2361
+ // Shallow resolution
2362
+ },
2363
+ /**
2364
+ * SECURE: High security with more headroom
2365
+ *
2366
+ * - Moderate limits for trusted AI code
2367
+ * - No composite handles by default
2368
+ * - Standard extraction threshold
2369
+ */
2370
+ SECURE: {
2371
+ maxTotalSize: 64 * 1024 * 1024,
2372
+ // 64MB total
2373
+ maxReferenceSize: 16 * 1024 * 1024,
2374
+ // 16MB per reference
2375
+ extractionThreshold: 256 * 1024,
2376
+ // 256KB extraction threshold
2377
+ maxResolvedSize: 32 * 1024 * 1024,
2378
+ // 32MB max resolved
2379
+ allowComposites: false,
2380
+ // No concatenation of references
2381
+ maxReferenceCount: 100,
2382
+ // Max 100 references
2383
+ maxResolutionDepth: 10
2384
+ // Moderate resolution depth
2385
+ },
2386
+ /**
2387
+ * STANDARD: Balanced security and functionality
2388
+ *
2389
+ * - Standard limits for internal tools
2390
+ * - Composite handles allowed
2391
+ * - Larger extraction threshold
2392
+ */
2393
+ STANDARD: {
2394
+ maxTotalSize: 256 * 1024 * 1024,
2395
+ // 256MB total
2396
+ maxReferenceSize: 64 * 1024 * 1024,
2397
+ // 64MB per reference
2398
+ extractionThreshold: 1024 * 1024,
2399
+ // 1MB extraction threshold
2400
+ maxResolvedSize: 128 * 1024 * 1024,
2401
+ // 128MB max resolved
2402
+ allowComposites: true,
2403
+ // Allow concatenation
2404
+ maxReferenceCount: 500,
2405
+ // Max 500 references
2406
+ maxResolutionDepth: 20
2407
+ // Deep resolution
2408
+ },
2409
+ /**
2410
+ * PERMISSIVE: Minimal restrictions
2411
+ *
2412
+ * - Large limits for development/debugging
2413
+ * - All features enabled
2414
+ * - High extraction threshold
2415
+ */
2416
+ PERMISSIVE: {
2417
+ maxTotalSize: 1024 * 1024 * 1024,
2418
+ // 1GB total
2419
+ maxReferenceSize: 256 * 1024 * 1024,
2420
+ // 256MB per reference
2421
+ extractionThreshold: 4 * 1024 * 1024,
2422
+ // 4MB extraction threshold
2423
+ maxResolvedSize: 512 * 1024 * 1024,
2424
+ // 512MB max resolved
2425
+ allowComposites: true,
2426
+ // Allow concatenation
2427
+ maxReferenceCount: 1e3,
2428
+ // Max 1000 references
2429
+ maxResolutionDepth: 50
2430
+ // Very deep resolution
2431
+ }
2432
+ };
2433
+ 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
+ function isReferenceId(value) {
2435
+ return typeof value === "string" && REF_ID_PATTERN.test(value);
2436
+ }
2437
+
2438
+ // libs/core/src/sidecar/reference-resolver.ts
2439
+ var ReflectGet2 = Reflect.get;
2440
+ var NumberIsFinite2 = Number.isFinite;
2441
+ var MathFloor2 = Math.floor;
2442
+ var MAX_TRAVERSAL_LENGTH = 1e6;
2443
+ function untrustedLength(value) {
2444
+ const rawLen = ReflectGet2(value, "length");
2445
+ if (typeof rawLen !== "number" || !NumberIsFinite2(rawLen) || rawLen < 0) {
2446
+ return 0;
2447
+ }
2448
+ const len = MathFloor2(rawLen);
2449
+ if (len > MAX_TRAVERSAL_LENGTH) {
2450
+ throw new ResolutionLimitError(
2451
+ `Array length ${len} exceeds maximum traversal limit (${MAX_TRAVERSAL_LENGTH})`,
2452
+ "MAX_TRAVERSAL_LENGTH",
2453
+ MAX_TRAVERSAL_LENGTH,
2454
+ len
2455
+ );
2456
+ }
2457
+ return len;
2458
+ }
2459
+ function untrustedAt(value, index) {
2460
+ try {
2461
+ return ReflectGet2(value, index);
2462
+ } catch {
2463
+ return void 0;
2464
+ }
2465
+ }
2466
+ var ResolutionLimitError = class _ResolutionLimitError extends Error {
2467
+ constructor(message, code, limit, actual) {
2468
+ super(message);
2469
+ this.code = code;
2470
+ this.limit = limit;
2471
+ this.actual = actual;
2472
+ this.name = "ResolutionLimitError";
2473
+ Object.setPrototypeOf(this, _ResolutionLimitError.prototype);
2474
+ }
2475
+ };
2476
+ function isCompositeHandle(value) {
2477
+ const obj = value;
2478
+ return typeof value === "object" && value !== null && obj["__type"] === "composite" && Array.isArray(obj["__parts"]);
2479
+ }
2480
+ var ReferenceResolver = class {
2481
+ constructor(sidecar, config) {
2482
+ this.sidecar = sidecar;
2483
+ this.config = config;
2484
+ }
2485
+ /**
2486
+ * Predict the expanded size of a value WITHOUT allocating memory
2487
+ *
2488
+ * This calculates the total size if all references were resolved,
2489
+ * enabling fail-fast before any memory allocation occurs.
2490
+ *
2491
+ * @param value - The value to analyze
2492
+ * @param depth - Current recursion depth (internal)
2493
+ * @returns Estimated size in bytes
2494
+ * @throws ResolutionLimitError if depth limit exceeded
2495
+ */
2496
+ predictExpandedSize(value, depth = 0) {
2497
+ if (depth > this.config.maxResolutionDepth) {
2498
+ throw new ResolutionLimitError(
2499
+ `Maximum resolution depth exceeded (${this.config.maxResolutionDepth})`,
2500
+ "MAX_RESOLUTION_DEPTH",
2501
+ this.config.maxResolutionDepth,
2502
+ depth
2503
+ );
2504
+ }
2505
+ if (isReferenceId(value)) {
2506
+ const size = this.sidecar.getSize(value);
2507
+ if (size === void 0) {
2508
+ return value.length;
2509
+ }
2510
+ return size;
2511
+ }
2512
+ if (isCompositeHandle(value)) {
2513
+ const parts = value.__parts;
2514
+ const len = untrustedLength(parts);
2515
+ let sum = 0;
2516
+ for (let i = 0; i < len; i++) {
2517
+ sum += this.predictExpandedSize(untrustedAt(parts, i), depth + 1);
2518
+ }
2519
+ return sum;
2520
+ }
2521
+ if (typeof value === "string") {
2522
+ return Buffer.byteLength(value, "utf-8");
2523
+ }
2524
+ if (Array.isArray(value)) {
2525
+ const len = untrustedLength(value);
2526
+ let sum = 0;
2527
+ for (let i = 0; i < len; i++) {
2528
+ sum += this.predictExpandedSize(untrustedAt(value, i), depth + 1);
2529
+ }
2530
+ return sum;
2531
+ }
2532
+ if (value !== null && typeof value === "object") {
2533
+ return Object.values(value).reduce((sum, val) => {
2534
+ return sum + this.predictExpandedSize(val, depth + 1);
2535
+ }, 0);
2536
+ }
2537
+ if (typeof value === "number") return 8;
2538
+ if (typeof value === "boolean") return 1;
2539
+ if (value === null || value === void 0) return 0;
2540
+ return 0;
2541
+ }
2542
+ /**
2543
+ * Check if resolution would exceed size limits
2544
+ *
2545
+ * @param value - The value to check
2546
+ * @returns true if resolution would exceed maxResolvedSize
2547
+ */
2548
+ wouldExceedLimit(value) {
2549
+ try {
2550
+ const size = this.predictExpandedSize(value);
2551
+ return size > this.config.maxResolvedSize;
2552
+ } catch {
2553
+ return true;
2554
+ }
2555
+ }
2556
+ /**
2557
+ * Resolve all reference IDs in a value tree
2558
+ *
2559
+ * Recursively walks the value and replaces reference IDs with
2560
+ * their actual data from the sidecar.
2561
+ *
2562
+ * @param value - The value to resolve
2563
+ * @param depth - Current recursion depth (internal)
2564
+ * @returns The resolved value with references replaced
2565
+ * @throws ResolutionLimitError if limits exceeded
2566
+ * @throws ReferenceNotFoundError if a reference doesn't exist
2567
+ */
2568
+ resolve(value, depth = 0) {
2569
+ if (depth > this.config.maxResolutionDepth) {
2570
+ throw new ResolutionLimitError(
2571
+ `Maximum resolution depth exceeded during resolution (${this.config.maxResolutionDepth})`,
2572
+ "MAX_RESOLUTION_DEPTH",
2573
+ this.config.maxResolutionDepth,
2574
+ depth
2575
+ );
2576
+ }
2577
+ if (isReferenceId(value)) {
2578
+ const data = this.sidecar.retrieveString(value);
2579
+ if (data === void 0) {
2580
+ throw new Error(`Unknown reference: ${value}`);
2581
+ }
2582
+ return data;
2583
+ }
2584
+ if (isCompositeHandle(value)) {
2585
+ if (!this.config.allowComposites) {
2586
+ throw new Error(
2587
+ "Cannot concatenate reference IDs. Pass references directly to callTool arguments. Composite handles are disabled in the current security configuration."
2588
+ );
2589
+ }
2590
+ return this.resolveComposite(value, depth);
2591
+ }
2592
+ if (typeof value === "string") {
2593
+ return value;
2594
+ }
2595
+ if (Array.isArray(value)) {
2596
+ const len = untrustedLength(value);
2597
+ const out = [];
2598
+ for (let i = 0; i < len; i++) {
2599
+ out[i] = this.resolve(untrustedAt(value, i), depth + 1);
2600
+ }
2601
+ return out;
2602
+ }
2603
+ if (value !== null && typeof value === "object") {
2604
+ const resolved = /* @__PURE__ */ Object.create(null);
2605
+ for (const [key, val] of Object.entries(value)) {
2606
+ resolved[key] = this.resolve(val, depth + 1);
2607
+ }
2608
+ return resolved;
2609
+ }
2610
+ return value;
2611
+ }
2612
+ /**
2613
+ * Resolve a composite handle by concatenating its parts
2614
+ */
2615
+ resolveComposite(handle, depth) {
2616
+ const out = [];
2617
+ const source = handle.__parts;
2618
+ const len = untrustedLength(source);
2619
+ for (let i = 0; i < len; i++) {
2620
+ const resolved = this.resolve(untrustedAt(source, i), depth + 1);
2621
+ if (typeof resolved !== "string") {
2622
+ throw new Error(`Composite part resolved to non-string: ${typeof resolved}`);
2623
+ }
2624
+ out.push(resolved);
2625
+ }
2626
+ return out.join("");
2627
+ }
2628
+ /**
2629
+ * Check if a value contains any reference IDs
2630
+ *
2631
+ * @param value - The value to check
2632
+ * @param depth - Current recursion depth (internal)
2633
+ * @returns true if the value or any nested value is a reference
2634
+ */
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;
2647
+ }
2648
+ }
2649
+ return false;
2650
+ }
2651
+ if (value !== null && typeof value === "object") {
2652
+ return Object.values(value).some((val) => this.containsReferences(val, depth + 1));
2653
+ }
2654
+ return false;
2655
+ }
2656
+ /**
2657
+ * Create a composite handle from multiple reference parts
2658
+ *
2659
+ * Used by __safe_concat__ when allowComposites is true.
2660
+ *
2661
+ * @param parts - Reference IDs or strings to combine
2662
+ * @returns A composite handle or the concatenated string
2663
+ * @throws Error if composites not allowed or limits exceeded
2664
+ */
2665
+ createComposite(parts) {
2666
+ const hasReferences = parts.some((p) => isReferenceId(p));
2667
+ if (!hasReferences) {
2668
+ return parts.join("");
2669
+ }
2670
+ if (!this.config.allowComposites) {
2671
+ throw new Error(
2672
+ "Cannot concatenate reference IDs. Pass references directly to callTool arguments. Composite handles are disabled in the current security configuration."
2673
+ );
2674
+ }
2675
+ const estimatedSize = parts.reduce((sum, part) => {
2676
+ if (isReferenceId(part)) {
2677
+ return sum + (this.sidecar.getSize(part) ?? part.length);
2678
+ }
2679
+ return sum + Buffer.byteLength(part, "utf-8");
2680
+ }, 0);
2681
+ if (estimatedSize > this.config.maxResolvedSize) {
2682
+ throw new ResolutionLimitError(
2683
+ `Composite would exceed maximum resolved size: ${estimatedSize} > ${this.config.maxResolvedSize}`,
2684
+ "MAX_RESOLVED_SIZE",
2685
+ this.config.maxResolvedSize,
2686
+ estimatedSize
2687
+ );
2688
+ }
2689
+ return {
2690
+ __type: "composite",
2691
+ __operation: "concat",
2692
+ __parts: parts,
2693
+ __estimatedSize: estimatedSize
2694
+ };
2695
+ }
2696
+ };
2697
+
2698
+ // libs/core/src/stack-trace.ts
635
2699
  var SENSITIVE_STACK_PATTERNS = [
636
2700
  // Unix file system paths
637
2701
  /\/Users\/[^/]+\/[^\s):]*/gi,
@@ -782,44 +2846,519 @@ function sanitizeStackTrace(stack, sanitize = true) {
782
2846
  return bounded.split("\n").map((line) => FRAME_LINE.test(line) ? REDACTED_FRAME : redactLine(line)).join("\n");
783
2847
  }
784
2848
 
2849
+ // libs/core/src/tool-bridge.ts
2850
+ var TOOL_BRIDGE_PROTOCOL_VERSION = 1;
2851
+ function utf8ByteLength(value) {
2852
+ return Buffer.byteLength(value, "utf8");
2853
+ }
2854
+ function jsonReplacer(_key, value) {
2855
+ if (typeof value === "bigint") return value.toString();
2856
+ if (typeof value === "number" && !Number.isFinite(value)) return null;
2857
+ return value;
2858
+ }
2859
+ function safeJsonStringify(value) {
2860
+ return JSON.stringify(value, jsonReplacer);
2861
+ }
2862
+ function truncateForErrorMessage(value, maxChars) {
2863
+ if (value.length <= maxChars) return value;
2864
+ return `${value.slice(0, maxChars)}\u2026`;
2865
+ }
2866
+ function toErrorPayload(error, fallbackName, fallbackMessage, code) {
2867
+ const safe = {
2868
+ name: fallbackName,
2869
+ message: fallbackMessage,
2870
+ code
2871
+ };
2872
+ if (error && typeof error === "object") {
2873
+ const maybeName = error.name;
2874
+ const maybeMessage = error.message;
2875
+ const maybeCode = error.code;
2876
+ if (typeof maybeName === "string" && maybeName) safe.name = maybeName;
2877
+ if (typeof maybeMessage === "string" && maybeMessage) safe.message = maybeMessage;
2878
+ if (typeof maybeCode === "string" && maybeCode) safe.code = maybeCode;
2879
+ } else if (typeof error === "string" && error) {
2880
+ safe.message = error;
2881
+ }
2882
+ safe.message = truncateForErrorMessage(String(safe.message || fallbackMessage), 4096);
2883
+ safe.name = truncateForErrorMessage(String(safe.name || fallbackName), 128);
2884
+ return safe;
2885
+ }
2886
+ function serializeResponse(response, maxPayloadBytes) {
2887
+ let json;
2888
+ try {
2889
+ json = safeJsonStringify(response);
2890
+ } catch {
2891
+ json = JSON.stringify({
2892
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
2893
+ ok: false,
2894
+ error: {
2895
+ name: "ToolBridgeError",
2896
+ message: "Tool bridge failed to serialize response",
2897
+ code: "TOOL_BRIDGE_SERIALIZE_FAILED"
2898
+ }
2899
+ });
2900
+ }
2901
+ if (utf8ByteLength(json) <= maxPayloadBytes) return json;
2902
+ const minimal = {
2903
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
2904
+ ok: false,
2905
+ error: {
2906
+ name: "ToolBridgeError",
2907
+ message: "Tool bridge payload exceeded maximum size",
2908
+ code: "TOOL_BRIDGE_PAYLOAD_TOO_LARGE"
2909
+ }
2910
+ };
2911
+ return JSON.stringify(minimal);
2912
+ }
2913
+ function parseToolBridgeRequest(requestJson) {
2914
+ let parsed;
2915
+ try {
2916
+ parsed = JSON.parse(requestJson);
2917
+ } catch {
2918
+ return { ok: false, error: "Tool request must be valid JSON" };
2919
+ }
2920
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2921
+ return { ok: false, error: "Tool request must be a JSON object" };
2922
+ }
2923
+ const v = parsed.v;
2924
+ const tool = parsed.tool;
2925
+ const args = parsed.args;
2926
+ if (v !== TOOL_BRIDGE_PROTOCOL_VERSION) {
2927
+ return { ok: false, error: "Unsupported tool bridge protocol version" };
2928
+ }
2929
+ if (typeof tool !== "string" || !tool) {
2930
+ return { ok: false, error: "Tool name must be a non-empty string" };
2931
+ }
2932
+ if (!args || typeof args !== "object" || Array.isArray(args)) {
2933
+ return { ok: false, error: "Tool arguments must be a JSON object" };
2934
+ }
2935
+ return { ok: true, request: { v: TOOL_BRIDGE_PROTOCOL_VERSION, tool, args } };
2936
+ }
2937
+ function encodeToolBridgeRequest(tool, args) {
2938
+ return safeJsonStringify({ v: TOOL_BRIDGE_PROTOCOL_VERSION, tool, args });
2939
+ }
2940
+ function encodeToolBridgeFailure(name, message, code, maxPayloadBytes) {
2941
+ return serializeResponse(
2942
+ { v: TOOL_BRIDGE_PROTOCOL_VERSION, ok: false, error: { name, message, code } },
2943
+ maxPayloadBytes
2944
+ );
2945
+ }
2946
+ function toolCallLimitMessage(maxToolCalls) {
2947
+ return `Maximum tool call limit exceeded (${maxToolCalls}). This limit prevents runaway script execution.`;
2948
+ }
2949
+ function createRelayedToolBridge(executionContext, options, relay) {
2950
+ const { config, stats } = executionContext;
2951
+ const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
2952
+ return async (requestJson) => {
2953
+ try {
2954
+ if (typeof requestJson !== "string") {
2955
+ return encodeToolBridgeFailure(
2956
+ "ToolBridgeError",
2957
+ "Tool request must be a string",
2958
+ "TOOL_BRIDGE_BAD_REQUEST",
2959
+ maxPayloadBytes
2960
+ );
2961
+ }
2962
+ if (utf8ByteLength(requestJson) > maxPayloadBytes) {
2963
+ return encodeToolBridgeFailure(
2964
+ "ToolBridgeError",
2965
+ `Tool request exceeds maximum size (${maxPayloadBytes} bytes)`,
2966
+ "TOOL_BRIDGE_REQUEST_TOO_LARGE",
2967
+ maxPayloadBytes
2968
+ );
2969
+ }
2970
+ if (executionContext.aborted) {
2971
+ return encodeToolBridgeFailure("AbortError", "Execution aborted", "EXECUTION_ABORTED", maxPayloadBytes);
2972
+ }
2973
+ if (options.updateStats) {
2974
+ stats.toolCallCount++;
2975
+ }
2976
+ if (!options.limitChecked && stats.toolCallCount > config.maxToolCalls) {
2977
+ return encodeToolBridgeFailure(
2978
+ "ToolLimitError",
2979
+ toolCallLimitMessage(config.maxToolCalls),
2980
+ "MAX_TOOL_CALLS_EXCEEDED",
2981
+ maxPayloadBytes
2982
+ );
2983
+ }
2984
+ const responseJson = await relay(requestJson);
2985
+ if (typeof responseJson !== "string" || utf8ByteLength(responseJson) > maxPayloadBytes) {
2986
+ return encodeToolBridgeFailure(
2987
+ "ToolBridgeError",
2988
+ `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
2989
+ "TOOL_BRIDGE_RESPONSE_TOO_LARGE",
2990
+ maxPayloadBytes
2991
+ );
2992
+ }
2993
+ return responseJson;
2994
+ } catch (error) {
2995
+ const safeError = toErrorPayload(error, "ToolBridgeError", "Tool bridge failure", "TOOL_BRIDGE_FAILURE");
2996
+ return serializeResponse({ v: TOOL_BRIDGE_PROTOCOL_VERSION, ok: false, error: safeError }, maxPayloadBytes);
2997
+ }
2998
+ };
2999
+ }
3000
+ function createHostToolBridge(executionContext, options) {
3001
+ if (typeof executionContext.hostToolBridge === "function") {
3002
+ return createRelayedToolBridge(executionContext, options, executionContext.hostToolBridge);
3003
+ }
3004
+ const { config, stats, toolHandler, sidecar, referenceConfig } = executionContext;
3005
+ const maxPayloadBytes = config.toolBridge?.maxPayloadBytes ?? 5 * 1024 * 1024;
3006
+ const resolver = sidecar && referenceConfig ? new ReferenceResolver(sidecar, referenceConfig) : void 0;
3007
+ return async (requestJson) => {
3008
+ try {
3009
+ if (typeof requestJson !== "string") {
3010
+ return serializeResponse(
3011
+ {
3012
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3013
+ ok: false,
3014
+ error: {
3015
+ name: "ToolBridgeError",
3016
+ message: "Tool request must be a string",
3017
+ code: "TOOL_BRIDGE_BAD_REQUEST"
3018
+ }
3019
+ },
3020
+ maxPayloadBytes
3021
+ );
3022
+ }
3023
+ if (utf8ByteLength(requestJson) > maxPayloadBytes) {
3024
+ return serializeResponse(
3025
+ {
3026
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3027
+ ok: false,
3028
+ error: {
3029
+ name: "ToolBridgeError",
3030
+ message: `Tool request exceeds maximum size (${maxPayloadBytes} bytes)`,
3031
+ code: "TOOL_BRIDGE_REQUEST_TOO_LARGE"
3032
+ }
3033
+ },
3034
+ maxPayloadBytes
3035
+ );
3036
+ }
3037
+ if (executionContext.aborted) {
3038
+ return serializeResponse(
3039
+ {
3040
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3041
+ ok: false,
3042
+ error: { name: "AbortError", message: "Execution aborted", code: "EXECUTION_ABORTED" }
3043
+ },
3044
+ maxPayloadBytes
3045
+ );
3046
+ }
3047
+ if (options.updateStats) {
3048
+ stats.toolCallCount++;
3049
+ }
3050
+ if (!options.limitChecked && stats.toolCallCount > config.maxToolCalls) {
3051
+ return serializeResponse(
3052
+ {
3053
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3054
+ ok: false,
3055
+ error: {
3056
+ name: "ToolLimitError",
3057
+ message: toolCallLimitMessage(config.maxToolCalls),
3058
+ code: "MAX_TOOL_CALLS_EXCEEDED"
3059
+ }
3060
+ },
3061
+ maxPayloadBytes
3062
+ );
3063
+ }
3064
+ if (!toolHandler) {
3065
+ return serializeResponse(
3066
+ {
3067
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3068
+ ok: false,
3069
+ error: {
3070
+ name: "ToolBridgeError",
3071
+ message: "No tool handler configured. Cannot execute tool calls.",
3072
+ code: "NO_TOOL_HANDLER"
3073
+ }
3074
+ },
3075
+ maxPayloadBytes
3076
+ );
3077
+ }
3078
+ const parsed = parseToolBridgeRequest(requestJson);
3079
+ if (!parsed.ok) {
3080
+ return serializeResponse(
3081
+ {
3082
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3083
+ ok: false,
3084
+ error: { name: "ToolBridgeError", message: parsed.error, code: "TOOL_BRIDGE_BAD_REQUEST" }
3085
+ },
3086
+ maxPayloadBytes
3087
+ );
3088
+ }
3089
+ const { tool, args } = parsed.request;
3090
+ const sanitizedArgs = sanitizeValue(args, {
3091
+ maxDepth: config.maxSanitizeDepth,
3092
+ maxProperties: config.maxSanitizeProperties,
3093
+ allowDates: false,
3094
+ allowErrors: false
3095
+ });
3096
+ if (!sanitizedArgs || typeof sanitizedArgs !== "object" || Array.isArray(sanitizedArgs)) {
3097
+ return serializeResponse(
3098
+ {
3099
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3100
+ ok: false,
3101
+ error: { name: "TypeError", message: "Tool arguments must be an object", code: "INVALID_TOOL_ARGS" }
3102
+ },
3103
+ maxPayloadBytes
3104
+ );
3105
+ }
3106
+ let resolvedArgs = sanitizedArgs;
3107
+ if (resolver && resolver.containsReferences(resolvedArgs)) {
3108
+ if (resolver.wouldExceedLimit(resolvedArgs)) {
3109
+ return serializeResponse(
3110
+ {
3111
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3112
+ ok: false,
3113
+ error: {
3114
+ name: "ToolBridgeError",
3115
+ message: "Arguments would exceed maximum resolved size when references are expanded. Reduce the amount of data passed to the tool.",
3116
+ code: "REFERENCE_RESOLUTION_LIMIT"
3117
+ }
3118
+ },
3119
+ maxPayloadBytes
3120
+ );
3121
+ }
3122
+ try {
3123
+ resolvedArgs = resolver.resolve(resolvedArgs);
3124
+ } catch (error) {
3125
+ if (error instanceof ResolutionLimitError) {
3126
+ return serializeResponse(
3127
+ {
3128
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3129
+ ok: false,
3130
+ error: {
3131
+ name: "ToolBridgeError",
3132
+ message: `Failed to resolve references in tool arguments: ${error.message}`,
3133
+ code: "REFERENCE_RESOLUTION_FAILED"
3134
+ }
3135
+ },
3136
+ maxPayloadBytes
3137
+ );
3138
+ }
3139
+ const safeError = toErrorPayload(
3140
+ error,
3141
+ "ToolBridgeError",
3142
+ "Reference resolution failed",
3143
+ "REFERENCE_RESOLUTION_FAILED"
3144
+ );
3145
+ return serializeResponse(
3146
+ {
3147
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3148
+ ok: false,
3149
+ error: safeError
3150
+ },
3151
+ maxPayloadBytes
3152
+ );
3153
+ }
3154
+ }
3155
+ let result;
3156
+ try {
3157
+ result = await toolHandler(tool, resolvedArgs);
3158
+ } catch (error) {
3159
+ const safeError = toErrorPayload(error, "ToolError", `Tool call failed: ${tool}`, "TOOL_CALL_FAILED");
3160
+ return serializeResponse(
3161
+ {
3162
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3163
+ ok: false,
3164
+ error: { ...safeError, toolError: true }
3165
+ },
3166
+ maxPayloadBytes
3167
+ );
3168
+ }
3169
+ let sanitizedResult;
3170
+ try {
3171
+ sanitizedResult = sanitizeValue(result, {
3172
+ maxDepth: config.maxSanitizeDepth,
3173
+ maxProperties: config.maxSanitizeProperties,
3174
+ allowDates: false,
3175
+ allowErrors: true
3176
+ });
3177
+ } catch (error) {
3178
+ const safeError = toErrorPayload(
3179
+ error,
3180
+ "ToolBridgeError",
3181
+ "Tool returned an unsupported value",
3182
+ "TOOL_RESULT_NOT_SAFE"
3183
+ );
3184
+ return serializeResponse(
3185
+ {
3186
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3187
+ ok: false,
3188
+ error: { ...safeError, toolError: true }
3189
+ },
3190
+ maxPayloadBytes
3191
+ );
3192
+ }
3193
+ if (sidecar && referenceConfig && typeof sanitizedResult === "string") {
3194
+ const size = utf8ByteLength(sanitizedResult);
3195
+ if (size >= referenceConfig.extractionThreshold) {
3196
+ try {
3197
+ const refId = sidecar.store(sanitizedResult, "tool-result", { origin: tool });
3198
+ sanitizedResult = refId;
3199
+ } catch {
3200
+ }
3201
+ }
3202
+ }
3203
+ const okResponse = sanitizedResult === void 0 ? { v: TOOL_BRIDGE_PROTOCOL_VERSION, ok: true } : { v: TOOL_BRIDGE_PROTOCOL_VERSION, ok: true, value: sanitizedResult };
3204
+ let okJson;
3205
+ try {
3206
+ okJson = safeJsonStringify(okResponse);
3207
+ } catch (error) {
3208
+ const safeError = toErrorPayload(
3209
+ error,
3210
+ "ToolBridgeError",
3211
+ "Tool result must be JSON-serializable",
3212
+ "TOOL_RESULT_NOT_JSON"
3213
+ );
3214
+ return serializeResponse(
3215
+ {
3216
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3217
+ ok: false,
3218
+ error: { ...safeError, toolError: true }
3219
+ },
3220
+ maxPayloadBytes
3221
+ );
3222
+ }
3223
+ if (utf8ByteLength(okJson) > maxPayloadBytes) {
3224
+ return serializeResponse(
3225
+ {
3226
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3227
+ ok: false,
3228
+ error: {
3229
+ name: "ToolBridgeError",
3230
+ message: `Tool response exceeds maximum size (${maxPayloadBytes} bytes)`,
3231
+ code: "TOOL_BRIDGE_RESPONSE_TOO_LARGE",
3232
+ toolError: true
3233
+ }
3234
+ },
3235
+ maxPayloadBytes
3236
+ );
3237
+ }
3238
+ return okJson;
3239
+ } catch (error) {
3240
+ const safeError = toErrorPayload(error, "ToolBridgeError", "Tool bridge failure", "TOOL_BRIDGE_FAILURE");
3241
+ return serializeResponse(
3242
+ {
3243
+ v: TOOL_BRIDGE_PROTOCOL_VERSION,
3244
+ ok: false,
3245
+ error: safeError
3246
+ },
3247
+ maxPayloadBytes
3248
+ );
3249
+ }
3250
+ };
3251
+ }
3252
+
785
3253
  // libs/core/src/adapters/interpreter-adapter.ts
786
- var SAFE_GLOBALS = Object.freeze({ Math, JSON });
787
3254
  var DEFAULT_MAX_STEPS = 5e6;
788
3255
  var DEFAULT_MAX_CALL_DEPTH = 256;
3256
+ var DEFAULT_MAX_ALLOCATION_BYTES = 64 * 1024 * 1024;
3257
+ var MAX_PARALLEL_ITEMS = 100;
3258
+ var MAX_SERIALIZED_RESULT_BYTES = 50 * 1024 * 1024;
3259
+ var DEFAULT_MAX_CONSOLE_CALLS = 100;
3260
+ var DEFAULT_MAX_CONSOLE_OUTPUT_BYTES = 64 * 1024;
3261
+ function sandboxError(message, name = "Error", code) {
3262
+ const error = new Error(message);
3263
+ error.name = name;
3264
+ if (code !== void 0) error.code = code;
3265
+ return error;
3266
+ }
3267
+ function frozenRecord2(members) {
3268
+ const record = /* @__PURE__ */ Object.create(null);
3269
+ for (const key of Object.keys(members)) record[key] = members[key];
3270
+ return Object.freeze(record);
3271
+ }
3272
+ function frozenDataCopy(name, value) {
3273
+ if (value === null || typeof value !== "object" && typeof value !== "function") return value;
3274
+ let json;
3275
+ try {
3276
+ json = typeof value === "function" ? void 0 : JSON.stringify(value);
3277
+ } catch {
3278
+ json = void 0;
3279
+ }
3280
+ if (json === void 0) {
3281
+ throw sandboxError(
3282
+ `Custom global "${name}" cannot be given to the interpreter: it supports JSON data only (no functions)`,
3283
+ "TypeError"
3284
+ );
3285
+ }
3286
+ const freeze = (item) => {
3287
+ if (item !== null && typeof item === "object") {
3288
+ for (const key of Object.keys(item)) freeze(item[key]);
3289
+ Object.freeze(item);
3290
+ }
3291
+ return item;
3292
+ };
3293
+ return freeze(JSON.parse(json));
3294
+ }
3295
+ function consoleText(value) {
3296
+ if (typeof value === "string") return value;
3297
+ if (typeof value === "function") return "[Function]";
3298
+ if (value === null || typeof value !== "object") return String(value);
3299
+ if (isScriptError(value)) {
3300
+ const error = value;
3301
+ return error.message ? `${error.name}: ${error.message}` : error.name;
3302
+ }
3303
+ try {
3304
+ return JSON.stringify(value) ?? "[object]";
3305
+ } catch {
3306
+ return "[object]";
3307
+ }
3308
+ }
789
3309
  var InterpreterAdapter = class {
790
3310
  constructor(options = {}) {
791
3311
  this.options = options;
792
3312
  }
793
3313
  async execute(code, context) {
794
3314
  const startTime = Date.now();
795
- let toolCallCount = 0;
796
3315
  const sanitizeStacks = context.config.sanitizeStackTraces === true;
797
- const maxToolCalls = context.config.maxToolCalls ?? Number.POSITIVE_INFINITY;
798
- const toolHandler = context.toolHandler ?? context.config.toolHandler;
799
- const __safe_callTool = async (name, args) => {
800
- if (++toolCallCount > maxToolCalls) {
801
- throw new Error(`Tool call limit exceeded (${maxToolCalls})`);
802
- }
803
- if (typeof toolHandler !== "function") {
804
- throw new Error("No toolHandler configured for the sandbox");
805
- }
806
- return toolHandler(name, args);
807
- };
808
- const globals = { ...SAFE_GLOBALS, __safe_callTool };
3316
+ const stats = context.stats ?? (context.stats = {
3317
+ duration: 0,
3318
+ toolCallCount: 0,
3319
+ iterationCount: 0,
3320
+ startTime
3321
+ });
809
3322
  let program;
810
3323
  try {
811
3324
  program = acorn.parse(code, { ecmaVersion: "latest", sourceType: "script" });
812
3325
  } catch (error) {
813
- return this.fail(error, startTime, toolCallCount, 0, sanitizeStacks, "SyntaxError");
3326
+ return this.fail(error, startTime, stats.toolCallCount, 0, sanitizeStacks, "SyntaxError");
3327
+ }
3328
+ const memoryLimit = context.config.memoryLimit;
3329
+ const adapterLimit = this.options.maxAllocationBytes ?? DEFAULT_MAX_ALLOCATION_BYTES;
3330
+ const allocationLimit = typeof memoryLimit === "number" && memoryLimit > 0 ? Math.min(memoryLimit, adapterLimit) : adapterLimit;
3331
+ const tracker = new MemoryTracker({ memoryLimit: Number.isFinite(allocationLimit) ? allocationLimit : 0 });
3332
+ const charge = (bytes) => tracker.track(bytes);
3333
+ let interpreter;
3334
+ try {
3335
+ 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);
3342
+ for (const name of Object.keys(runtime)) {
3343
+ if (!Object.prototype.hasOwnProperty.call(safe.globals, name)) safe.globals[name] = runtime[name];
3344
+ }
3345
+ interpreter = new Interpreter({
3346
+ globals: safe.globals,
3347
+ constructors: safe.constructors,
3348
+ instanceChecks: safe.instanceChecks,
3349
+ maxSteps: this.options.maxSteps ?? DEFAULT_MAX_STEPS,
3350
+ maxCallDepth: this.options.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH,
3351
+ maxPendingCalls: this.options.maxPendingCalls,
3352
+ signal: context.abortController.signal,
3353
+ charge
3354
+ });
3355
+ const running = interpreter;
3356
+ callbacks.call = (fn, args) => running.call(fn, args);
3357
+ } catch (error) {
3358
+ return this.fail(error, startTime, stats.toolCallCount, 0, sanitizeStacks);
814
3359
  }
815
3360
  const timeout = context.config.timeout;
816
3361
  const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
817
- const interpreter = new Interpreter({
818
- globals,
819
- maxSteps: this.options.maxSteps ?? DEFAULT_MAX_STEPS,
820
- maxCallDepth: this.options.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH,
821
- signal: context.abortController.signal
822
- });
823
3362
  let timeoutHandle;
824
3363
  const TIMED_OUT = /* @__PURE__ */ Symbol("timeout");
825
3364
  const deadline = timeout && timeout > 0 ? new Promise((resolve) => {
@@ -833,40 +3372,293 @@ var InterpreterAdapter = class {
833
3372
  return this.fail(
834
3373
  new Error(`Execution timed out after ${timeout}ms`),
835
3374
  startTime,
836
- toolCallCount,
3375
+ stats.toolCallCount,
837
3376
  interpreter.stepCount,
838
3377
  sanitizeStacks,
839
3378
  "TimeoutError",
840
3379
  "EXECUTION_TIMEOUT"
841
3380
  );
842
3381
  }
843
- return {
844
- success: true,
845
- value: outcome,
846
- stats: this.stats(startTime, toolCallCount, interpreter.stepCount)
847
- };
3382
+ return this.succeed(outcome, context, startTime, stats.toolCallCount, interpreter.stepCount);
848
3383
  } catch (error) {
849
3384
  const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
850
- return this.fail(error, startTime, toolCallCount, interpreter.stepCount, sanitizeStacks, void 0, code2);
3385
+ return this.fail(
3386
+ error,
3387
+ startTime,
3388
+ stats.toolCallCount,
3389
+ interpreter.stepCount,
3390
+ sanitizeStacks,
3391
+ void 0,
3392
+ code2
3393
+ );
851
3394
  } finally {
852
3395
  if (timer) clearTimeout(timer);
853
3396
  if (timeoutHandle) clearTimeout(timeoutHandle);
3397
+ interpreter.stop();
854
3398
  }
855
3399
  }
856
3400
  dispose() {
857
3401
  }
3402
+ /**
3403
+ * What transformed AgentScript refers to beyond the standard globals: the helpers the
3404
+ * transformer emits, and the console, tool namespaces and custom globals of this execution.
3405
+ */
3406
+ runtimeGlobals(context, charge, callbacks) {
3407
+ const { config } = context;
3408
+ const callTool = this.createCallTool(context);
3409
+ const resolver = context.sidecar && context.referenceConfig ? new ReferenceResolver(context.sidecar, context.referenceConfig) : void 0;
3410
+ const joinReferences = (parts) => {
3411
+ if (!resolver) {
3412
+ throw sandboxError(
3413
+ "Cannot concatenate reference IDs: reference system not configured. Pass references directly to callTool arguments instead."
3414
+ );
3415
+ }
3416
+ return resolver.createComposite(parts);
3417
+ };
3418
+ const concat = (left, right) => {
3419
+ if (typeof left === "number" && typeof right === "number") return left + right;
3420
+ if (typeof left === "string" && isReferenceId(left) || typeof right === "string" && isReferenceId(right)) {
3421
+ return joinReferences([String(left), String(right)]);
3422
+ }
3423
+ const result = left + right;
3424
+ if (typeof result === "string") {
3425
+ charge((result.length - (typeof left === "string" ? left.length : 0)) * 2);
3426
+ }
3427
+ return result;
3428
+ };
3429
+ const template = (quasis, ...values) => {
3430
+ if (!Array.isArray(quasis)) throw sandboxError("Template pieces must be an array", "TypeError");
3431
+ const parts = [];
3432
+ let hasReference = false;
3433
+ for (let i = 0; i < quasis.length; i++) {
3434
+ parts.push(String(quasis[i]));
3435
+ if (i < values.length) {
3436
+ const value = values[i];
3437
+ if (typeof value === "string" && isReferenceId(value)) hasReference = true;
3438
+ parts.push(String(value));
3439
+ }
3440
+ }
3441
+ if (hasReference) return joinReferences(parts.filter((part) => part !== ""));
3442
+ const result = parts.join("");
3443
+ charge(result.length * 2);
3444
+ return result;
3445
+ };
3446
+ const maxIterations = typeof config.maxIterations === "number" ? config.maxIterations : Number.POSITIVE_INFINITY;
3447
+ const signal = context.abortController.signal;
3448
+ function* forOf(iterable) {
3449
+ let iterations = 0;
3450
+ for (const item of iterable) {
3451
+ if (signal.aborted) throw sandboxError("Execution aborted");
3452
+ if (++iterations > maxIterations) {
3453
+ throw sandboxError(
3454
+ `Maximum iteration limit exceeded (${maxIterations}). This limit prevents infinite loops.`
3455
+ );
3456
+ }
3457
+ yield item;
3458
+ }
3459
+ }
3460
+ const parallel = async (first, second) => {
3461
+ let tasks;
3462
+ if (typeof second === "function") {
3463
+ if (!Array.isArray(first)) throw sandboxError("parallel requires an array of items", "TypeError");
3464
+ const items = first;
3465
+ tasks = items.map((item, index) => () => callbacks.call(second, [item, index, items]));
3466
+ } else {
3467
+ if (!Array.isArray(first) || !first.every((task) => typeof task === "function")) {
3468
+ throw sandboxError("parallel requires an array of functions", "TypeError");
3469
+ }
3470
+ tasks = first.map((task) => () => callbacks.call(task, []));
3471
+ }
3472
+ if (tasks.length > MAX_PARALLEL_ITEMS) {
3473
+ throw sandboxError(
3474
+ `Cannot execute more than ${MAX_PARALLEL_ITEMS} operations in parallel. Split into smaller batches.`
3475
+ );
3476
+ }
3477
+ const settled = await Promise.allSettled(tasks.map(async (task) => task()));
3478
+ const failures = settled.filter((result) => result.status === "rejected");
3479
+ 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}`);
3483
+ }
3484
+ return settled.map((result) => result.value);
3485
+ };
3486
+ const globals = {
3487
+ __safe_callTool: callTool,
3488
+ __safe_concat: concat,
3489
+ __safe_template: template,
3490
+ // Both go through the items of an array they are given and never convert it to text, so
3491
+ // the interpreter does not measure it first (as it does for a built-in that might).
3492
+ __safe_forOf: takesArraysAsData(forOf),
3493
+ __safe_parallel: takesArraysAsData(parallel),
3494
+ __maxIterations: maxIterations
3495
+ };
3496
+ if (typeof context.consoleHandler === "function") {
3497
+ const maxConsoleCalls = config.maxConsoleCalls ?? DEFAULT_MAX_CONSOLE_CALLS;
3498
+ const maxConsoleOutputBytes = config.maxConsoleOutputBytes ?? DEFAULT_MAX_CONSOLE_OUTPUT_BYTES;
3499
+ const sink = createConsoleSink(context.consoleHandler, { maxConsoleCalls, maxConsoleOutputBytes });
3500
+ let consoleCalls = 0;
3501
+ let consoleLength = 0;
3502
+ const write = (level) => (...args) => {
3503
+ consoleCalls++;
3504
+ if (consoleCalls > maxConsoleCalls) {
3505
+ throw sandboxError(
3506
+ `Console call limit exceeded (max: ${maxConsoleCalls}). This limit prevents I/O flood attacks.`
3507
+ );
3508
+ }
3509
+ const line = args.map(consoleText).join(" ");
3510
+ 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
+ }
3516
+ sink(level, line);
3517
+ };
3518
+ globals["__safe_console"] = frozenRecord2({
3519
+ log: write("log"),
3520
+ info: write("info"),
3521
+ warn: write("warn"),
3522
+ error: write("error")
3523
+ });
3524
+ }
3525
+ for (const namespace of context.toolNamespaces ?? []) {
3526
+ const methods = {};
3527
+ for (const method of namespace.methods) {
3528
+ if (isBlockedKey(method.name)) continue;
3529
+ methods[method.name] = (args, options) => callTool(method.toolName, args === void 0 ? {} : args, options);
3530
+ }
3531
+ globals[namespace.name] = frozenRecord2(methods);
3532
+ }
3533
+ const custom = config.globals;
3534
+ if (custom && typeof custom === "object") {
3535
+ for (const name of Object.keys(custom)) {
3536
+ if (name.startsWith("__") || Object.prototype.hasOwnProperty.call(globals, name)) continue;
3537
+ globals[name] = frozenDataCopy(name, custom[name]);
3538
+ }
3539
+ }
3540
+ return globals;
3541
+ }
3542
+ /**
3543
+ * `callTool(name, args, options)` for the script, through the host tool bridge: the request
3544
+ * and the response cross as JSON, so the handler never receives a value of the script and the
3545
+ * script never receives an object of the handler.
3546
+ */
3547
+ createCallTool(context) {
3548
+ const configured = context.config.toolHandler;
3549
+ const bridgeContext = context.toolHandler === void 0 && typeof configured === "function" ? Object.create(context, { toolHandler: { value: configured } }) : context;
3550
+ const bridge = createHostToolBridge(bridgeContext, { updateStats: true });
3551
+ return async (toolName, args, options) => {
3552
+ let throwOnError = true;
3553
+ if (options !== void 0 && options !== null) {
3554
+ if (typeof options !== "object") throw sandboxError("callTool options must be an object", "TypeError");
3555
+ throwOnError = options.throwOnError !== false;
3556
+ }
3557
+ if (typeof toolName !== "string" || !toolName) {
3558
+ throw sandboxError("Tool name must be a non-empty string", "TypeError");
3559
+ }
3560
+ if (typeof args !== "object" || args === null || Array.isArray(args)) {
3561
+ throw sandboxError("Tool arguments must be an object", "TypeError");
3562
+ }
3563
+ let requestJson;
3564
+ try {
3565
+ requestJson = encodeToolBridgeRequest(toolName, args);
3566
+ } catch {
3567
+ throw sandboxError("Tool arguments must be JSON-serializable", "TypeError");
3568
+ }
3569
+ let response;
3570
+ try {
3571
+ response = JSON.parse(await bridge(requestJson));
3572
+ } catch {
3573
+ throw sandboxError("Tool bridge returned invalid JSON");
3574
+ }
3575
+ if (!response || typeof response !== "object" || Array.isArray(response)) {
3576
+ throw sandboxError("Tool bridge returned invalid response");
3577
+ }
3578
+ const reply = response;
3579
+ if (reply.ok === true) {
3580
+ return throwOnError ? reply.value : { success: true, data: reply.value };
3581
+ }
3582
+ if (reply.ok === false && reply.error && typeof reply.error === "object") {
3583
+ const message = typeof reply.error["message"] === "string" ? reply.error["message"] : "Tool call failed";
3584
+ const name = typeof reply.error["name"] === "string" ? reply.error["name"] : "Error";
3585
+ const code = typeof reply.error["code"] === "string" ? reply.error["code"] : void 0;
3586
+ if (!throwOnError && reply.error["toolError"] === true) {
3587
+ return { success: false, error: { name, message, toolName, ...code !== void 0 ? { code } : {} } };
3588
+ }
3589
+ throw sandboxError(message, name, code);
3590
+ }
3591
+ throw sandboxError("Tool bridge returned invalid response");
3592
+ };
3593
+ }
3594
+ /**
3595
+ * The value a script returned, as the caller gets it: plain host data, like from every other
3596
+ * adapter. A function, or a result that would serialize to more than the memory limit, fails
3597
+ * the execution.
3598
+ */
3599
+ succeed(value, context, startTime, toolCallCount, stepCount) {
3600
+ const { config } = context;
3601
+ const stats = this.stats(startTime, toolCallCount, stepCount);
3602
+ if (typeof config.memoryLimit === "number" && config.memoryLimit > 0 && value !== void 0) {
3603
+ const sizeCheck = checkSerializedSize(value, Math.min(config.memoryLimit, MAX_SERIALIZED_RESULT_BYTES));
3604
+ if (!sizeCheck.ok) {
3605
+ return {
3606
+ success: false,
3607
+ error: {
3608
+ name: "MemoryLimitError",
3609
+ message: `Return value serialization would exceed memory limit: ${sizeCheck.error}`,
3610
+ code: "SERIALIZATION_LIMIT_EXCEEDED"
3611
+ },
3612
+ stats
3613
+ };
3614
+ }
3615
+ }
3616
+ const maxDepth = config.maxSanitizeDepth;
3617
+ const maxProperties = config.maxSanitizeProperties;
3618
+ return {
3619
+ success: true,
3620
+ value: sanitizeValue(value, { maxDepth, maxProperties, allowDates: true, allowErrors: true }),
3621
+ stats
3622
+ };
3623
+ }
858
3624
  stats(startTime, toolCallCount, iterationCount) {
859
3625
  const endTime = Date.now();
860
3626
  return { duration: endTime - startTime, toolCallCount, iterationCount, startTime, endTime };
861
3627
  }
3628
+ /**
3629
+ * What ended an execution, as a name and a message. A script can throw any value: a string is
3630
+ * the message, an object contributes its `name`, `message` and `code` when they are strings.
3631
+ */
3632
+ describe(thrown) {
3633
+ if (thrown instanceof Error) {
3634
+ const code = thrown.code;
3635
+ return {
3636
+ name: thrown.name,
3637
+ message: thrown.message,
3638
+ stack: thrown.stack,
3639
+ ...typeof code === "string" ? { code } : {}
3640
+ };
3641
+ }
3642
+ if (typeof thrown === "string") return { name: "Error", message: thrown };
3643
+ if (thrown !== null && typeof thrown === "object") {
3644
+ const value = thrown;
3645
+ return {
3646
+ name: typeof value.name === "string" ? value.name : "Error",
3647
+ message: typeof value.message === "string" ? value.message : "The script threw a value that is not an error",
3648
+ ...typeof value.code === "string" ? { code: value.code } : {}
3649
+ };
3650
+ }
3651
+ return { name: "Error", message: `The script threw ${String(thrown)}` };
3652
+ }
862
3653
  fail(error, startTime, toolCallCount, iterationCount, sanitizeStacks, name, code) {
863
- const err = error instanceof Error ? error : new Error(String(error));
864
- const stack = sanitizeStackTrace(err.stack, sanitizeStacks);
3654
+ const described = this.describe(error);
3655
+ const stack = sanitizeStackTrace(described.stack, sanitizeStacks);
3656
+ const errorCode = code ?? described.code;
865
3657
  const execError = {
866
- message: err.message,
867
- name: name ?? err.name,
3658
+ message: described.message,
3659
+ name: name ?? described.name,
868
3660
  ...stack ? { stack } : {},
869
- ...code ? { code } : {}
3661
+ ...errorCode ? { code: errorCode } : {}
870
3662
  };
871
3663
  return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };
872
3664
  }