llmz 0.7.0 → 0.8.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.
Files changed (47) hide show
  1. package/dist/{_baseForOwn-buOZDFbK.cjs → _baseForOwn-BfWDTL8L.cjs} +0 -50
  2. package/dist/common-DdArNQhl.cjs +643 -0
  3. package/dist/common-pgJjFu2Y.js +596 -0
  4. package/dist/compiler-C-OI9sim.cjs +547 -0
  5. package/dist/compiler-CW1VjQsn.js +473 -0
  6. package/dist/{component-BwixNVH8.cjs → component-BXS8vAwO.cjs} +3 -3
  7. package/dist/{component-DGG7d_Mz.js → component-Dq7ZLdvy.js} +1 -1
  8. package/dist/component.d.ts +4 -4
  9. package/dist/component.default.d.ts +60 -87
  10. package/dist/component.default.test.d.ts +1 -0
  11. package/dist/context.d.ts +10 -0
  12. package/dist/{custom-client-CMuy7fXU.js → custom-client-2V9lmzUf.js} +119 -24
  13. package/dist/{custom-client-Bp1TgTKk.cjs → custom-client-HkM1Sdzv.cjs} +124 -29
  14. package/dist/{dual-modes-CfqTk9M8.cjs → dual-modes-Cb7ThvoV.cjs} +1268 -1062
  15. package/dist/{dual-modes-mNyMThtf.js → dual-modes-Cy0_W4O2.js} +1242 -1036
  16. package/dist/example.d.ts +45 -0
  17. package/dist/example.test.d.ts +1 -0
  18. package/dist/{execute-DP_17lYZ.js → execute-Aw4cbIx-.js} +23 -10
  19. package/dist/{execute-msui51b2.cjs → execute-COIHOIKR.cjs} +30 -18
  20. package/dist/{exit-BGi0Kk0y.cjs → exit-DUM96DN1.cjs} +3 -3
  21. package/dist/exit-parser.d.ts +2 -0
  22. package/dist/index.cjs +33 -356
  23. package/dist/index.d.ts +2 -0
  24. package/dist/index.js +13 -337
  25. package/dist/index.workerd.js +9981 -9388
  26. package/dist/{jsx-CIgdGGVs.js → jsx-B0iYyvfr.js} +50 -2
  27. package/dist/{jsx-BWvT6ukg.cjs → jsx-D5Y2cPo-.cjs} +58 -4
  28. package/dist/message-stream/parser.d.ts +3 -0
  29. package/dist/message-stream/types.d.ts +1 -1
  30. package/dist/prompts/chat-mode/system.d.ts +2 -0
  31. package/dist/prompts/chat-mode/user.d.ts +2 -0
  32. package/dist/prompts/execution-history.d.ts +6 -0
  33. package/dist/prompts/execution-state.d.ts +3 -0
  34. package/dist/prompts/prompt.d.ts +26 -0
  35. package/dist/prompts/protocol.test.d.ts +1 -0
  36. package/dist/prompts/worker-mode/system.d.ts +2 -0
  37. package/dist/prompts/worker-mode/user.d.ts +2 -0
  38. package/dist/runtime/types.d.ts +9 -0
  39. package/dist/{tool-ReA9gxMp.cjs → tool-Dy6AJpJH.cjs} +4 -4
  40. package/dist/{truncator-B6aaJaN1.cjs → truncator-CLkouTCO.cjs} +3 -3
  41. package/dist/{typings-BwAz_TM9.cjs → typings-3lsqCbkn.cjs} +3 -3
  42. package/dist/{utils-ZpJm00ed.cjs → utils-3ESwP3yg.cjs} +2 -2
  43. package/dist/{vm-C5vf1LH3.js → vm-BLsHw1da.js} +3 -462
  44. package/dist/{vm-BjkJqSQH.cjs → vm-D6s1zF6M.cjs} +28 -489
  45. package/package.json +2 -2
  46. package/dist/isPlainObject-CSxXVKCk.cjs +0 -56
  47. package/dist/isPlainObject-D39AzPO2.js +0 -51
@@ -1,11 +1,9 @@
1
- const require__baseForOwn = require("./_baseForOwn-buOZDFbK.cjs");
1
+ const require_compiler = require("./compiler-C-OI9sim.cjs");
2
2
  const require__baseIteratee = require("./_baseIteratee-CF4qP2a8.cjs");
3
+ const require__baseForOwn = require("./_baseForOwn-BfWDTL8L.cjs");
3
4
  const require_stack_traces = require("./stack-traces-ntw_qhoy.cjs");
4
5
  const require_errors = require("./errors-C962uJdS.cjs");
5
6
  const require_quickjs_variant = require("./quickjs-variant-CsIwTVFC.cjs");
6
- let magic_string = require("magic-string");
7
- magic_string = require__baseForOwn.__toESM(magic_string, 1);
8
- let acorn = require("acorn");
9
7
  let quickjs_emscripten_core = require("quickjs-emscripten-core");
10
8
  //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGt.js
