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
@@ -3,9 +3,8 @@ import { B as isSymbol, I as isFunction, M as baseAssignValue, t as baseIteratee
3
3
  import { t as baseForOwn } from "./_baseForOwn-CFhWe_W6.js";
4
4
  import { t as cleanStackTrace } from "./stack-traces-BIE_5Xwf.js";
5
5
  import { a as InvalidCodeError, c as SnapshotSignal, n as CodeExecutionError, s as Signals, u as VMSignal } from "./errors-Cg1G0Awu.js";
6
+ import { n as compile, t as Identifiers } from "./compiler-CW1VjQsn.js";
6
7
  import { n as getQuickJSVariant } from "./quickjs-variant-BYhMBpwU.js";
7
- import MagicString from "magic-string";
8
- import { parse } from "acorn";
9
8
  import { newQuickJSWASMModuleFromVariant, shouldInterruptAfterDeadline } from "quickjs-emscripten-core";
10
9
  //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGt.js
11
10
  /**
@@ -2205,470 +2204,12 @@ var require_source_node = /* @__PURE__ */ __commonJSMin(((exports) => {
2205
2204
  exports.SourceNode = SourceNode;
2206
2205
  }));
2207
2206
  //#endregion
2208
- //#region src/compiler/ast.ts
2207
+ //#region src/vm/errors.ts
2209
2208
  var import_source_map = (/* @__PURE__ */ __commonJSMin(((exports) => {
2210
2209
  exports.SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
2211
2210
  exports.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer;
2212
2211
  exports.SourceNode = require_source_node().SourceNode;
2213
2212
  })))();
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 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 MagicString(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 MagicString(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
2213
  const handleErrorQuickJS = (err, code, _consumer, traces, variables, lines_executed, userCodeStartLine, currentToolCall) => {
2673
2214
  err = Signals.maybeDeserializeError(err);
2674
2215
  const lines = code.split("\n");
@@ -3433,4 +2974,4 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
3433
2974
  });
3434
2975
  }
3435
2976
  //#endregion
3436
- export { runAsyncFunction, hasTopLevelReturn as t, warmupVM };
2977
+ export { runAsyncFunction, warmupVM };