llmz 0.2.1 → 0.2.2

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 (35) hide show
  1. package/dist/{chunk-WWZ2W4WR.cjs → chunk-2EZSVF5X.cjs} +382 -492
  2. package/dist/{chunk-ZWUWCRHG.js → chunk-2MSLOTFO.js} +2 -2
  3. package/dist/{chunk-GC5IQDGV.js → chunk-3OSQ4XL4.js} +1 -1
  4. package/dist/{chunk-E5NHK3FS.js → chunk-5ISVDYBA.js} +3 -3
  5. package/dist/{chunk-MY26EAOP.cjs → chunk-5XPEVOOW.cjs} +8 -8
  6. package/dist/{chunk-YGKQEVQQ.cjs → chunk-C2KND2PS.cjs} +3 -3
  7. package/dist/{chunk-DH35WO5G.js → chunk-EJIDFDQP.js} +373 -483
  8. package/dist/{chunk-665O7CAN.js → chunk-GDWRFHM5.js} +4 -0
  9. package/dist/{chunk-DD4AZSP5.cjs → chunk-MHVORH33.cjs} +5 -1
  10. package/dist/{chunk-ETYFOCWC.cjs → chunk-S46T73HR.cjs} +2 -2
  11. package/dist/compiler/ast.d.ts +26 -0
  12. package/dist/compiler/compiler.d.ts +13 -11
  13. package/dist/compiler/plugins/line-tracking.d.ts +6 -4
  14. package/dist/compiler/plugins/replace-comment.d.ts +8 -4
  15. package/dist/compiler/plugins/return-async.d.ts +18 -4
  16. package/dist/compiler/plugins/track-tool-calls.d.ts +21 -4
  17. package/dist/compiler/plugins/variable-extraction.d.ts +9 -4
  18. package/dist/component.default.d.ts +13 -91
  19. package/dist/{dual-modes-ZZY6QPYT.cjs → dual-modes-IZQJTXR7.cjs} +2 -2
  20. package/dist/{dual-modes-RMF7V7ZQ.js → dual-modes-J4RWHJ2O.js} +1 -1
  21. package/dist/{execute-2AGZ5QUN.cjs → execute-4IL4QPAR.cjs} +23 -23
  22. package/dist/{execute-LNUBLVMZ.js → execute-6AYBMTRM.js} +5 -5
  23. package/dist/index.cjs +185 -234
  24. package/dist/index.js +172 -221
  25. package/dist/prompts/chat-mode/system.md.d.ts +1 -1
  26. package/dist/prompts/worker-mode/system.md.d.ts +1 -1
  27. package/dist/prompts/worker-mode/user.md.d.ts +1 -1
  28. package/dist/{tool-V55GD2FS.cjs → tool-56I7OSKU.cjs} +3 -3
  29. package/dist/{tool-HTAYKIA2.js → tool-I3MAWDN2.js} +2 -2
  30. package/dist/{typings-S6I6IPTG.cjs → typings-LVI4VGE2.cjs} +2 -2
  31. package/dist/{typings-SCKZCAPN.js → typings-SR3EE6LR.js} +1 -1
  32. package/dist/typings-formatter.d.ts +19 -0
  33. package/dist/{vm-44H4UKI2.js → vm-ZLWGAYYJ.js} +1 -1
  34. package/dist/{vm-A3OTQVIR.cjs → vm-ZVONLAZV.cjs} +2 -2
  35. package/package.json +4 -12
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
2
 
3
3
 
4
4
 
