@enclave-vm/core 2.18.0 → 2.19.0

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