11
9
  /**
@@ -108,7 +106,7 @@ function maxBy(array, iteratee) {
108
106
  }
109
107
  //#endregion
110
108
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/base64.js
111
- var require_base64 = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports) => {
109
+ var require_base64 = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
112
110
  var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
113
111
  /**
114
112
  * Encode an integer in the range of 0 to 63 to a single base 64 digit.
@@ -142,7 +140,7 @@ var require_base64 = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports
142
140
  }));
143
141
  //#endregion
144
142
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/base64-vlq.js
145
- var require_base64_vlq = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports) => {
143
+ var require_base64_vlq = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
146
144
  var base64 = require_base64();
147
145
  var VLQ_BASE_SHIFT = 5;
148
146
  var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
@@ -207,7 +205,7 @@ var require_base64_vlq = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exp
207
205
  }));
208
206
  //#endregion
209
207
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/util.js
210
- var require_util = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports) => {
208
+ var require_util = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
211
209
  /**
212
210
  * This is a helper function for getting values from parameter/options
213
211
  * objects.
@@ -554,7 +552,7 @@ var require_util = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports)
554
552
  }));
555
553
  //#endregion
556
554
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/array-set.js
557
- var require_array_set = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports) => {
555
+ var require_array_set = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
558
556
  var util = require_util();
559
557
  var has = Object.prototype.hasOwnProperty;
560
558
  var hasNativeMap = typeof Map !== "undefined";
@@ -648,7 +646,7 @@ var require_array_set = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((expo
648
646
  }));
649
647
  //#endregion
650
648
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/mapping-list.js
651
- var require_mapping_list = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports) => {
649
+ var require_mapping_list = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
652
650
  var util = require_util();
653
651
  /**
654
652
  * Determine whether mappingB is after mappingA with respect to generated
@@ -717,7 +715,7 @@ var require_mapping_list = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((e
717
715
  }));
718
716
  //#endregion
719
717
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/source-map-generator.js
720
- var require_source_map_generator = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports) => {
718
+ var require_source_map_generator = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
721
719
  var base64VLQ = require_base64_vlq();
722
720
  var util = require_util();
723
721
  var ArraySet = require_array_set().ArraySet;
@@ -1001,7 +999,7 @@ var require_source_map_generator = /* @__PURE__ */ require__baseForOwn.__commonJ
1001
999
  }));
1002
1000
  //#endregion
1003
1001
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/binary-search.js
1004
- var require_binary_search = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports) => {
1002
+ var require_binary_search = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
1005
1003
  exports.GREATEST_LOWER_BOUND = 1;
1006
1004
  exports.LEAST_UPPER_BOUND = 2;
1007
1005
  /**
@@ -1062,7 +1060,7 @@ var require_binary_search = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((
1062
1060
  }));
1063
1061
  //#endregion
1064
1062
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/quick-sort.js
1065
- var require_quick_sort = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports) => {
1063
+ var require_quick_sort = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
1066
1064
  function SortTemplate(comparator) {
1067
1065
  /**
1068
1066
  * Swap the elements indexed by `x` and `y` in the array `ary`.
@@ -1144,7 +1142,7 @@ var require_quick_sort = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exp
1144
1142
  }));
1145
1143
  //#endregion
1146
1144
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/source-map-consumer.js
1147
- var require_source_map_consumer = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports) => {
1145
+ var require_source_map_consumer = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
1148
1146
  var util = require_util();
1149
1147
  var binarySearch = require_binary_search();
1150
1148
  var ArraySet = require_array_set().ArraySet;
@@ -1920,7 +1918,7 @@ var require_source_map_consumer = /* @__PURE__ */ require__baseForOwn.__commonJS
1920
1918
  }));
1921
1919
  //#endregion