@@ -1934,7 +1934,75 @@ var require_source_map = _chunkHC2QZTVTcjs.__commonJS.call(void 0, {
1934
1934
  var import_source_map_js = _chunkHC2QZTVTcjs.__toESM.call(void 0, require_source_map(), 1);
1935
1935
 
1936
1936
  // src/compiler/compiler.ts
1937
- var _standalone = require('@babel/standalone'); var Babel = _interopRequireWildcard(_standalone);
1937
+ var _magicstring = require('magic-string'); var _magicstring2 = _interopRequireDefault(_magicstring);
1938
+
1939
+ // src/compiler/ast.ts
1940
+ var _acorn = require('acorn');
1941
+ var 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;
1942
+ function parseScript(code, opts) {
1943
+ try {
1944
+ return _acorn.parse.call(void 0, code, {
1945
+ ecmaVersion: "latest",
1946
+ sourceType: "script",
1947
+ locations: true,
1948
+ allowReturnOutsideFunction: true,
1949
+ allowAwaitOutsideFunction: true,
1950
+ ...opts,
1951
+ onComment: opts == null ? void 0 : opts.comments
1952
+ });
1953
+ } catch (err) {
1954
+ if (err instanceof SyntaxError && TS_SMELL.test(code)) {
1955
+ err.message += '. The code must be plain JavaScript: do not use TypeScript syntax (type annotations, "as" casts, generics, interfaces or type aliases).';
1956
+ }
1957
+ throw err;
1958
+ }
1959
+ }
1960
+ function walk(root, enter) {
1961
+ const ancestors = [];
1962
+ const visit = (node) => {
1963
+ enter(node, _nullishCoalesce(ancestors[ancestors.length - 1], () => ( null)), ancestors);
1964
+ ancestors.push(node);
1965
+ for (const key of Object.keys(node)) {
1966
+ if (key === "loc") {
1967
+ continue;
1968
+ }
1969
+ const value = node[key];
1970
+ if (Array.isArray(value)) {
1971
+ for (const child of value) {
1972
+ if (isNode(child)) {
1973
+ visit(child);
1974
+ }
1975
+ }
1976
+ } else if (isNode(value)) {
1977
+ visit(value);
1978
+ }
1979
+ }
1980
+ ancestors.pop();
1981
+ };
1982
+ visit(root);
1983
+ }
1984
+ var isNode = (value) => !!value && typeof value === "object" && typeof value.type === "string";
1985
+ var isStatementContainer = (node) => !!node && (node.type === "Program" || node.type === "BlockStatement" || node.type === "StaticBlock");
1986
+ function enclosingStatement(node, ancestors) {
1987
+ const chain = [...ancestors, node];
1988
+ for (let i = chain.length - 1; i > 0; i--) {
1989
+ if (isStatementContainer(chain[i - 1])) {
1990
+ return chain[i];
1991
+ }
1992
+ }
1993
+ return null;
1994
+ }
1995
+ function innermostContaining(ast, start, end) {
1996
+ let best = null;
1997
+ walk(ast, (node) => {
1998
+ if (node.start <= start && node.end >= end) {
1999
+ if (!best || node.start >= best.start && node.end <= best.end) {
2000
+ best = node;
2001
+ }
2002
+ }
2003
+ });
2004
+ return best;
2005
+ }
1938
2006
 
1939
2007
  // src/compiler/plugins/async-wrapper.ts
1940
2008
  var Open = "async function __fn__() {";
@@ -1952,467 +2020,303 @@ ${Close}
1952
2020
  `.trim();
1953
2021
  },
1954
2022
  postProcessing: (code) => {
1955
- code = code.slice(code.indexOf(Open) + Open.length).trim();
2023
+ code = code.slice(code.indexOf(Open) + Open.length);
1956
2024
  code = code.slice(0, code.lastIndexOf(Close));
1957
2025
  code = code.replace(USER_CODE_START_MARKER, "").replace(USER_CODE_END_MARKER, "");
1958
- return code;
2026
+ return code.trimEnd();
1959
2027
  }
1960
2028
  };
1961
2029
 
1962
2030
  // src/compiler/plugins/line-tracking.ts
1963
- var _types = require('@babel/types');
1964
2031
  var LineTrackingFnIdentifier = "__track__";
1965
- var lineTrackingBabelPlugin = function({ types: t }) {
1966
- return {
1967
- visitor: {
1968
- Program(path) {
1969
- const trackedLines = /* @__PURE__ */ new Set();
1970
- const lineTrackingCall = (line) => {
1971
- trackedLines.add(line);
1972
- return _types.expressionStatement.call(void 0, _types.callExpression.call(void 0, _types.identifier.call(void 0, LineTrackingFnIdentifier), [_types.numericLiteral.call(void 0, line)]));
1973
- };
1974
- path.traverse({
1975
- enter(path2) {
1976
- if (path2.node.loc && !path2.isProgram()) {
1977
- const { line: startLine } = path2.node.loc.start;
1978
- const node = path2.node;
1979
- const track = () => {
1980
- try {
1981
- path2.insertBefore(lineTrackingCall(startLine));
1982
- } catch (e) {
1983
- console.error(e);
1984
- }
1985
- };
1986
- if (t.isFunctionDeclaration(node) || t.isClassMethod(node) || t.isReturnStatement(node) || t.isAwaitExpression(node) || t.isForOfStatement(node) || t.isCallExpression(node) || t.isUnaryExpression(node) || t.isVariableDeclaration(node) || t.isBlockStatement(path2.parent) || t.isAssignmentExpression(node)) {
1987
- if (!trackedLines.has(startLine) && !t.isArrowFunctionExpression(path2.parent) && !t.isObjectProperty(path2.parent) && !t.isAwaitExpression(path2.parent) && !t.isUnaryExpression(path2.parent) && !t.isReturnStatement(path2.parent) && !t.isForOfStatement(path2.parent) && !t.isForStatement(path2.parent) && !t.isForInStatement(path2.parent) && !t.isVariableDeclaration(path2.parent) && !t.isBinaryExpression(path2.parent) && !t.isLogicalExpression(path2.parent)) {
1988
- track();
1989
- }
1990
- }
1991
- }
1992
- }
1993
- });
1994
- }
2032
+ var TRACKED_TYPES = /* @__PURE__ */ new Set([
2033
+ "FunctionDeclaration",
2034
+ "MethodDefinition",
2035
+ "ReturnStatement",
2036
+ "AwaitExpression",
2037
+ "ForOfStatement",
2038
+ "CallExpression",
2039
+ "UnaryExpression",
2040
+ "VariableDeclaration",
2041
+ "AssignmentExpression"
2042
+ ]);
2043
+ var SKIPPED_PARENT_TYPES = /* @__PURE__ */ new Set([
2044
+ "ArrowFunctionExpression",
2045
+ "Property",
2046
+ "AwaitExpression",
2047
+ "UnaryExpression",
2048
+ "ReturnStatement",
2049
+ "ForOfStatement",
2050
+ "ForStatement",
2051
+ "ForInStatement",
2052
+ "VariableDeclaration",
2053
+ "BinaryExpression",
2054
+ "LogicalExpression"
2055
+ ]);
2056
+ function applyLineTracking(ctx) {
2057
+ const trackedLines = /* @__PURE__ */ new Set();
2058
+ walk(ctx.ast, (node, parent, ancestors) => {
2059
+ if (!parent || !node.loc) {
2060
+ return;
1995
2061
  }
1996
- };
1997
- };
2062
+ if (!TRACKED_TYPES.has(node.type) && parent.type !== "BlockStatement") {
2063
+ return;
2064
+ }
2065
+ const line = node.loc.start.line;
2066
+ if (trackedLines.has(line) || SKIPPED_PARENT_TYPES.has(parent.type)) {
2067
+ return;
2068
+ }
2069
+ const statement = enclosingStatement(node, ancestors);
2070
+ if (!statement) {
2071
+ return;
2072
+ }
2073
+ trackedLines.add(line);
2074
+ ctx.ms.appendLeft(statement.start, `${LineTrackingFnIdentifier}(${line});`);
2075
+ });
2076
+ }
1998
2077
 
1999
2078
  // src/compiler/plugins/replace-comment.ts
2000
2079
  var CommentFnIdentifier = "__comment__";
2001
- var replaceCommentBabelPlugin = function({
2002
- types: t
2003
- }) {
2004
- return {
2005
- visitor: {
2006
- Program(path) {
2007
- const processed = /* @__PURE__ */ new Set();
2008
- path.traverse({
2009
- enter(path2) {
2010
- const node = path2.node;
2011
- function processComments(comments, insertMethod) {
2012
- if (!comments) {
2013
- return;
2014
- }
2015
- comments.sort((a, b) => a.start > b.start ? -1 : 1).forEach((comment) => {
2016
- var _a;
2017
- if (processed.has(comment.loc)) {
2018
- return;
2019
- }
2020
- processed.add(comment.loc);
2021
- const commentCall = t.expressionStatement(
2022
- t.callExpression(t.identifier(CommentFnIdentifier), [
2023
- t.stringLiteral(comment.value.trim()),
2024
- t.numericLiteral(_nullishCoalesce(((_a = comment.loc) == null ? void 0 : _a.start.line), () => ( 0)))
2025
- ])
2026
- );
2027
- const isInsideObjectProperty = t.isObjectProperty(node) || path2.findParent((path3) => t.isObjectProperty(path3.node));
2028
- if (!isInsideObjectProperty) {
2029
- insertMethod(commentCall);
2030
- }
2031
- });
2032
- comments.length = 0;
2033
- }
2034
- processComments(_nullishCoalesce(node.trailingComments, () => ( [])), (commentCall) => path2.insertAfter(commentCall));
2035
- processComments(_nullishCoalesce(node.leadingComments, () => ( [])), (commentCall) => path2.insertBefore(commentCall));
2036
- processComments(_nullishCoalesce(node.innerComments, () => ( [])), (commentCall) => path2.insertAfter(commentCall));
2037
- }
2038
- });
2039
- }
2040
- }
2041
- };
2080
+ var MARKER_TAGS = [USER_CODE_START_MARKER, USER_CODE_END_MARKER].map((m) => m.replace(/\/\*|\*\/|\s/g, ""));
2081
+ var blank = (ctx, start, end) => {
2082
+ ctx.ms.update(start, end, ctx.code.slice(start, end).replace(/[^\n]/g, " "));
2042
2083
  };
2084
+ function applyCommentReplacement(ctx, skipRanges) {
2085
+ for (const comment of ctx.comments) {
2086
+ const text = comment.value.trim();
2087
+ if (MARKER_TAGS.some((tag) => text.includes(tag))) {
2088
+ blank(ctx, comment.start, comment.end);
2089
+ continue;
2090
+ }
2091
+ if (skipRanges.some(([start, end]) => comment.start >= start && comment.end <= end)) {
2092
+ continue;
2093
+ }
2094
+ const container = innermostContaining(ctx.ast, comment.start, comment.end);
2095
+ if (isStatementContainer(container)) {
2096
+ const newlines = ctx.code.slice(comment.start, comment.end).replace(/[^\n]/g, "");
2097
+ ctx.ms.update(
2098
+ comment.start,
2099
+ comment.end,
2100
+ `;${CommentFnIdentifier}(${JSON.stringify(text)}, ${comment.loc.start.line});${newlines}`
2101
+ );
2102
+ } else {
2103
+ blank(ctx, comment.start, comment.end);
2104
+ }
2105
+ }
2106
+ }
2043
2107
 
2044
2108
  // src/compiler/plugins/return-async.ts
2045
- var instrumentLastLinePlugin = function({
2046
- types: t
2047
- }) {
2048
- return {
2049
- visitor: {
2050
- FunctionDeclaration(path) {
2051
- var _a, _b;
2052
- if (((_a = path.node.id) == null ? void 0 : _a.name) !== "__fn__") {
2053
- return;
2054
- }
2055
- const statements = path.node.body.body;
2056
- if (statements.length === 0) {
2057
- return;
2058
- }
2059
- const lastStatement = statements[statements.length - 1];
2060
- if (t.isReturnStatement(lastStatement)) {
2061
- if (t.isExpression(lastStatement.argument)) {
2062
- lastStatement.argument = t.awaitExpression(lastStatement.argument);
2063
- }
2064
- return;
2065
- }
2066
- if (t.isExpressionStatement(lastStatement) && (t.isCallExpression(lastStatement.expression) || t.isAwaitExpression(lastStatement.expression))) {
2067
- const returnStatement3 = t.returnStatement(t.awaitExpression(lastStatement.expression));
2068
- (_b = path.get("body").get("body")[statements.length - 1]) == null ? void 0 : _b.replaceWith(returnStatement3);
2069
- }
2070
- }
2109
+ function planLastLineInstrumentation(ast) {
2110
+ const fn = ast.body.find((node) => {
2111
+ var _a;
2112
+ return node.type === "FunctionDeclaration" && ((_a = node.id) == null ? void 0 : _a.name) === "__fn__";
2113
+ });
2114
+ if (!fn) {
2115
+ return null;
2116
+ }
2117
+ const statements = fn.body.body;
2118
+ const last = statements[statements.length - 1];
2119
+ if (!last) {
2120
+ return null;
2121
+ }
2122
+ if (last.type === "ReturnStatement") {
2123
+ if (!last.argument) {
2124
+ return null;
2071
2125
  }
2072
- };
2073
- };
2126
+ return { prefixPos: last.argument.start, prefix: "await (", suffixPos: last.argument.end, suffix: ")" };
2127
+ }
2128
+ if (last.type === "ExpressionStatement" && (last.expression.type === "CallExpression" || last.expression.type === "AwaitExpression")) {
2129
+ return { prefixPos: last.expression.start, prefix: "return await (", suffixPos: last.expression.end, suffix: ")" };
2130
+ }
2131
+ return null;
2132
+ }
2074
2133
 
2075
2134
  // src/compiler/plugins/track-tool-calls.ts
2076
-
2077
-
2078
-
2079
-
2080
-
2081
-
2082
-
2083
-
2084
-
2085
-
2086
-
2087
-
2088
-
2089
-
2090
-
2091
-
2092
-
2093
-
2094
-
2095
-
2096
2135
  var ToolCallTrackerFnIdentifier = "__toolc__";
2097
2136
  var ToolTrackerRetIdentifier = "__ret__";
2098
- var extractLVal = (path) => {
2099
- let source = path.getSource();
2100
- if (path.isIdentifier()) {
2101
- return {
2102
- type: "single",
2103
- left: source,
2104
- evalFn: `let ${source} = arguments[0]; return { ${source} };`
2105
- };
2106
- }
2107
- if (path.isArrayPattern()) {
2108
- source = path.get("elements").map((el) => el.getSource()).join(", ");
2109
- return {
2110
- type: "array",
2111
- left: source,
2112
- evalFn: `let [${source}] = arguments[0] ?? []; return { ${source} };`
2113
- };
2114
- }
2115
- if (path.isObjectPattern()) {
2116
- return {
2117
- type: "object",
2118
- left: source,
2119
- evalFn: `let ${source} = arguments[0] ?? {}; return ${source};`
2120
- };
2121
- }
2122
- return {
2123
- type: "unsupported",
2124
- evalFn: "",
2125
- left: ""
2126
- };
2127
- };
2128
- var toolCallTrackingPlugin = (calls = /* @__PURE__ */ new Map()) => function({}) {
2137
+ function applyToolCallTracking(ctx, calls) {
2129
2138
  let callId = 0;
2130
- const skip = /* @__PURE__ */ new Set();
2131
- return {
2132
- visitor: {
2133
- Program() {
2134
- callId = 0;
2135
- skip.clear();
2136
- },
2137
- CallExpression(path) {
2138
- var _a;
2139
- if (skip.has(path.node) || path.findParent((p) => skip.has(p.node))) {
2140
- return;
2139
+ const wrappedRanges = [];
2140
+ const src = ctx.code;
2141
+ const sliceOf = (node) => src.slice(node.start, node.end);
2142
+ const extractAssignment = (lval) => {
2143
+ const source = sliceOf(lval);
2144
+ if (lval.type === "Identifier") {
2145
+ return { type: "single", left: source, evalFn: `let ${source} = arguments[0]; return { ${source} };` };
2146
+ }
2147
+ if (lval.type === "ArrayPattern") {
2148
+ const elements = lval.elements.map((el) => el ? sliceOf(el) : "").join(", ");
2149
+ return {
2150
+ type: "array",
2151
+ left: elements,
2152
+ evalFn: `let [${elements}] = arguments[0] ?? []; return { ${elements} };`
2153
+ };
2154
+ }
2155
+ if (lval.type === "ObjectPattern") {
2156
+ return { type: "object", left: source, evalFn: `let ${source} = arguments[0] ?? {}; return ${source};` };
2157
+ }
2158
+ return { type: "unsupported", left: "", evalFn: "" };
2159
+ };
2160
+ walk(ctx.ast, (node, parent, ancestors) => {
2161
+ var _a;
2162
+ if (node.type !== "CallExpression") {
2163
+ return;
2164
+ }
2165
+ if (wrappedRanges.some(([start2, end2]) => node.start >= start2 && node.end <= end2)) {
2166
+ return;
2167
+ }
2168
+ if ((parent == null ? void 0 : parent.type) === "YieldExpression") {
2169
+ return;
2170
+ }
2171
+ const declaration = [...ancestors].reverse().find((n) => n.type === "VariableDeclaration");
2172
+ const assignment = [...ancestors].reverse().find((n) => n.type === "AssignmentExpression");
2173
+ let lval = null;
2174
+ if (declaration) {
2175
+ lval = _nullishCoalesce(((_a = declaration.declarations[0]) == null ? void 0 : _a.id), () => ( null));
2176
+ }
2177
+ if (assignment) {
2178
+ lval = assignment.left;
2179
+ }
2180
+ const isAsync = (parent == null ? void 0 : parent.type) === "AwaitExpression";
2181
+ const start = (id) => `${ToolCallTrackerFnIdentifier}(${id}, "start");`;
2182
+ const end = (id, value) => `${ToolCallTrackerFnIdentifier}(${id}, "end", ${value});`;
2183
+ const prefix = (id) => `(${isAsync ? "async " : ""}() => {try {${start(id)}const ${ToolTrackerRetIdentifier} = ${isAsync ? "await " : ""}`;
2184
+ const successSuffix = (id) => `;${end(id, ToolTrackerRetIdentifier)}return ${ToolTrackerRetIdentifier};}`;
2185
+ if (!lval) {
2186
+ if (!sliceOf(node).trim().length) {
2187
+ return;
2188
+ }
2189
+ const catchClause2 = ` catch (err) {${end(callId, "err")}const __newError = new Error(err.message);__newError.stack = err.stack + ("\\n" + __newError.stack);throw __newError;}})()`;
2190
+ ctx.ms.appendLeft(node.start, prefix(callId));
2191
+ ctx.ms.appendRight(node.end, successSuffix(callId) + catchClause2);
2192
+ wrappedRanges.push([node.start, node.end]);
2193
+ callId++;
2194
+ return;
2195
+ }
2196
+ const assign = extractAssignment(lval);
2197
+ if (assign.type === "unsupported") {
2198
+ return;
2199
+ }
2200
+ const tryId = callId;
2201
+ callId++;
2202
+ const callee = node.callee;
2203
+ let object = "global";
2204
+ let tool = callee.type === "Identifier" ? callee.name : sliceOf(callee);
2205
+ if (callee.type === "MemberExpression") {
2206
+ object = sliceOf(callee.object);
2207
+ const property = callee.property;
2208
+ tool = property.type === "Identifier" ? property.name : property.type === "Literal" ? String(property.value) : sliceOf(property);
2209
+ }
2210
+ const catchClause = ` catch (err) {${end(callId, "err")}throw new Error(err.message);}})()`;
2211
+ ctx.ms.appendLeft(node.start, prefix(tryId));
2212
+ ctx.ms.appendRight(node.end, successSuffix(tryId) + catchClause);
2213
+ wrappedRanges.push([node.start, node.end]);
2214
+ calls.set(callId, { object, tool, assignment: assign });
2215
+ });
2216
+ return wrappedRanges;
2217
+ }
2218
+
2219
+ // src/compiler/plugins/variable-extraction.ts
2220
+ var VariableTrackingFnIdentifier = "__var__";
2221
+ function applyVariableTracking(ctx, variables) {
2222
+ const trackerFor = (name) => {
2223
+ if (name.startsWith("__")) {
2224
+ return null;
2225
+ }
2226
+ variables.add(name);
2227
+ return `${VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => eval(${JSON.stringify(name)}));`;
2228
+ };
2229
+ const track = (names) => names.map(trackerFor).filter((t) => !!t).join("");
2230
+ const declaredNames = (id) => {
2231
+ if (id.type === "Identifier") {
2232
+ return [id.name];
2233
+ }
2234
+ if (id.type === "ObjectPattern") {
2235
+ const names = [];
2236
+ for (const prop of id.properties) {
2237
+ if (prop.type !== "Property") {
2238
+ continue;
2141
2239
  }
2142
- if (path.parentPath.isYieldExpression()) {
2143
- return;
2240
+ if (prop.value.type === "Identifier") {
2241
+ names.push(prop.value.name);
2242
+ } else if (prop.value.type === "ObjectPattern") {
2243
+ names.push(...declaredNames(prop.value));
2244
+ } else if (prop.value.type === "AssignmentPattern" && prop.value.left.type === "Identifier") {
2245
+ names.push(prop.value.left.name);
2144
2246
  }
2145
- let lval = null;
2146
- const declaration = path.findParent(
2147
- (p) => p.isVariableDeclaration()
2148
- );
2149
- const assignment = path.findParent(
2150
- (p) => p.isAssignmentExpression()
2151
- );
2152
- if (declaration) {
2153
- lval = (_a = declaration.get("declarations")[0]) == null ? void 0 : _a.get("id");
2247
+ }
2248
+ return names;
2249
+ }
2250
+ if (id.type === "ArrayPattern") {
2251
+ const names = [];
2252
+ for (const element of id.elements) {
2253
+ if (!element) {
2254
+ continue;
2154
2255
  }
2155
- if (assignment) {
2156
- const left = assignment.get("left");
2157
- if (left.isLVal()) {
2158
- lval = left;
2159
- }
2256
+ if (element.type === "Identifier") {
2257
+ names.push(element.name);
2258
+ } else if (element.type === "RestElement" && element.argument.type === "Identifier") {
2259
+ names.push(element.argument.name);
2260
+ } else if (element.type === "AssignmentPattern" && element.left.type === "Identifier") {
2261
+ names.push(element.left.name);
2160
2262
  }
2161
- const endStatement = (value) => _types.expressionStatement.call(void 0,
2162
- _types.callExpression.call(void 0, _types.identifier.call(void 0, ToolCallTrackerFnIdentifier), [
2163
- _types.numericLiteral.call(void 0, callId),
2164
- _types.stringLiteral.call(void 0, "end"),
2165
- value
2166
- ])
2167
- );
2168
- const isAsync = path.parentPath.isAwaitExpression();
2169
- const tryBodyStatement = _types.blockStatement.call(void 0, [
2170
- _types.expressionStatement.call(void 0,
2171
- _types.callExpression.call(void 0, _types.identifier.call(void 0, ToolCallTrackerFnIdentifier), [_types.numericLiteral.call(void 0, callId), _types.stringLiteral.call(void 0, "start")])
2172
- ),
2173
- _types.variableDeclaration.call(void 0, "const", [
2174
- _types.variableDeclarator.call(void 0,
2175
- _types.identifier.call(void 0, ToolTrackerRetIdentifier),
2176
- isAsync ? _types.awaitExpression.call(void 0, path.node) : path.node
2177
- )
2178
- ]),
2179
- endStatement(_types.identifier.call(void 0, ToolTrackerRetIdentifier)),
2180
- _types.returnStatement.call(void 0, _types.identifier.call(void 0, ToolTrackerRetIdentifier))
2181
- ]);
2182
- if (!lval) {
2183
- if (path.getSource().trim().length) {
2184
- const newError = _types.identifier.call(void 0, "__newError");
2185
- const newCall2 = _types.callExpression.call(void 0,
2186
- _types.arrowFunctionExpression.call(void 0,
2187
- [],
2188
- // params
2189
- _types.blockStatement.call(void 0, [
2190
- _types.tryStatement.call(void 0,
2191
- tryBodyStatement,
2192
- _types.catchClause.call(void 0,
2193
- _types.identifier.call(void 0, "err"),
2194
- _types.blockStatement.call(void 0, [
2195
- endStatement(_types.identifier.call(void 0, "err")),
2196
- _types.variableDeclaration.call(void 0, "const", [
2197
- _types.variableDeclarator.call(void 0,
2198
- newError,
2199
- _types.newExpression.call(void 0, _types.identifier.call(void 0, "Error"), [
2200
- _types.memberExpression.call(void 0, _types.identifier.call(void 0, "err"), _types.identifier.call(void 0, "message"))
2201
- ])
2202
- )
2203
- ]),
2204
- _types.expressionStatement.call(void 0,
2205
- _types.assignmentExpression.call(void 0,
2206
- "=",
2207
- _types.memberExpression.call(void 0, newError, _types.identifier.call(void 0, "stack")),
2208
- _types.binaryExpression.call(void 0,
2209
- "+",
2210
- _types.memberExpression.call(void 0, _types.identifier.call(void 0, "err"), _types.identifier.call(void 0, "stack")),
2211
- _types.binaryExpression.call(void 0,
2212
- "+",
2213
- _types.stringLiteral.call(void 0, "\n"),
2214
- _types.memberExpression.call(void 0, newError, _types.identifier.call(void 0, "stack"))
2215
- )
2216
- )
2217
- )
2218
- ),
2219
- _types.throwStatement.call(void 0, newError)
2220
- ])
2221
- )
2222
- )
2223
- ]),
2224
- isAsync
2225
- ),
2226
- []
2227
- // args
2228
- );
2229
- callId++;
2230
- skip.add(newCall2);
2231
- path.replaceWith(newCall2);
2263
+ }
2264
+ return names;
2265
+ }
2266
+ return [];
2267
+ };
2268
+ const paramNames = (params) => {
2269
+ const names = [];
2270
+ for (const param of params) {
2271
+ if (param.type === "Identifier") {
2272
+ names.push(param.name);
2273
+ } else if (param.type === "AssignmentPattern" && param.left.type === "Identifier") {
2274
+ names.push(param.left.name);
2275
+ } else if (param.type === "ObjectPattern") {
2276
+ for (const prop of param.properties) {
2277
+ if (prop.type === "Property" && prop.value.type === "Identifier") {
2278
+ names.push(prop.value.name);
2232
2279
  }
2233
- return;
2234
2280
  }
2235
- callId++;
2236
- const parts = path.get("callee").getSource().split(".");
2237
- const object = parts.length === 1 ? "global" : parts[0];
2238
- const tool = parts.length === 1 ? parts[0] : parts[1];
2239
- const assign = extractLVal(lval);
2240
- if (assign.type === "unsupported") {
2241
- return;
2281
+ } else if (param.type === "ArrayPattern") {
2282
+ for (const element of param.elements) {
2283
+ if ((element == null ? void 0 : element.type) === "Identifier") {
2284
+ names.push(element.name);
2285
+ }
2242
2286
  }
2243
- const newCall = _types.callExpression.call(void 0,
2244
- _types.arrowFunctionExpression.call(void 0,
2245
- [],
2246
- // params
2247
- _types.blockStatement.call(void 0, [
2248
- _types.tryStatement.call(void 0,
2249
- tryBodyStatement,
2250
- _types.catchClause.call(void 0,
2251
- _types.identifier.call(void 0, "err"),
2252
- _types.blockStatement.call(void 0, [
2253
- endStatement(_types.identifier.call(void 0, "err")),
2254
- _types.throwStatement.call(void 0,
2255
- _types.newExpression.call(void 0, _types.identifier.call(void 0, "Error"), [_types.memberExpression.call(void 0, _types.identifier.call(void 0, "err"), _types.identifier.call(void 0, "message"))])
2256
- )
2257
- ])
2258
- )
2259
- )
2260
- ]),
2261
- isAsync
2262
- ),
2263
- []
2264
- // args
2265
- );
2266
- calls.set(callId, { object, tool, assignment: assign });
2267
- skip.add(newCall);
2268
- path.replaceWith(newCall);
2269
2287
  }
2270
2288
  }
2289
+ return names;
2271
2290
  };
2272
- };
2273
-
2274
- // src/compiler/plugins/variable-extraction.ts
2275
-
2276
-
2277
-
2278
-
2279
-
2280
-
2281
-
2282
-
2283
-
2284
- var VariableTrackingFnIdentifier = "__var__";
2285
- var variableTrackingPlugin = (variables = /* @__PURE__ */ new Set()) => function({ types: t }) {
2286
- let trackingStatements = [];
2287
- const trackVariable = (variableName) => {
2288
- if (variableName.startsWith("__")) {
2291
+ walk(ctx.ast, (node, parent) => {
2292
+ if (node.type === "VariableDeclaration") {
2293
+ if (parent && (parent.type === "ForStatement" || parent.type === "ForInStatement" || parent.type === "ForOfStatement")) {
2294
+ return;
2295
+ }
2296
+ const trackers = track(node.declarations.flatMap((d) => declaredNames(d.id)));
2297
+ if (trackers) {
2298
+ const semi = ctx.code[node.end - 1] === ";" ? "" : ";";
2299
+ ctx.ms.appendRight(node.end, `${semi}${trackers}`);
2300
+ }
2289
2301
  return;
2290
2302
  }
2291
- variables.add(variableName);
2292
- trackingStatements.push(
2293
- _types.expressionStatement.call(void 0,
2294
- _types.callExpression.call(void 0, _types.identifier.call(void 0, VariableTrackingFnIdentifier), [
2295
- _types.stringLiteral.call(void 0, variableName),
2296
- _types.arrowFunctionExpression.call(void 0, [], _types.callExpression.call(void 0, _types.identifier.call(void 0, "eval"), [_types.stringLiteral.call(void 0, variableName)]))
2297
- ])
2298
- )
2299
- );
2300
- };
2301
- return {
2302
- visitor: {
2303
- FunctionDeclaration(path) {
2304
- path.node.params.forEach((param) => {
2305
- if (t.isIdentifier(param)) {
2306
- trackVariable(param.name);
2307
- } else if (t.isAssignmentPattern(param) && t.isIdentifier(param.left)) {
2308
- trackVariable(param.left.name);
2309
- } else if (t.isObjectPattern(param)) {
2310
- param.properties.forEach((prop) => {
2311
- if (t.isObjectProperty(prop) && t.isIdentifier(prop.value)) {
2312
- trackVariable(prop.value.name);
2313
- }
2314
- });
2315
- } else if (t.isArrayPattern(param)) {
2316
- param.elements.forEach((element) => {
2317
- if (t.isIdentifier(element)) {
2318
- trackVariable(element.name);
2319
- }
2320
- });
2321
- }
2322
- });
2323
- if (trackingStatements.length) {
2324
- path.get("body").unshiftContainer("body", trackingStatements);
2325
- trackingStatements = [];
2326
- }
2327
- },
2328
- ArrowFunctionExpression(path) {
2329
- path.node.params.forEach((param) => {
2330
- if (t.isIdentifier(param)) {
2331
- trackVariable(param.name);
2332
- } else if (t.isAssignmentPattern(param) && t.isIdentifier(param.left)) {
2333
- trackVariable(param.left.name);
2334
- } else if (t.isObjectPattern(param)) {
2335
- param.properties.forEach((prop) => {
2336
- if (t.isObjectProperty(prop) && t.isIdentifier(prop.value)) {
2337
- trackVariable(prop.value.name);
2338
- }
2339
- });
2340
- } else if (t.isArrayPattern(param)) {
2341
- param.elements.forEach((element) => {
2342
- if (t.isIdentifier(element)) {
2343
- trackVariable(element.name);
2344
- }
2345
- });
2346
- }
2347
- });
2348
- if (trackingStatements.length) {
2349
- const body = path.get("body");
2350
- if (body.isBlockStatement()) {
2351
- body.unshiftContainer("body", trackingStatements);
2352
- } else if (body.isExpression() && body.getSource().trim().length) {
2353
- const newBody = _types.blockStatement.call(void 0, [...trackingStatements, _types.returnStatement.call(void 0, body.node)]);
2354
- path.get("body").replaceWith(newBody);
2355
- }
2356
- trackingStatements = [];
2357
- }
2358
- },
2359
- VariableDeclaration(path) {
2360
- const parent = path.parentPath;
2361
- const handleObjectPattern = (pattern) => {
2362
- pattern.properties.forEach((prop) => {
2363
- if (t.isObjectProperty(prop) && t.isIdentifier(prop.value)) {
2364
- trackVariable(prop.value.name);
2365
- } else if (t.isObjectProperty(prop) && t.isObjectPattern(prop.value)) {
2366
- handleObjectPattern(prop.value);
2367
- } else if (t.isObjectProperty(prop) && t.isAssignmentPattern(prop.value) && t.isIdentifier(prop.value.left)) {
2368
- trackVariable(prop.value.left.name);
2369
- }
2370
- });
2371
- };
2372
- path.node.declarations.forEach((declarator) => {
2373
- if (parent.isForXStatement() || parent.isForStatement()) {
2374
- return;
2375
- }
2376
- if (t.isIdentifier(declarator.id)) {
2377
- trackVariable(declarator.id.name);
2378
- }
2379
- if (t.isObjectPattern(declarator.id)) {
2380
- handleObjectPattern(declarator.id);
2381
- }
2382
- if (t.isArrayPattern(declarator.id)) {
2383
- declarator.id.elements.forEach((element) => {
2384
- if (t.isIdentifier(element)) {
2385
- trackVariable(element.name);
2386
- } else if (t.isRestElement(element) && t.isIdentifier(element.argument)) {
2387
- trackVariable(element.argument.name);
2388
- } else if (t.isAssignmentPattern(element) && t.isIdentifier(element.left)) {
2389
- trackVariable(element.left.name);
2390
- }
2391
- });
2392
- }
2393
- });
2394
- if (trackingStatements.length) {
2395
- path.insertAfter(trackingStatements);
2396
- trackingStatements = [];
2397
- }
2303
+ if (node.type === "FunctionDeclaration" || node.type === "ArrowFunctionExpression") {
2304
+ const trackers = track(paramNames(node.params));
2305
+ if (!trackers) {
2306
+ return;
2307
+ }
2308
+ const body = node.body;
2309
+ if (body.type === "BlockStatement") {
2310
+ ctx.ms.appendRight(body.start + 1, trackers);
2311
+ } else {
2312
+ ctx.ms.appendLeft(body.start, `{${trackers}return (`);
2313
+ ctx.ms.appendRight(body.end, ");}");
2398
2314
  }
2399
2315
  }
2400
- };
2401
- };
2316
+ });
2317
+ }
2402
2318
 
2403
2319
  // src/compiler/compiler.ts
2404
- var DEFAULT_TRANSFORM_OPTIONS = {
2405
- parserOpts: {
2406
- allowReturnOutsideFunction: true,
2407
- allowAwaitOutsideFunction: true,
2408
- strictMode: true,
2409
- startLine: 1
2410
- },
2411
- sourceFileName: "<anonymous>",
2412
- sourceMaps: true,
2413
- minified: false,
2414
- retainLines: true
2415
- };
2416
2320
  var Identifiers = {
2417
2321
  ConsoleObjIdentifier: "console",
2418
2322
  LineTrackingFnIdentifier,
@@ -2421,71 +2325,52 @@ var Identifiers = {
2421
2325
  ToolTrackerRetIdentifier,
2422
2326
  CommentFnIdentifier
2423
2327
  };
2328
+ var FUNCTION_TYPES = /* @__PURE__ */ new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
2424
2329
  function hasTopLevelReturn(code) {
2425
- let found = false;
2426
- const detectTopLevelReturnPlugin = () => ({
2427
- visitor: {
2428
- ReturnStatement(path) {
2429
- if (!path.getFunctionParent()) {
2430
- found = true;
2431
- }
2432
- }
2433
- }
2434
- });
2435
2330
  try {
2436
- Babel.transform(code, {
2437
- parserOpts: {
2438
- allowReturnOutsideFunction: true,
2439
- allowAwaitOutsideFunction: true
2440
- },
2441
- presets: ["typescript"],
2442
- plugins: [detectTopLevelReturnPlugin],
2443
- filename: "<anonymous>.ts",
2444
- code: false
2331
+ const ast = parseScript(code);
2332
+ let found = false;
2333
+ walk(ast, (node, _parent, ancestors) => {
2334
+ if (node.type === "ReturnStatement" && !ancestors.some((a) => FUNCTION_TYPES.has(a.type))) {
2335
+ found = true;
2336
+ }
2445
2337
  });
2446
- } catch (e2) {
2338
+ return found;
2339
+ } catch (e) {
2447
2340
  return /\breturn\b/.test(code);
2448
2341
  }
2449
- return found;
2450
2342
  }
2451
2343
  function compile(code) {
2452
- code = AsyncWrapper.preProcessing(code);
2453
- let output = Babel.transform(code, {
2454
- parserOpts: {
2455
- allowReturnOutsideFunction: true,
2456
- allowAwaitOutsideFunction: true
2457
- },
2458
- presets: ["typescript"],
2459
- plugins: [instrumentLastLinePlugin],
2460
- filename: "<anonymous>.ts",
2461
- sourceFileName: "<anonymous>",
2462
- sourceMaps: true,
2463
- minified: false,
2464
- retainLines: true
2465
- });
2344
+ const wrapped = AsyncWrapper.preProcessing(code);
2345
+ const comments = [];
2346
+ const ast = parseScript(wrapped, { comments });
2466
2347
  const variables = /* @__PURE__ */ new Set();
2467
2348
  const toolCalls = /* @__PURE__ */ new Map();
2468
- const codeWithMarkers = output.code;
2469
- output = Babel.transform(output.code, {
2470
- ...DEFAULT_TRANSFORM_OPTIONS,
2471
- parserOpts: {
2472
- ...DEFAULT_TRANSFORM_OPTIONS.parserOpts
2473
- },
2474
- plugins: [
2475
- lineTrackingBabelPlugin,
2476
- replaceCommentBabelPlugin,
2477
- variableTrackingPlugin(variables),
2478
- toolCallTrackingPlugin(toolCalls)
2479
- ],
2480
- retainLines: true
2481
- });
2482
- let outputCode = output.code;
2483
- outputCode = AsyncWrapper.postProcessing(outputCode);
2349
+ const lastLine = planLastLineInstrumentation(ast);
2350
+ const msMarkers = new (0, _magicstring2.default)(wrapped);
2351
+ if (lastLine) {
2352
+ msMarkers.appendLeft(lastLine.prefixPos, lastLine.prefix);
2353
+ msMarkers.appendRight(lastLine.suffixPos, lastLine.suffix);
2354
+ }
2355
+ const codeWithMarkers = msMarkers.toString();
2356
+ const ms = new (0, _magicstring2.default)(wrapped);
2357
+ const ctx = { code: wrapped, ms, ast, comments };
2358
+ applyLineTracking(ctx);
2359
+ if (lastLine) {
2360
+ ms.appendLeft(lastLine.prefixPos, lastLine.prefix);
2361
+ }
2362
+ const wrappedRanges = applyToolCallTracking(ctx, toolCalls);
2363
+ applyCommentReplacement(ctx, wrappedRanges);
2364
+ applyVariableTracking(ctx, variables);
2365
+ if (lastLine) {
2366
+ ms.appendRight(lastLine.suffixPos, lastLine.suffix);
2367
+ }
2368
+ const outputCode = AsyncWrapper.postProcessing(ms.toString());
2369
+ const map = ms.generateMap({ hires: true, source: "<anonymous>" });
2484
2370
  return {
2485
2371
  code: outputCode,
2486
2372
  codeWithMarkers,
2487
- // Code from before second transform, still has literal markers
2488
- map: output.map,
2373
+ map,
2489
2374
  variables,
2490
2375
  toolCalls
2491
2376
  };
@@ -2539,12 +2424,18 @@ var handleErrorNode = (err, code, consumer, traces, variables, _lines_executed,
2539
2424
  const stackTrace = err.stack || "";
2540
2425
  const LINE_OFFSET = 1;
2541
2426
  const regex = /<anonymous>:(\d+):(\d+)/g;
2427
+ const ASYNC_FUNCTION_HEADER_LINES = 2;
2428
+ const SLICED_WRAPPER_LINES = 2;
2429
+ const KEPT_BLANK_LINES = 1;
2430
+ const RUNTIME_TO_MAP_OFFSET = SLICED_WRAPPER_LINES - ASYNC_FUNCTION_HEADER_LINES - KEPT_BLANK_LINES;
2431
+ const WRAPPED_HEADER_LINES = 3;
2542
2432
  const matches = [...stackTrace.matchAll(regex)].map((x) => {
2433
+ const mapLine = Number(x[1]) + RUNTIME_TO_MAP_OFFSET;
2543
2434
  const originalLine = consumer.originalPositionFor({
2544
- line: Number(x[1]),
2435
+ line: mapLine,
2545
2436
  column: Number(x[2])
2546
2437
  });
2547
- const line = _nullishCoalesce(originalLine.line, () => ( Number(x[1])));
2438
+ const line = (_nullishCoalesce(originalLine.line, () => ( mapLine))) - WRAPPED_HEADER_LINES;
2548
2439
  const actualLine = _nullishCoalesce(lines[line - LINE_OFFSET], () => ( ""));
2549
2440
  const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
2550
2441
  const minColumn = Math.max(whiteSpacesCount, originalLine.column);
@@ -2687,7 +2578,7 @@ function instrumentContext(context, transformed, traces, variables, lines_execut
2687
2578
  return "[[non-primitive]]";
2688
2579
  }
2689
2580
  return value;
2690
- } catch (e3) {
2581
+ } catch (e2) {
2691
2582
  return "[[non-primitive]]";
2692
2583
  }
2693
2584
  };
@@ -2880,9 +2771,9 @@ var QuickJSDriver = class {
2880
2771
  valueResult.unwrap().dispose();
2881
2772
  try {
2882
2773
  context[key] = vmValue;
2883
- } catch (e4) {
2774
+ } catch (e3) {
2884
2775
  }
2885
- } catch (e5) {
2776
+ } catch (e4) {
2886
2777
  }
2887
2778
  }
2888
2779
  };
@@ -2909,7 +2800,7 @@ var QuickJSDriver = class {
2909
2800
  if (errorValue !== null && errorValue !== "") {
2910
2801
  try {
2911
2802
  copyBackContextFromVM();
2912
- } catch (e6) {
2803
+ } catch (e5) {
2913
2804
  }
2914
2805
  const errorStackResult = vm.evalCode("globalThis.__llmz_error_stack");
2915
2806
  const errorStack = vm.dump(errorStackResult.unwrap()) || "";
@@ -2985,11 +2876,11 @@ var QuickJSDriver = class {
2985
2876
  } finally {
2986
2877
  try {
2987
2878
  vm.dispose();
2988
- } catch (e7) {
2879
+ } catch (e6) {
2989
2880
  }
2990
2881
  try {
2991
2882
  runtime.dispose();
2992
- } catch (e8) {
2883
+ } catch (e7) {
2993
2884
  }
2994
2885
  }
2995
2886
  }
@@ -3226,7 +3117,7 @@ function setupVariableTrackingBridge(vm, variables) {
3226
3117
  } else {
3227
3118
  variables[name] = value;
3228
3119
  }
3229
- } catch (e9) {
3120
+ } catch (e8) {
3230
3121
  variables[name] = "[[non-primitive]]";
3231
3122
  }
3232
3123
  }
@@ -3290,10 +3181,9 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
3290
3181
  version: transformed.map.version.toString(),
3291
3182
  mappings: transformed.map.mappings,
3292
3183
  names: transformed.map.names,
3293
- sources: [transformed.map.file],
3184
+ sources: transformed.map.sources,
3294
3185
  sourcesContent: [transformed.code],
3295
- file: transformed.map.file,
3296
- sourceRoot: transformed.map.sourceRoot
3186
+ file: transformed.map.file
3297
3187
  });
3298
3188
  context ??= {};
3299
3189
  for (const name of Array.from(transformed.variables)) {