@enclave-vm/core 2.12.0 → 2.14.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/index.mjs CHANGED
@@ -10486,6 +10486,685 @@ async function runAgentScript(code, options = {}) {
10486
10486
  init_safe_runtime();
10487
10487
  init_secure_proxy();
10488
10488
  init_memory_tracker();
10489
+
10490
+ // libs/core/src/adapters/interpreter-adapter.ts
10491
+ import * as acorn3 from "acorn";
10492
+
10493
+ // libs/core/src/interpreter/interpreter.ts
10494
+ var BLOCKED_KEYS = /* @__PURE__ */ new Set([
10495
+ "__proto__",
10496
+ "prototype",
10497
+ "constructor",
10498
+ "__defineGetter__",
10499
+ "__defineSetter__",
10500
+ "__lookupGetter__",
10501
+ "__lookupSetter__"
10502
+ ]);
10503
+ var MAX_STRING_OP_LENGTH = 1e6;
10504
+ var HIGHER_ORDER_ARRAY_METHODS = /* @__PURE__ */ new Set([
10505
+ "map",
10506
+ "flatMap",
10507
+ "filter",
10508
+ "forEach",
10509
+ "some",
10510
+ "every",
10511
+ "find",
10512
+ "findIndex",
10513
+ "reduce",
10514
+ "sort"
10515
+ ]);
10516
+ var StepLimitError = class extends Error {
10517
+ constructor(limit) {
10518
+ super(`Execution step limit exceeded (${limit})`);
10519
+ this.name = "StepLimitError";
10520
+ }
10521
+ };
10522
+ var InterpreterError = class extends Error {
10523
+ constructor(message) {
10524
+ super(message);
10525
+ this.name = "InterpreterError";
10526
+ }
10527
+ };
10528
+ var ReturnSignal = class {
10529
+ constructor(value) {
10530
+ this.value = value;
10531
+ }
10532
+ };
10533
+ var BreakSignal = class {
10534
+ };
10535
+ var ContinueSignal = class {
10536
+ };
10537
+ var Scope = class _Scope {
10538
+ constructor(parent) {
10539
+ this.parent = parent;
10540
+ }
10541
+ vars = /* @__PURE__ */ new Map();
10542
+ child() {
10543
+ return new _Scope(this);
10544
+ }
10545
+ declare(name, value, mutable) {
10546
+ this.vars.set(name, { value, mutable });
10547
+ }
10548
+ has(name) {
10549
+ return this.vars.has(name) || (this.parent?.has(name) ?? false);
10550
+ }
10551
+ get(name) {
10552
+ const slot = this.vars.get(name);
10553
+ if (slot) return slot.value;
10554
+ if (this.parent) return this.parent.get(name);
10555
+ throw new InterpreterError(`'${name}' is not defined`);
10556
+ }
10557
+ set(name, value) {
10558
+ const slot = this.vars.get(name);
10559
+ if (slot) {
10560
+ if (!slot.mutable) throw new InterpreterError(`Assignment to constant '${name}'`);
10561
+ slot.value = value;
10562
+ return;
10563
+ }
10564
+ if (this.parent) {
10565
+ this.parent.set(name, value);
10566
+ return;
10567
+ }
10568
+ throw new InterpreterError(`'${name}' is not defined`);
10569
+ }
10570
+ };
10571
+ var Interpreter = class {
10572
+ constructor(options) {
10573
+ this.options = options;
10574
+ this.globals = options.globals;
10575
+ }
10576
+ steps = 0;
10577
+ callDepth = 0;
10578
+ globals;
10579
+ /** Number of AST nodes evaluated so far (for execution stats). */
10580
+ get stepCount() {
10581
+ return this.steps;
10582
+ }
10583
+ async run(program) {
10584
+ const root = new Scope();
10585
+ for (const stmt of program.body) {
10586
+ if (stmt.type === "FunctionDeclaration" && stmt.id) {
10587
+ root.declare(stmt.id.name, this.makeFunction(stmt, root), false);
10588
+ }
10589
+ }
10590
+ let last;
10591
+ for (const stmt of program.body) {
10592
+ if (stmt.type === "FunctionDeclaration") continue;
10593
+ last = await this.execStatement(stmt, root);
10594
+ }
10595
+ if (root.has("__ag_main")) {
10596
+ const main = root.get("__ag_main");
10597
+ if (typeof main === "function") return main();
10598
+ }
10599
+ return last;
10600
+ }
10601
+ tick() {
10602
+ if (this.options.signal?.aborted) throw new InterpreterError("Execution aborted");
10603
+ if (++this.steps > this.options.maxSteps) throw new StepLimitError(this.options.maxSteps);
10604
+ }
10605
+ // ── Statements ─────────────────────────────────────────────────────────────
10606
+ async execStatement(node, scope) {
10607
+ this.tick();
10608
+ switch (node.type) {
10609
+ case "VariableDeclaration": {
10610
+ for (const d of node.declarations) {
10611
+ const value = d.init ? await this.evalExpr(d.init, scope) : void 0;
10612
+ this.bindPattern(d.id, value, scope, node.kind !== "const");
10613
+ }
10614
+ return void 0;
10615
+ }
10616
+ case "FunctionDeclaration":
10617
+ if (node.id) scope.declare(node.id.name, this.makeFunction(node, scope), false);
10618
+ return void 0;
10619
+ case "ExpressionStatement":
10620
+ return this.evalExpr(node.expression, scope);
10621
+ case "BlockStatement":
10622
+ return this.execBlock(node.body, scope.child());
10623
+ case "IfStatement":
10624
+ if (truthy(await this.evalExpr(node.test, scope))) return this.execStatement(node.consequent, scope);
10625
+ if (node.alternate) return this.execStatement(node.alternate, scope);
10626
+ return void 0;
10627
+ case "ForOfStatement":
10628
+ return this.execForOf(node, scope);
10629
+ case "ForStatement":
10630
+ return this.execFor(node, scope);
10631
+ case "WhileStatement":
10632
+ return this.execWhile(node, scope);
10633
+ case "ReturnStatement":
10634
+ throw new ReturnSignal(node.argument ? await this.evalExpr(node.argument, scope) : void 0);
10635
+ case "BreakStatement":
10636
+ throw new BreakSignal();
10637
+ case "ContinueStatement":
10638
+ throw new ContinueSignal();
10639
+ case "EmptyStatement":
10640
+ return void 0;
10641
+ default:
10642
+ throw new InterpreterError(`Unsupported statement: ${node.type}`);
10643
+ }
10644
+ }
10645
+ async execBlock(body, scope) {
10646
+ for (const stmt of body) {
10647
+ if (stmt.type === "FunctionDeclaration" && stmt.id) {
10648
+ scope.declare(stmt.id.name, this.makeFunction(stmt, scope), false);
10649
+ }
10650
+ }
10651
+ for (const stmt of body) {
10652
+ if (stmt.type === "FunctionDeclaration") continue;
10653
+ await this.execStatement(stmt, scope);
10654
+ }
10655
+ return void 0;
10656
+ }
10657
+ async execForOf(node, scope) {
10658
+ const iterable = await this.evalExpr(node.right, scope);
10659
+ if (!isIterable(iterable)) throw new InterpreterError("for-of target is not iterable");
10660
+ for (const item of iterable) {
10661
+ this.tick();
10662
+ const inner = scope.child();
10663
+ const decl = node.left;
10664
+ if (decl.type === "VariableDeclaration") {
10665
+ this.bindPattern(decl.declarations[0].id, item, inner, decl.kind !== "const");
10666
+ } else {
10667
+ this.assignTo(decl, item, inner);
10668
+ }
10669
+ try {
10670
+ await this.execStatement(node.body, inner);
10671
+ } catch (e) {
10672
+ if (e instanceof BreakSignal) break;
10673
+ if (e instanceof ContinueSignal) continue;
10674
+ throw e;
10675
+ }
10676
+ }
10677
+ }
10678
+ async execFor(node, scope) {
10679
+ const inner = scope.child();
10680
+ if (node.init) {
10681
+ if (node.init.type === "VariableDeclaration") await this.execStatement(node.init, inner);
10682
+ else await this.evalExpr(node.init, inner);
10683
+ }
10684
+ while (node.test ? truthy(await this.evalExpr(node.test, inner)) : true) {
10685
+ this.tick();
10686
+ try {
10687
+ await this.execStatement(node.body, inner.child());
10688
+ } catch (e) {
10689
+ if (e instanceof BreakSignal) break;
10690
+ if (!(e instanceof ContinueSignal)) throw e;
10691
+ }
10692
+ if (node.update) await this.evalExpr(node.update, inner);
10693
+ }
10694
+ }
10695
+ async execWhile(node, scope) {
10696
+ while (truthy(await this.evalExpr(node.test, scope))) {
10697
+ this.tick();
10698
+ try {
10699
+ await this.execStatement(node.body, scope.child());
10700
+ } catch (e) {
10701
+ if (e instanceof BreakSignal) break;
10702
+ if (!(e instanceof ContinueSignal)) throw e;
10703
+ }
10704
+ }
10705
+ }
10706
+ // ── Expressions ──────────────────────────────────────────────────────────--
10707
+ async evalExpr(node, scope) {
10708
+ this.tick();
10709
+ switch (node.type) {
10710
+ case "Literal":
10711
+ return node.value;
10712
+ case "Identifier":
10713
+ return scope.has(node.name) ? scope.get(node.name) : this.readGlobal(node.name);
10714
+ case "TemplateLiteral":
10715
+ return this.evalTemplate(node, scope);
10716
+ case "ArrayExpression": {
10717
+ const arr = [];
10718
+ for (const el of node.elements) {
10719
+ if (el == null) {
10720
+ arr.push(void 0);
10721
+ } else if (el.type === "SpreadElement") {
10722
+ const spread = await this.evalExpr(el.argument, scope);
10723
+ if (!isIterable(spread)) throw new InterpreterError("Spread target is not iterable");
10724
+ for (const v of spread) arr.push(v);
10725
+ } else {
10726
+ arr.push(await this.evalExpr(el, scope));
10727
+ }
10728
+ }
10729
+ return arr;
10730
+ }
10731
+ case "ObjectExpression": {
10732
+ const obj = {};
10733
+ for (const prop of node.properties) {
10734
+ if (prop.type === "SpreadElement") {
10735
+ const spread = await this.evalExpr(prop.argument, scope);
10736
+ if (spread && typeof spread === "object") {
10737
+ for (const [k, v] of Object.entries(spread)) {
10738
+ if (!BLOCKED_KEYS.has(k)) obj[k] = v;
10739
+ }
10740
+ }
10741
+ continue;
10742
+ }
10743
+ const key = await this.propKey(prop, scope);
10744
+ if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property key: ${key}`);
10745
+ obj[key] = await this.evalExpr(prop.value, scope);
10746
+ }
10747
+ return obj;
10748
+ }
10749
+ case "UnaryExpression": {
10750
+ const v = await this.evalExpr(node.argument, scope);
10751
+ switch (node.operator) {
10752
+ case "!":
10753
+ return !truthy(v);
10754
+ case "-":
10755
+ return -v;
10756
+ case "+":
10757
+ return +v;
10758
+ case "typeof":
10759
+ return typeof v;
10760
+ case "~":
10761
+ return ~v;
10762
+ default:
10763
+ throw new InterpreterError(`Unsupported unary operator: ${node.operator}`);
10764
+ }
10765
+ }
10766
+ case "BinaryExpression":
10767
+ return this.evalBinary(node, scope);
10768
+ case "LogicalExpression": {
10769
+ const left = await this.evalExpr(node.left, scope);
10770
+ if (node.operator === "&&") return truthy(left) ? this.evalExpr(node.right, scope) : left;
10771
+ if (node.operator === "||") return truthy(left) ? left : this.evalExpr(node.right, scope);
10772
+ return left ?? await this.evalExpr(node.right, scope);
10773
+ }
10774
+ case "ConditionalExpression":
10775
+ return truthy(await this.evalExpr(node.test, scope)) ? this.evalExpr(node.consequent, scope) : this.evalExpr(node.alternate, scope);
10776
+ case "MemberExpression":
10777
+ return (await this.evalMember(node, scope)).value;
10778
+ case "CallExpression":
10779
+ return this.evalCall(node, scope);
10780
+ case "AwaitExpression":
10781
+ return await this.evalExpr(node.argument, scope);
10782
+ case "AssignmentExpression":
10783
+ return this.evalAssignment(node, scope);
10784
+ case "ArrowFunctionExpression":
10785
+ case "FunctionExpression":
10786
+ return this.makeFunction(node, scope);
10787
+ default:
10788
+ throw new InterpreterError(`Unsupported expression: ${node.type}`);
10789
+ }
10790
+ }
10791
+ async evalTemplate(node, scope) {
10792
+ let out = "";
10793
+ for (let i = 0; i < node.quasis.length; i++) {
10794
+ out += node.quasis[i].value.cooked ?? "";
10795
+ if (i < node.expressions.length) out += String(await this.evalExpr(node.expressions[i], scope));
10796
+ }
10797
+ return out;
10798
+ }
10799
+ async evalBinary(node, scope) {
10800
+ const l = await this.evalExpr(node.left, scope);
10801
+ const r = await this.evalExpr(node.right, scope);
10802
+ switch (node.operator) {
10803
+ case "+":
10804
+ return l + r;
10805
+ case "-":
10806
+ return l - r;
10807
+ case "*":
10808
+ return l * r;
10809
+ case "/":
10810
+ return l / r;
10811
+ case "%":
10812
+ return l % r;
10813
+ case "**":
10814
+ return l ** r;
10815
+ case "==":
10816
+ return l == r;
10817
+ case "!=":
10818
+ return l != r;
10819
+ case "===":
10820
+ return l === r;
10821
+ case "!==":
10822
+ return l !== r;
10823
+ case "<":
10824
+ return l < r;
10825
+ case "<=":
10826
+ return l <= r;
10827
+ case ">":
10828
+ return l > r;
10829
+ case ">=":
10830
+ return l >= r;
10831
+ case "&":
10832
+ return l & r;
10833
+ case "|":
10834
+ return l | r;
10835
+ case "^":
10836
+ return l ^ r;
10837
+ case "<<":
10838
+ return l << r;
10839
+ case ">>":
10840
+ return l >> r;
10841
+ case ">>>":
10842
+ return l >>> r;
10843
+ default:
10844
+ throw new InterpreterError(`Unsupported binary operator: ${node.operator}`);
10845
+ }
10846
+ }
10847
+ /** Resolve a member access to `{ object, key, value }`, blocking escape keys. */
10848
+ async evalMember(node, scope) {
10849
+ const object = await this.evalExpr(node.object, scope);
10850
+ const key = node.computed ? String(await this.evalExpr(node.property, scope)) : node.property.name;
10851
+ if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden property access: ${key}`);
10852
+ if (object == null) throw new InterpreterError(`Cannot read '${key}' of ${String(object)}`);
10853
+ const value = object[key];
10854
+ return { object, key, value };
10855
+ }
10856
+ async evalCall(node, scope) {
10857
+ const args = [];
10858
+ for (const a of node.arguments) {
10859
+ if (a.type === "SpreadElement") {
10860
+ const spread = await this.evalExpr(a.argument, scope);
10861
+ if (!isIterable(spread)) throw new InterpreterError("Spread target is not iterable");
10862
+ for (const v of spread) args.push(v);
10863
+ } else {
10864
+ args.push(await this.evalExpr(a, scope));
10865
+ }
10866
+ }
10867
+ let fn;
10868
+ let thisArg;
10869
+ if (node.callee.type === "MemberExpression") {
10870
+ const m = await this.evalMember(node.callee, scope);
10871
+ if (Array.isArray(m.object) && HIGHER_ORDER_ARRAY_METHODS.has(m.key) && typeof args[0] === "function") {
10872
+ return this.callArrayMethod(m.object, m.key, args);
10873
+ }
10874
+ if (typeof m.object === "string" && (m.key === "repeat" || m.key === "padStart" || m.key === "padEnd")) {
10875
+ const n = Number(args[0]);
10876
+ const produced = m.key === "repeat" ? m.object.length * (n > 0 ? n : 0) : Math.max(m.object.length, n > 0 ? n : 0);
10877
+ if (produced > MAX_STRING_OP_LENGTH) {
10878
+ throw new InterpreterError(
10879
+ `String '${m.key}' would produce ${produced} chars, exceeding the ${MAX_STRING_OP_LENGTH} limit`
10880
+ );
10881
+ }
10882
+ }
10883
+ fn = m.value;
10884
+ thisArg = m.object;
10885
+ } else {
10886
+ fn = await this.evalExpr(node.callee, scope);
10887
+ thisArg = void 0;
10888
+ }
10889
+ if (typeof fn !== "function") throw new InterpreterError("Attempted to call a non-function");
10890
+ if (++this.callDepth > this.options.maxCallDepth) {
10891
+ this.callDepth--;
10892
+ throw new InterpreterError(`Max call depth exceeded (${this.options.maxCallDepth})`);
10893
+ }
10894
+ try {
10895
+ return await fn.apply(thisArg, args);
10896
+ } finally {
10897
+ this.callDepth--;
10898
+ }
10899
+ }
10900
+ /**
10901
+ * Async implementations of the higher-order array methods, so interpreter
10902
+ * callbacks (which are async — they may `await` tool calls) are awaited. Each
10903
+ * iteration ticks the step budget.
10904
+ */
10905
+ async callArrayMethod(arr, method, args) {
10906
+ const cb = args[0];
10907
+ const each = (i) => {
10908
+ this.tick();
10909
+ return cb(arr[i], i, arr);
10910
+ };
10911
+ switch (method) {
10912
+ case "map": {
10913
+ const out = [];
10914
+ for (let i = 0; i < arr.length; i++) out.push(await each(i));
10915
+ return out;
10916
+ }
10917
+ case "flatMap": {
10918
+ const out = [];
10919
+ for (let i = 0; i < arr.length; i++) {
10920
+ const v = await each(i);
10921
+ if (Array.isArray(v)) out.push(...v);
10922
+ else out.push(v);
10923
+ }
10924
+ return out;
10925
+ }
10926
+ case "filter": {
10927
+ const out = [];
10928
+ for (let i = 0; i < arr.length; i++) if (truthy(await each(i))) out.push(arr[i]);
10929
+ return out;
10930
+ }
10931
+ case "forEach":
10932
+ for (let i = 0; i < arr.length; i++) await each(i);
10933
+ return void 0;
10934
+ case "some":
10935
+ for (let i = 0; i < arr.length; i++) if (truthy(await each(i))) return true;
10936
+ return false;
10937
+ case "every":
10938
+ for (let i = 0; i < arr.length; i++) if (!truthy(await each(i))) return false;
10939
+ return true;
10940
+ case "find":
10941
+ for (let i = 0; i < arr.length; i++) if (truthy(await each(i))) return arr[i];
10942
+ return void 0;
10943
+ case "findIndex":
10944
+ for (let i = 0; i < arr.length; i++) if (truthy(await each(i))) return i;
10945
+ return -1;
10946
+ case "reduce": {
10947
+ const reducer = cb;
10948
+ let acc;
10949
+ let start = 0;
10950
+ if (args.length > 1) acc = args[1];
10951
+ else {
10952
+ if (arr.length === 0) throw new InterpreterError("Reduce of empty array with no initial value");
10953
+ acc = arr[0];
10954
+ start = 1;
10955
+ }
10956
+ for (let i = start; i < arr.length; i++) {
10957
+ this.tick();
10958
+ acc = await reducer(acc, arr[i], i, arr);
10959
+ }
10960
+ return acc;
10961
+ }
10962
+ case "sort": {
10963
+ const cmp = cb;
10964
+ for (let i = 1; i < arr.length; i++) {
10965
+ let j = i;
10966
+ while (j > 0) {
10967
+ this.tick();
10968
+ if (await cmp(arr[j - 1], arr[j]) <= 0) break;
10969
+ [arr[j - 1], arr[j]] = [arr[j], arr[j - 1]];
10970
+ j--;
10971
+ }
10972
+ }
10973
+ return arr;
10974
+ }
10975
+ default:
10976
+ throw new InterpreterError(`Unsupported array method: ${method}`);
10977
+ }
10978
+ }
10979
+ async evalAssignment(node, scope) {
10980
+ const value = await this.evalExpr(node.right, scope);
10981
+ if (node.operator === "=") {
10982
+ this.assignTo(node.left, value, scope);
10983
+ return value;
10984
+ }
10985
+ const current = await this.evalExpr(node.left, scope);
10986
+ const op = node.operator.slice(0, -1);
10987
+ const next = applyBinary(op, current, value);
10988
+ this.assignTo(node.left, next, scope);
10989
+ return next;
10990
+ }
10991
+ /** Assign to an Identifier or MemberExpression target (blocking escape keys). */
10992
+ assignTo(target, value, scope) {
10993
+ if (target.type === "Identifier") {
10994
+ scope.set(target.name, value);
10995
+ return;
10996
+ }
10997
+ if (target.type === "MemberExpression") {
10998
+ throw new InterpreterError("Member assignment is not supported in AgentScript");
10999
+ }
11000
+ throw new InterpreterError(`Unsupported assignment target: ${target.type}`);
11001
+ }
11002
+ bindPattern(pattern, value, scope, mutable) {
11003
+ if (pattern.type === "Identifier") {
11004
+ scope.declare(pattern.name, value, mutable);
11005
+ return;
11006
+ }
11007
+ if (pattern.type === "ArrayPattern") {
11008
+ const arr = isIterable(value) ? [...value] : [];
11009
+ pattern.elements.forEach((el, i) => {
11010
+ if (el) this.bindPattern(el, arr[i], scope, mutable);
11011
+ });
11012
+ return;
11013
+ }
11014
+ if (pattern.type === "ObjectPattern") {
11015
+ const obj = value ?? {};
11016
+ for (const prop of pattern.properties) {
11017
+ if (prop.type === "RestElement") continue;
11018
+ const key = prop.key.name;
11019
+ if (BLOCKED_KEYS.has(key)) throw new InterpreterError(`Forbidden destructured key: ${key}`);
11020
+ this.bindPattern(prop.value, obj[key], scope, mutable);
11021
+ }
11022
+ return;
11023
+ }
11024
+ throw new InterpreterError(`Unsupported binding pattern: ${pattern.type}`);
11025
+ }
11026
+ /** Build an interpreter-backed function (declaration / arrow / expression). */
11027
+ makeFunction(node, closure) {
11028
+ const self = this;
11029
+ return async function interpreted(...args) {
11030
+ const fnScope = closure.child();
11031
+ node.params.forEach((p, i) => self.bindPattern(p, args[i], fnScope, true));
11032
+ try {
11033
+ if (node.body.type === "BlockStatement") {
11034
+ await self.execBlock(node.body.body, fnScope);
11035
+ return void 0;
11036
+ }
11037
+ return await self.evalExpr(node.body, fnScope);
11038
+ } catch (e) {
11039
+ if (e instanceof ReturnSignal) return e.value;
11040
+ throw e;
11041
+ }
11042
+ };
11043
+ }
11044
+ async propKey(prop, scope) {
11045
+ if (prop.computed) return String(await this.evalExpr(prop.key, scope));
11046
+ if (prop.key.type === "Identifier") return prop.key.name;
11047
+ if (prop.key.type === "Literal") return String(prop.key.value);
11048
+ throw new InterpreterError("Unsupported property key");
11049
+ }
11050
+ readGlobal(name) {
11051
+ if (Object.prototype.hasOwnProperty.call(this.globals, name)) return this.globals[name];
11052
+ throw new InterpreterError(`'${name}' is not defined`);
11053
+ }
11054
+ };
11055
+ function truthy(v) {
11056
+ return Boolean(v);
11057
+ }
11058
+ function isIterable(v) {
11059
+ return v != null && typeof v[Symbol.iterator] === "function";
11060
+ }
11061
+ function applyBinary(op, l, r) {
11062
+ switch (op) {
11063
+ case "+":
11064
+ return l + r;
11065
+ case "-":
11066
+ return l - r;
11067
+ case "*":
11068
+ return l * r;
11069
+ case "/":
11070
+ return l / r;
11071
+ case "%":
11072
+ return l % r;
11073
+ case "**":
11074
+ return l ** r;
11075
+ default:
11076
+ throw new InterpreterError(`Unsupported compound operator: ${op}=`);
11077
+ }
11078
+ }
11079
+
11080
+ // libs/core/src/adapters/interpreter-adapter.ts
11081
+ var SAFE_GLOBALS = Object.freeze({ Math, JSON });
11082
+ var DEFAULT_MAX_STEPS = 5e6;
11083
+ var DEFAULT_MAX_CALL_DEPTH = 256;
11084
+ var InterpreterAdapter = class {
11085
+ constructor(options = {}) {
11086
+ this.options = options;
11087
+ }
11088
+ async execute(code, context) {
11089
+ const startTime = Date.now();
11090
+ let toolCallCount = 0;
11091
+ const maxToolCalls = context.config.maxToolCalls ?? Number.POSITIVE_INFINITY;
11092
+ const toolHandler = context.toolHandler ?? context.config.toolHandler;
11093
+ const __safe_callTool = async (name, args) => {
11094
+ if (++toolCallCount > maxToolCalls) {
11095
+ throw new Error(`Tool call limit exceeded (${maxToolCalls})`);
11096
+ }
11097
+ if (typeof toolHandler !== "function") {
11098
+ throw new Error("No toolHandler configured for the sandbox");
11099
+ }
11100
+ return toolHandler(name, args);
11101
+ };
11102
+ const globals = { ...SAFE_GLOBALS, __safe_callTool };
11103
+ let program;
11104
+ try {
11105
+ program = acorn3.parse(code, { ecmaVersion: "latest", sourceType: "script" });
11106
+ } catch (error) {
11107
+ return this.fail(error, startTime, toolCallCount, 0, "SyntaxError");
11108
+ }
11109
+ const timeout = context.config.timeout;
11110
+ const timer = timeout && timeout > 0 ? setTimeout(() => context.abortController.abort(), timeout) : void 0;
11111
+ const interpreter = new Interpreter({
11112
+ globals,
11113
+ maxSteps: this.options.maxSteps ?? DEFAULT_MAX_STEPS,
11114
+ maxCallDepth: this.options.maxCallDepth ?? DEFAULT_MAX_CALL_DEPTH,
11115
+ signal: context.abortController.signal
11116
+ });
11117
+ let timeoutHandle;
11118
+ const TIMED_OUT = /* @__PURE__ */ Symbol("timeout");
11119
+ const deadline = timeout && timeout > 0 ? new Promise((resolve) => {
11120
+ timeoutHandle = setTimeout(() => resolve(TIMED_OUT), timeout);
11121
+ }) : void 0;
11122
+ try {
11123
+ const run = interpreter.run(program);
11124
+ run.catch(() => void 0);
11125
+ const outcome = deadline ? await Promise.race([run, deadline]) : await run;
11126
+ if (outcome === TIMED_OUT) {
11127
+ return this.fail(
11128
+ new Error(`Execution timed out after ${timeout}ms`),
11129
+ startTime,
11130
+ toolCallCount,
11131
+ interpreter.stepCount,
11132
+ "TimeoutError",
11133
+ "EXECUTION_TIMEOUT"
11134
+ );
11135
+ }
11136
+ return {
11137
+ success: true,
11138
+ value: outcome,
11139
+ stats: this.stats(startTime, toolCallCount, interpreter.stepCount)
11140
+ };
11141
+ } catch (error) {
11142
+ const code2 = error instanceof StepLimitError ? "STEP_LIMIT_EXCEEDED" : void 0;
11143
+ return this.fail(error, startTime, toolCallCount, interpreter.stepCount, void 0, code2);
11144
+ } finally {
11145
+ if (timer) clearTimeout(timer);
11146
+ if (timeoutHandle) clearTimeout(timeoutHandle);
11147
+ }
11148
+ }
11149
+ dispose() {
11150
+ }
11151
+ stats(startTime, toolCallCount, iterationCount) {
11152
+ const endTime = Date.now();
11153
+ return { duration: endTime - startTime, toolCallCount, iterationCount, startTime, endTime };
11154
+ }
11155
+ fail(error, startTime, toolCallCount, iterationCount, name, code) {
11156
+ const err = error instanceof Error ? error : new Error(String(error));
11157
+ const execError = {
11158
+ message: err.message,
11159
+ name: name ?? err.name,
11160
+ ...err.stack ? { stack: err.stack } : {},
11161
+ ...code ? { code } : {}
11162
+ };
11163
+ return { success: false, error: execError, stats: this.stats(startTime, toolCallCount, iterationCount) };
11164
+ }
11165
+ };
11166
+
11167
+ // libs/core/src/index.ts
10489
11168
  init_worker_pool();
10490
11169
 
10491
11170
  // libs/core/src/session/session.ts
@@ -10516,6 +11195,12 @@ var SessionEmitter = class {
10516
11195
  getSeq() {
10517
11196
  return this.seq;
10518
11197
  }
11198
+ /**
11199
+ * Advance and return the next sequence number.
11200
+ */
11201
+ nextSeq() {
11202
+ return ++this.seq;
11203
+ }
10519
11204
  /**
10520
11205
  * Emit a stream event
10521
11206
  */
@@ -10630,7 +11315,7 @@ var SessionEmitter = class {
10630
11315
  /**
10631
11316
  * Create and emit a final event (success)
10632
11317
  */
10633
- emitFinalSuccess(result, stats) {
11318
+ emitFinalSuccess(result, stats, errors) {
10634
11319
  const event = {
10635
11320
  protocolVersion: PROTOCOL_VERSION,
10636
11321
  sessionId: this.sessionId,
@@ -10639,6 +11324,7 @@ var SessionEmitter = class {
10639
11324
  payload: {
10640
11325
  ok: true,
10641
11326
  result,
11327
+ ...errors && errors.length > 0 && { errors },
10642
11328
  stats
10643
11329
  }
10644
11330
  };
@@ -10648,7 +11334,7 @@ var SessionEmitter = class {
10648
11334
  /**
10649
11335
  * Create and emit a final event (failure)
10650
11336
  */
10651
- emitFinalError(error, stats) {
11337
+ emitFinalError(error, stats, errors) {
10652
11338
  const event = {
10653
11339
  protocolVersion: PROTOCOL_VERSION,
10654
11340
  sessionId: this.sessionId,
@@ -10657,6 +11343,7 @@ var SessionEmitter = class {
10657
11343
  payload: {
10658
11344
  ok: false,
10659
11345
  error,
11346
+ ...errors && errors.length > 0 && { errors },
10660
11347
  stats
10661
11348
  }
10662
11349
  };
@@ -11347,6 +12034,9 @@ export {
11347
12034
  ExternalApiScorer,
11348
12035
  ExternalApiScorerError,
11349
12036
  FeatureExtractor,
12037
+ Interpreter,
12038
+ InterpreterAdapter,
12039
+ InterpreterError,
11350
12040
  MemoryLimitError,
11351
12041
  MemoryMonitor,
11352
12042
  MemoryTracker,
@@ -11373,6 +12063,7 @@ export {
11373
12063
  SessionEmitter,
11374
12064
  SessionStateMachine,
11375
12065
  SidecarLimitError,
12066
+ StepLimitError,
11376
12067
  TooManyPendingCallsError,
11377
12068
  WORKER_POOL_PRESETS,
11378
12069
  WorkerCrashedError,