1922
1920
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/source-node.js
1923
- var require_source_node = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports) => {
1921
+ var require_source_node = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
1924
1922
  var SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
1925
1923
  var util = require_util();
1926
1924
  var REGEX_NEWLINE = /(\r?\n)/;
@@ -2205,470 +2203,12 @@ var require_source_node = /* @__PURE__ */ require__baseForOwn.__commonJSMin(((ex
2205
2203
  exports.SourceNode = SourceNode;
2206
2204
  }));
2207
2205
  //#endregion
2208
- //#region src/compiler/ast.ts
2209
- var import_source_map = (/* @__PURE__ */ require__baseForOwn.__commonJSMin(((exports) => {
2206
+ //#region src/vm/errors.ts
2207
+ var import_source_map = (/* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
2210
2208
  exports.SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
2211
2209
  exports.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer;
2212
2210
  exports.SourceNode = require_source_node().SourceNode;
2213
2211
  })))();
2214
- const TS_SMELL = /(^|[^:]):\s*(string|number|boolean|any|unknown|void)\b|\bas\s+(const\b|[A-Z])|\binterface\s+[A-Z]|^\s*type\s+[A-Z]|[a-zA-Z)\]]!\.|<(string|number|boolean)[,>]/m;
2215
- function parseScript(code, opts) {
2216
- try {
2217
- return (0, acorn.parse)(code, {
2218
- ecmaVersion: "latest",
2219
- sourceType: "script",
2220
- locations: true,
2221
- allowReturnOutsideFunction: true,
2222
- allowAwaitOutsideFunction: true,
2223
- ...opts,
2224
- onComment: opts === null || opts === void 0 ? void 0 : opts.comments
2225
- });
2226
- } catch (err) {
2227
- if (err instanceof SyntaxError && TS_SMELL.test(code)) err.message += ". The code must be plain JavaScript: do not use TypeScript syntax (type annotations, \"as\" casts, generics, interfaces or type aliases).";
2228
- throw err;
2229
- }
2230
- }
2231
- /**
2232
- * Depth-first pre-order walk. `ancestors` is ordered outermost → innermost and
2233
- * excludes `node` itself; `parent` is `ancestors[ancestors.length - 1]`.
2234
- */
2235
- function walk(root, enter) {
2236
- const ancestors = [];
2237
- const visit = (node) => {
2238
- enter(node, ancestors[ancestors.length - 1] ?? null, ancestors);
2239
- ancestors.push(node);
2240
- for (const key of Object.keys(node)) {
2241
- if (key === "loc") continue;
2242
- const value = node[key];
2243
- if (Array.isArray(value)) {
2244
- for (const child of value) if (isNode(child)) visit(child);
2245
- } else if (isNode(value)) visit(value);
2246
- }
2247
- ancestors.pop();
2248
- };
2249
- visit(root);
2250
- }
2251
- const isNode = (value) => !!value && typeof value === "object" && typeof value.type === "string";
2252
- const isStatementContainer = (node) => !!node && (node.type === "Program" || node.type === "BlockStatement" || node.type === "StaticBlock");
2253
- /**
2254
- * The statement that contains `node`: the outermost ancestor (or the node
2255
- * itself) whose parent is a statement container.
2256
- */
2257
- function enclosingStatement(node, ancestors) {
2258
- const chain = [...ancestors, node];
2259
- for (let i = chain.length - 1; i > 0; i--) if (isStatementContainer(chain[i - 1])) return chain[i];
2260
- return null;
2261
- }
2262
- /** The innermost node whose range contains [start, end] */
2263
- function innermostContaining(ast, start, end) {
2264
- let best = null;
2265
- walk(ast, (node) => {
2266
- if (node.start <= start && node.end >= end) {
2267
- if (!best || node.start >= best.start && node.end <= best.end) best = node;
2268
- }
2269
- });
2270
- return best;
2271
- }
2272
- //#endregion
2273
- //#region src/compiler/plugins/async-wrapper.ts
2274
- const Open = "async function __fn__() {";
2275
- const Close = "}";
2276
- const USER_CODE_START_MARKER = "/* __LLMZ_USER_CODE_START__ */";
2277
- const USER_CODE_END_MARKER = "/* __LLMZ_USER_CODE_END__ */";
2278
- /**
2279
- * Wraps user code in an async function so top-level `await` and `return` parse,
2280
- * and so plugins can target the `__fn__` declaration. The wrapper is removed
2281
- * after transformation — drivers re-wrap the bare statements themselves.
2282
- */
2283
- const AsyncWrapper = {
2284
- preProcessing: (code) => {
2285
- return `"use strict";
2286
- ${Open}
2287
- ${USER_CODE_START_MARKER}
2288
- ${code}
2289
- ${USER_CODE_END_MARKER}
2290
- ${Close}
2291
- `.trim();
2292
- },
2293
- postProcessing: (code) => {
2294
- code = code.slice(code.indexOf(Open) + 25);
2295
- code = code.slice(0, code.lastIndexOf(Close));
2296
- code = code.replace(USER_CODE_START_MARKER, "").replace(USER_CODE_END_MARKER, "");
2297
- return code.trimEnd();
2298
- }
2299
- };
2300
- //#endregion
2301
- //#region src/compiler/plugins/line-tracking.ts
2302
- const LineTrackingFnIdentifier = "__track__";
2303
- const TRACKED_TYPES = /* @__PURE__ */ new Set([
2304
- "FunctionDeclaration",
2305
- "MethodDefinition",
2306
- "ReturnStatement",
2307
- "AwaitExpression",
2308
- "ForOfStatement",
2309
- "CallExpression",
2310
- "UnaryExpression",
2311
- "VariableDeclaration",
2312
- "AssignmentExpression"
2313
- ]);
2314
- const SKIPPED_PARENT_TYPES = /* @__PURE__ */ new Set([
2315
- "ArrowFunctionExpression",
2316
- "Property",
2317
- "AwaitExpression",
2318
- "UnaryExpression",
2319
- "ReturnStatement",
2320
- "ForOfStatement",
2321
- "ForStatement",
2322
- "ForInStatement",
2323
- "VariableDeclaration",
2324
- "BinaryExpression",
2325
- "LogicalExpression"
2326
- ]);
2327
- /**
2328
- * Inserts a `__track__(<line>)` call before the statement containing each
2329
- * tracked node — at most one per source line.
2330
- */
2331
- function applyLineTracking(ctx) {
2332
- const trackedLines = /* @__PURE__ */ new Set();
2333
- walk(ctx.ast, (node, parent, ancestors) => {
2334
- if (!parent || !node.loc) return;
2335
- if (!TRACKED_TYPES.has(node.type) && parent.type !== "BlockStatement") return;
2336
- const line = node.loc.start.line;
2337
- if (trackedLines.has(line) || SKIPPED_PARENT_TYPES.has(parent.type)) return;
2338
- const statement = enclosingStatement(node, ancestors);
2339
- if (!statement) return;
2340
- trackedLines.add(line);
2341
- ctx.ms.appendLeft(statement.start, `${LineTrackingFnIdentifier}(${line});`);
2342
- });
2343
- }
2344
- //#endregion
2345
- //#region src/compiler/plugins/replace-comment.ts
2346
- const CommentFnIdentifier = "__comment__";
2347
- const MARKER_TAGS = [USER_CODE_START_MARKER, USER_CODE_END_MARKER].map((m) => m.replace(/\/\*|\*\/|\s/g, ""));
2348
- /** Blanks a range, keeping newlines so line numbers are preserved */
2349
- const blank = (ctx, start, end) => {
2350
- ctx.ms.update(start, end, ctx.code.slice(start, end).replace(/[^\n]/g, " "));
2351
- };
2352
- /**
2353
- * Replaces comments at statement position with `__comment__("<text>", <line>)`
2354
- * calls so the agent's inline "thinking" comments show up as traces at runtime.
2355
- * Comments inside expressions and the user-code markers are blanked; comments
2356
- * inside instrumented tool-call ranges are left verbatim.
2357
- */
2358
- function applyCommentReplacement(ctx, skipRanges) {
2359
- for (const comment of ctx.comments) {
2360
- const text = comment.value.trim();
2361
- if (MARKER_TAGS.some((tag) => text.includes(tag))) {
2362
- blank(ctx, comment.start, comment.end);
2363
- continue;
2364
- }
2365
- if (skipRanges.some(([start, end]) => comment.start >= start && comment.end <= end)) continue;
2366
- const container = innermostContaining(ctx.ast, comment.start, comment.end);
2367
- if (isStatementContainer(container)) {
2368
- const newlines = ctx.code.slice(comment.start, comment.end).replace(/[^\n]/g, "");
2369
- ctx.ms.update(comment.start, comment.end, `;${CommentFnIdentifier}(${JSON.stringify(text)}, ${comment.loc.start.line});${newlines}`);
2370
- } else blank(ctx, comment.start, comment.end);
2371
- }
2372
- }
2373
- //#endregion
2374
- //#region src/compiler/plugins/return-async.ts
2375
- /**
2376
- * Plans the instrumentation of the last statement of the `__fn__` wrapper so
2377
- * the generated code always returns an awaited value (the isolated VM cannot
2378
- * return a pending Promise):
2379
- * - `return expr` → `return await (expr)`
2380
- * - a trailing `call()` / `await call()` statement → `return await (…)`
2381
- *
2382
- * The prefix must be applied before, and the suffix after, all other edits so
2383
- * they wrap around the tool-call instrumentation.
2384
- */
2385
- function planLastLineInstrumentation(ast) {
2386
- const fn = ast.body.find((node) => {
2387
- var _id;
2388
- return node.type === "FunctionDeclaration" && ((_id = node.id) === null || _id === void 0 ? void 0 : _id.name) === "__fn__";
2389
- });
2390
- if (!fn) return null;
2391
- const statements = fn.body.body;
2392
- const last = statements[statements.length - 1];
2393
- if (!last) return null;
2394
- if (last.type === "ReturnStatement") {
2395
- if (!last.argument) return null;
2396
- return {
2397
- prefixPos: last.argument.start,
2398
- prefix: "await (",
2399
- suffixPos: last.argument.end,
2400
- suffix: ")"
2401
- };
2402
- }
2403
- if (last.type === "ExpressionStatement" && (last.expression.type === "CallExpression" || last.expression.type === "AwaitExpression")) return {
2404
- prefixPos: last.expression.start,
2405
- prefix: "return await (",
2406
- suffixPos: last.expression.end,
2407
- suffix: ")"
2408
- };
2409
- return null;
2410
- }
2411
- //#endregion
2412
- //#region src/compiler/plugins/track-tool-calls.ts
2413
- const ToolCallTrackerFnIdentifier = "__toolc__";
2414
- const ToolTrackerRetIdentifier = "__ret__";
2415
- /**
2416
- * Wraps every outermost call expression in an IIFE that reports
2417
- * `__toolc__(<id>, "start" | "end", …)` events around the call:
2418
- *
2419
- * const x = (() => {
2420
- * try {
2421
- * __toolc__(0, "start");
2422
- * const __ret__ = tool();
2423
- * __toolc__(0, "end", __ret__);
2424
- * return __ret__;
2425
- * } catch (err) { __toolc__(1, "end", err); throw new Error(err.message); }
2426
- * })()
2427
- *
2428
- * Calls assigned to a variable are registered in `calls` (keyed by the id used
2429
- * in the catch clause — the id the runtime sees when a tool throws a
2430
- * SnapshotSignal). Awaited calls get an async IIFE that awaits the call.
2431
- *
2432
- * Returns the wrapped source ranges so later passes can avoid editing inside.
2433
- */
2434
- function applyToolCallTracking(ctx, calls) {
2435
- let callId = 0;
2436
- const wrappedRanges = [];
2437
- const src = ctx.code;
2438
- const sliceOf = (node) => src.slice(node.start, node.end);
2439
- const extractAssignment = (lval) => {
2440
- const source = sliceOf(lval);
2441
- if (lval.type === "Identifier") return {
2442
- type: "single",
2443
- left: source,
2444
- evalFn: `let ${source} = arguments[0]; return { ${source} };`
2445
- };
2446
- if (lval.type === "ArrayPattern") {
2447
- const elements = lval.elements.map((el) => el ? sliceOf(el) : "").join(", ");
2448
- return {
2449
- type: "array",
2450
- left: elements,
2451
- evalFn: `let [${elements}] = arguments[0] ?? []; return { ${elements} };`
2452
- };
2453
- }
2454
- if (lval.type === "ObjectPattern") return {
2455
- type: "object",
2456
- left: source,
2457
- evalFn: `let ${source} = arguments[0] ?? {}; return ${source};`
2458
- };
2459
- return {
2460
- type: "unsupported",
2461
- left: "",
2462
- evalFn: ""
2463
- };
2464
- };
2465
- walk(ctx.ast, (node, parent, ancestors) => {
2466
- if (node.type !== "CallExpression") return;
2467
- if (wrappedRanges.some(([start, end]) => node.start >= start && node.end <= end)) return;
2468
- if ((parent === null || parent === void 0 ? void 0 : parent.type) === "YieldExpression") return;
2469
- const declaration = [...ancestors].reverse().find((n) => n.type === "VariableDeclaration");
2470
- const assignment = [...ancestors].reverse().find((n) => n.type === "AssignmentExpression");
2471
- let lval = null;
2472
- if (declaration) {
2473
- var _;
2474
- lval = ((_ = declaration.declarations[0]) === null || _ === void 0 ? void 0 : _.id) ?? null;
2475
- }
2476
- if (assignment) lval = assignment.left;
2477
- const isAsync = (parent === null || parent === void 0 ? void 0 : parent.type) === "AwaitExpression";
2478
- const start = (id) => `${ToolCallTrackerFnIdentifier}(${id}, "start");`;
2479
- const end = (id, value) => `${ToolCallTrackerFnIdentifier}(${id}, "end", ${value});`;
2480
- const prefix = (id) => `(${isAsync ? "async " : ""}() => {try {${start(id)}const ${ToolTrackerRetIdentifier} = ${isAsync ? "await " : ""}`;
2481
- const successSuffix = (id) => `;${end(id, ToolTrackerRetIdentifier)}return ${ToolTrackerRetIdentifier};}`;
2482
- if (!lval) {
2483
- if (!sliceOf(node).trim().length) return;
2484
- const catchClause = ` catch (err) {${end(callId, "err")}const __newError = new Error(err.message);__newError.stack = err.stack + ("\\n" + __newError.stack);throw __newError;}})()`;
2485
- ctx.ms.appendLeft(node.start, prefix(callId));
2486
- ctx.ms.appendRight(node.end, successSuffix(callId) + catchClause);
2487
- wrappedRanges.push([node.start, node.end]);
2488
- callId++;
2489
- return;
2490
- }
2491
- const assign = extractAssignment(lval);
2492
- if (assign.type === "unsupported") return;
2493
- const tryId = callId;
2494
- callId++;
2495
- const callee = node.callee;
2496
- let object = "global";
2497
- let tool = callee.type === "Identifier" ? callee.name : sliceOf(callee);
2498
- if (callee.type === "MemberExpression") {
2499
- object = sliceOf(callee.object);
2500
- const property = callee.property;
2501
- tool = property.type === "Identifier" ? property.name : property.type === "Literal" ? String(property.value) : sliceOf(property);
2502
- }
2503
- const catchClause = ` catch (err) {${end(callId, "err")}throw new Error(err.message);}})()`;
2504
- ctx.ms.appendLeft(node.start, prefix(tryId));
2505
- ctx.ms.appendRight(node.end, successSuffix(tryId) + catchClause);
2506
- wrappedRanges.push([node.start, node.end]);
2507
- calls.set(callId, {
2508
- object,
2509
- tool,
2510
- assignment: assign
2511
- });
2512
- });
2513
- return wrappedRanges;
2514
- }
2515
- //#endregion
2516
- //#region src/compiler/plugins/variable-extraction.ts
2517
- const VariableTrackingFnIdentifier = "__var__";
2518
- /**
2519
- * Tracks user variables so the VM can read their values between iterations:
2520
- * - after each variable declaration: `__var__("a", () => eval("a"));`
2521
- * - at the top of function bodies, for their parameters
2522
- *
2523
- * The `eval` indirection captures the variable lazily in its own scope.
2524
- */
2525
- function applyVariableTracking(ctx, variables) {
2526
- const trackerFor = (name) => {
2527
- if (name.startsWith("__")) return null;
2528
- variables.add(name);
2529
- return `${VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => eval(${JSON.stringify(name)}));`;
2530
- };
2531
- const track = (names) => names.map(trackerFor).filter((t) => !!t).join("");
2532
- const declaredNames = (id) => {
2533
- if (id.type === "Identifier") return [id.name];
2534
- if (id.type === "ObjectPattern") {
2535
- const names = [];
2536
- for (const prop of id.properties) {
2537
- if (prop.type !== "Property") continue;
2538
- if (prop.value.type === "Identifier") names.push(prop.value.name);
2539
- else if (prop.value.type === "ObjectPattern") names.push(...declaredNames(prop.value));
2540
- else if (prop.value.type === "AssignmentPattern" && prop.value.left.type === "Identifier") names.push(prop.value.left.name);
2541
- }
2542
- return names;
2543
- }
2544
- if (id.type === "ArrayPattern") {
2545
- const names = [];
2546
- for (const element of id.elements) {
2547
- if (!element) continue;
2548
- if (element.type === "Identifier") names.push(element.name);
2549
- else if (element.type === "RestElement" && element.argument.type === "Identifier") names.push(element.argument.name);
2550
- else if (element.type === "AssignmentPattern" && element.left.type === "Identifier") names.push(element.left.name);
2551
- }
2552
- return names;
2553
- }
2554
- return [];
2555
- };
2556
- const paramNames = (params) => {
2557
- const names = [];
2558
- for (const param of params) if (param.type === "Identifier") names.push(param.name);
2559
- else if (param.type === "AssignmentPattern" && param.left.type === "Identifier") names.push(param.left.name);
2560
- else if (param.type === "ObjectPattern") {
2561
- for (const prop of param.properties) if (prop.type === "Property" && prop.value.type === "Identifier") names.push(prop.value.name);
2562
- } else if (param.type === "ArrayPattern") {
2563
- for (const element of param.elements) if ((element === null || element === void 0 ? void 0 : element.type) === "Identifier") names.push(element.name);
2564
- }
2565
- return names;
2566
- };
2567
- walk(ctx.ast, (node, parent) => {
2568
- if (node.type === "VariableDeclaration") {
2569
- if (parent && (parent.type === "ForStatement" || parent.type === "ForInStatement" || parent.type === "ForOfStatement")) return;
2570
- const trackers = track(node.declarations.flatMap((d) => declaredNames(d.id)));
2571
- if (trackers) {
2572
- const semi = ctx.code[node.end - 1] === ";" ? "" : ";";
2573
- ctx.ms.appendRight(node.end, `${semi}${trackers}`);
2574
- }
2575
- return;
2576
- }
2577
- if (node.type === "FunctionDeclaration" || node.type === "ArrowFunctionExpression") {
2578
- const trackers = track(paramNames(node.params));
2579
- if (!trackers) return;
2580
- const body = node.body;
2581
- if (body.type === "BlockStatement") ctx.ms.appendRight(body.start + 1, trackers);
2582
- else {
2583
- ctx.ms.appendLeft(body.start, `{${trackers}return (`);
2584
- ctx.ms.appendRight(body.end, ");}");
2585
- }
2586
- }
2587
- });
2588
- }
2589
- //#endregion
2590
- //#region src/compiler/compiler.ts
2591
- const Identifiers = {
2592
- ConsoleObjIdentifier: "console",
2593
- LineTrackingFnIdentifier,
2594
- VariableTrackingFnIdentifier,
2595
- ToolCallTrackerFnIdentifier,
2596
- ToolTrackerRetIdentifier,
2597
- CommentFnIdentifier
2598
- };
2599
- const FUNCTION_TYPES = /* @__PURE__ */ new Set([
2600
- "FunctionDeclaration",
2601
- "FunctionExpression",
2602
- "ArrowFunctionExpression"
2603
- ]);
2604
- /**
2605
- * Whether the code contains a top-level `return` statement (one that would
2606
- * return from the generated code itself, not from a nested function). Unlike a
2607
- * regex, this ignores `return` inside comments, strings and nested functions.
2608
- * Falls back to a word-boundary match if the code cannot be parsed.
2609
- */
2610
- function hasTopLevelReturn(code) {
2611
- try {
2612
- const ast = parseScript(code);
2613
- let found = false;
2614
- walk(ast, (node, _parent, ancestors) => {
2615
- if (node.type === "ReturnStatement" && !ancestors.some((a) => FUNCTION_TYPES.has(a.type))) found = true;
2616
- });
2617
- return found;
2618
- } catch {
2619
- return /\breturn\b/.test(code);
2620
- }
2621
- }
2622
- /**
2623
- * Compiles the agent's generated JavaScript for VM execution:
2624
- *
2625
- * 1. wraps it in an async `__fn__` so top-level `await`/`return` parse
2626
- * 2. instruments it in a single parse + text-edit pass:
2627
- * line tracking, last-line return, tool-call tracking, comment tracing
2628
- * and variable tracking
2629
- * 3. unwraps it — the VM drivers re-wrap the bare statements themselves
2630
- *
2631
- * All edits preserve line numbers 1:1 with the wrapped source, so positions
2632
- * reported at runtime map straight back to the user code.
2633
- */
2634
- function compile(code) {
2635
- const wrapped = AsyncWrapper.preProcessing(code);
2636
- const comments = [];
2637
- const ast = parseScript(wrapped, { comments });
2638
- const variables = /* @__PURE__ */ new Set();
2639
- const toolCalls = /* @__PURE__ */ new Map();
2640
- const lastLine = planLastLineInstrumentation(ast);
2641
- const msMarkers = new magic_string.default(wrapped);
2642
- if (lastLine) {
2643
- msMarkers.appendLeft(lastLine.prefixPos, lastLine.prefix);
2644
- msMarkers.appendRight(lastLine.suffixPos, lastLine.suffix);
2645
- }
2646
- const codeWithMarkers = msMarkers.toString();
2647
- const ms = new magic_string.default(wrapped);
2648
- const ctx = {
2649
- code: wrapped,
2650
- ms,
2651
- ast,
2652
- comments
2653
- };
2654
- applyLineTracking(ctx);
2655
- if (lastLine) ms.appendLeft(lastLine.prefixPos, lastLine.prefix);
2656
- applyCommentReplacement(ctx, applyToolCallTracking(ctx, toolCalls));
2657
- applyVariableTracking(ctx, variables);
2658
- if (lastLine) ms.appendRight(lastLine.suffixPos, lastLine.suffix);
2659
- return {
2660
- code: AsyncWrapper.postProcessing(ms.toString()),
2661
- codeWithMarkers,
2662
- map: ms.generateMap({
2663
- hires: true,
2664
- source: "<anonymous>"
2665
- }),
2666
- variables,
2667
- toolCalls
2668
- };
2669
- }
2670
- //#endregion
2671
- //#region src/vm/errors.ts
2672
2212
  const handleErrorQuickJS = (err, code, _consumer, traces, variables, lines_executed, userCodeStartLine, currentToolCall) => {
2673
2213
  err = require_errors.Signals.maybeDeserializeError(err);
2674
2214
  const lines = code.split("\n");
@@ -2817,15 +2357,15 @@ function formatError(err, lines, matches, traces, variables, lines_executed, cur
2817
2357
  const USER_CODE_MARKER_TAG_START = "__LLMZ_USER_CODE_START__";
2818
2358
  const USER_CODE_MARKER_TAG_END = "__LLMZ_USER_CODE_END__";
2819
2359
  const NO_TRACKING = [
2820
- Identifiers.CommentFnIdentifier,
2821
- Identifiers.ToolCallTrackerFnIdentifier,
2822
- Identifiers.ToolTrackerRetIdentifier,
2823
- Identifiers.VariableTrackingFnIdentifier,
2824
- Identifiers.ConsoleObjIdentifier
2360
+ require_compiler.Identifiers.CommentFnIdentifier,
2361
+ require_compiler.Identifiers.ToolCallTrackerFnIdentifier,
2362
+ require_compiler.Identifiers.ToolTrackerRetIdentifier,
2363
+ require_compiler.Identifiers.VariableTrackingFnIdentifier,
2364
+ require_compiler.Identifiers.ConsoleObjIdentifier
2825
2365
  ];
2826
2366
  function instrumentContext(context, transformed, traces, variables, lines_executed, consumer, userCodeStartLine) {
2827
2367
  const state = { currentToolCall: void 0 };
2828
- context[Identifiers.CommentFnIdentifier] = (comment, line) => {
2368
+ context[require_compiler.Identifiers.CommentFnIdentifier] = (comment, line) => {
2829
2369
  if (comment.includes(USER_CODE_MARKER_TAG_START) || comment.includes(USER_CODE_MARKER_TAG_END)) return;
2830
2370
  traces.push({
2831
2371
  type: "comment",
@@ -2834,7 +2374,7 @@ function instrumentContext(context, transformed, traces, variables, lines_execut
2834
2374
  started_at: Date.now()
2835
2375
  });
2836
2376
  };
2837
- context[Identifiers.LineTrackingFnIdentifier] = (line) => {
2377
+ context[require_compiler.Identifiers.LineTrackingFnIdentifier] = (line) => {
2838
2378
  const mappedLine = consumer.originalPositionFor({
2839
2379
  line,
2840
2380
  column: 0
@@ -2842,7 +2382,7 @@ function instrumentContext(context, transformed, traces, variables, lines_execut
2842
2382
  const userCodeLine = Math.max(1, mappedLine - userCodeStartLine);
2843
2383
  lines_executed.set(userCodeLine, (lines_executed.get(userCodeLine) ?? 0) + 1);
2844
2384
  };
2845
- context[Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
2385
+ context[require_compiler.Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
2846
2386
  if (NO_TRACKING.includes(name)) return;
2847
2387
  variables[name] = () => {
2848
2388
  try {
@@ -2854,7 +2394,7 @@ function instrumentContext(context, transformed, traces, variables, lines_execut
2854
2394
  }
2855
2395
  };
2856
2396
  };
2857
- context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
2397
+ context[require_compiler.Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
2858
2398
  const temp = require_errors.Signals.maybeDeserializeError(outputOrError === null || outputOrError === void 0 ? void 0 : outputOrError.message);
2859
2399
  if (type === "end" && temp instanceof require_errors.SnapshotSignal && (temp === null || temp === void 0 ? void 0 : temp.toolCall)) {
2860
2400
  var _transformed$toolCall;
@@ -2864,7 +2404,7 @@ function instrumentContext(context, transformed, traces, variables, lines_execut
2864
2404
  };
2865
2405
  }
2866
2406
  };
2867
- context[Identifiers.ConsoleObjIdentifier] = { log: (...args) => {
2407
+ context[require_compiler.Identifiers.ConsoleObjIdentifier] = { log: (...args) => {
2868
2408
  const message = args.shift();
2869
2409
  traces.push({
2870
2410
  type: "log",
@@ -2898,7 +2438,7 @@ var NodeDriver = class {
2898
2438
  };
2899
2439
  context.__report = __report;
2900
2440
  const reportAll = topLevelProperties.map((x) => `__report("${x}", ${x})`).join(";");
2901
- const wrapper = `"use strict"; try { ${`let __${Identifiers.LineTrackingFnIdentifier} = ${Identifiers.LineTrackingFnIdentifier}; ${Identifiers.LineTrackingFnIdentifier} = function(line) { ${reportAll}; __${Identifiers.LineTrackingFnIdentifier}(line);}`};${transformed.code} } finally { ${reportAll} };`;
2441
+ const wrapper = `"use strict"; try { ${`let __${require_compiler.Identifiers.LineTrackingFnIdentifier} = ${require_compiler.Identifiers.LineTrackingFnIdentifier}; ${require_compiler.Identifiers.LineTrackingFnIdentifier} = function(line) { ${reportAll}; __${require_compiler.Identifiers.LineTrackingFnIdentifier}(line);}`};${transformed.code} } finally { ${reportAll} };`;
2902
2442
  return await AsyncFunction(...Object.keys(context), wrapper)(...Object.values(context));
2903
2443
  })().then((res) => {
2904
2444
  res = require_errors.Signals.maybeDeserializeError(res);
@@ -3287,7 +2827,7 @@ function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue) {
3287
2827
  else result.value.dispose();
3288
2828
  }
3289
2829
  function setupVariableTrackingBridge(vm, variables) {
3290
- const varTrackFnHandle = vm.newFunction(Identifiers.VariableTrackingFnIdentifier, (nameHandle, getterHandle) => {
2830
+ const varTrackFnHandle = vm.newFunction(require_compiler.Identifiers.VariableTrackingFnIdentifier, (nameHandle, getterHandle) => {
3291
2831
  const name = vm.getString(nameHandle);
3292
2832
  if (NO_TRACKING.includes(name)) return;
3293
2833
  try {
@@ -3306,7 +2846,7 @@ function setupVariableTrackingBridge(vm, variables) {
3306
2846
  variables[name] = "[[non-primitive]]";
3307
2847
  }
3308
2848
  });
3309
- vm.setProp(vm.global, Identifiers.VariableTrackingFnIdentifier, varTrackFnHandle);
2849
+ vm.setProp(vm.global, require_compiler.Identifiers.VariableTrackingFnIdentifier, varTrackFnHandle);
3310
2850
  varTrackFnHandle.dispose();
3311
2851
  }
3312
2852
  function buildScriptCode(transformedCode) {
@@ -3355,7 +2895,7 @@ const warmupVM = () => {
3355
2895
  async function runAsyncFunction(context, code, traces = [], signal = null, timeout = MAX_VM_EXECUTION_TIME) {
3356
2896
  const transformed = (() => {
3357
2897
  try {
3358
- return compile(code);
2898
+ return require_compiler.compile(code);
3359
2899
  } catch (err) {
3360
2900
  traces.push({
3361
2901
  type: "invalid_code_exception",
@@ -3433,6 +2973,5 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
3433
2973
  });
3434
2974
  }
3435
2975
  //#endregion
3436
- exports.hasTopLevelReturn = hasTopLevelReturn;
3437
2976
  exports.runAsyncFunction = runAsyncFunction;
3438
2977
  exports.warmupVM = warmupVM;