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