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.
- package/dist/{_baseForOwn-buOZDFbK.cjs → _baseForOwn-BfWDTL8L.cjs} +0 -50
- package/dist/common-DdArNQhl.cjs +643 -0
- package/dist/common-pgJjFu2Y.js +596 -0
- package/dist/compiler-C-OI9sim.cjs +547 -0
- package/dist/compiler-CW1VjQsn.js +473 -0
- package/dist/{component-BwixNVH8.cjs → component-BXS8vAwO.cjs} +3 -3
- package/dist/{component-DGG7d_Mz.js → component-Dq7ZLdvy.js} +1 -1
- package/dist/component.d.ts +4 -4
- package/dist/component.default.d.ts +60 -87
- package/dist/component.default.test.d.ts +1 -0
- package/dist/context.d.ts +10 -0
- package/dist/{custom-client-CMuy7fXU.js → custom-client-2V9lmzUf.js} +119 -24
- package/dist/{custom-client-Bp1TgTKk.cjs → custom-client-HkM1Sdzv.cjs} +124 -29
- package/dist/{dual-modes-CfqTk9M8.cjs → dual-modes-Cb7ThvoV.cjs} +1268 -1062
- package/dist/{dual-modes-mNyMThtf.js → dual-modes-Cy0_W4O2.js} +1242 -1036
- package/dist/example.d.ts +45 -0
- package/dist/example.test.d.ts +1 -0
- package/dist/{execute-DP_17lYZ.js → execute-Aw4cbIx-.js} +23 -10
- package/dist/{execute-msui51b2.cjs → execute-COIHOIKR.cjs} +30 -18
- package/dist/{exit-BGi0Kk0y.cjs → exit-DUM96DN1.cjs} +3 -3
- package/dist/exit-parser.d.ts +2 -0
- package/dist/index.cjs +33 -356
- package/dist/index.d.ts +2 -0
- package/dist/index.js +13 -337
- package/dist/index.workerd.js +9981 -9388
- package/dist/{jsx-CIgdGGVs.js → jsx-B0iYyvfr.js} +50 -2
- package/dist/{jsx-BWvT6ukg.cjs → jsx-D5Y2cPo-.cjs} +58 -4
- package/dist/message-stream/parser.d.ts +3 -0
- package/dist/message-stream/types.d.ts +1 -1
- package/dist/prompts/chat-mode/system.d.ts +2 -0
- package/dist/prompts/chat-mode/user.d.ts +2 -0
- package/dist/prompts/execution-history.d.ts +6 -0
- package/dist/prompts/execution-state.d.ts +3 -0
- package/dist/prompts/prompt.d.ts +26 -0
- package/dist/prompts/protocol.test.d.ts +1 -0
- package/dist/prompts/worker-mode/system.d.ts +2 -0
- package/dist/prompts/worker-mode/user.d.ts +2 -0
- package/dist/runtime/types.d.ts +9 -0
- package/dist/{tool-ReA9gxMp.cjs → tool-Dy6AJpJH.cjs} +4 -4
- package/dist/{truncator-B6aaJaN1.cjs → truncator-CLkouTCO.cjs} +3 -3
- package/dist/{typings-BwAz_TM9.cjs → typings-3lsqCbkn.cjs} +3 -3
- package/dist/{utils-ZpJm00ed.cjs → utils-3ESwP3yg.cjs} +2 -2
- package/dist/{vm-C5vf1LH3.js → vm-BLsHw1da.js} +3 -462
- package/dist/{vm-BjkJqSQH.cjs → vm-D6s1zF6M.cjs} +28 -489
- package/package.json +2 -2
- package/dist/isPlainObject-CSxXVKCk.cjs +0 -56
- package/dist/isPlainObject-D39AzPO2.js +0 -51
|
@@ -0,0 +1,547 @@
|
|
|
1
|
+
//#region \0rolldown/runtime.js
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
|
|
9
|
+
var __exportAll = (all, no_symbols) => {
|
|
10
|
+
let target = {};
|
|
11
|
+
for (var name in all) __defProp(target, name, {
|
|
12
|
+
get: all[name],
|
|
13
|
+
enumerable: true
|
|
14
|
+
});
|
|
15
|
+
if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
16
|
+
return target;
|
|
17
|
+
};
|
|
18
|
+
var __copyProps = (to, from, except, desc) => {
|
|
19
|
+
if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
|
|
20
|
+
key = keys[i];
|
|
21
|
+
if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
|
|
22
|
+
get: ((k) => from[k]).bind(null, key),
|
|
23
|
+
enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
return to;
|
|
27
|
+
};
|
|
28
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
|
|
29
|
+
value: mod,
|
|
30
|
+
enumerable: true
|
|
31
|
+
}) : target, mod));
|
|
32
|
+
//#endregion
|
|
33
|
+
let acorn = require("acorn");
|
|
34
|
+
let magic_string = require("magic-string");
|
|
35
|
+
magic_string = __toESM(magic_string, 1);
|
|
36
|
+
//#region src/compiler/ast.ts
|
|
37
|
+
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;
|
|
38
|
+
function parseScript(code, opts) {
|
|
39
|
+
try {
|
|
40
|
+
return (0, acorn.parse)(code, {
|
|
41
|
+
ecmaVersion: "latest",
|
|
42
|
+
sourceType: "script",
|
|
43
|
+
locations: true,
|
|
44
|
+
allowReturnOutsideFunction: true,
|
|
45
|
+
allowAwaitOutsideFunction: true,
|
|
46
|
+
...opts,
|
|
47
|
+
onComment: opts === null || opts === void 0 ? void 0 : opts.comments
|
|
48
|
+
});
|
|
49
|
+
} catch (err) {
|
|
50
|
+
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).";
|
|
51
|
+
throw err;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Depth-first pre-order walk. `ancestors` is ordered outermost → innermost and
|
|
56
|
+
* excludes `node` itself; `parent` is `ancestors[ancestors.length - 1]`.
|
|
57
|
+
*/
|
|
58
|
+
function walk(root, enter) {
|
|
59
|
+
const ancestors = [];
|
|
60
|
+
const visit = (node) => {
|
|
61
|
+
enter(node, ancestors[ancestors.length - 1] ?? null, ancestors);
|
|
62
|
+
ancestors.push(node);
|
|
63
|
+
for (const key of Object.keys(node)) {
|
|
64
|
+
if (key === "loc") continue;
|
|
65
|
+
const value = node[key];
|
|
66
|
+
if (Array.isArray(value)) {
|
|
67
|
+
for (const child of value) if (isNode(child)) visit(child);
|
|
68
|
+
} else if (isNode(value)) visit(value);
|
|
69
|
+
}
|
|
70
|
+
ancestors.pop();
|
|
71
|
+
};
|
|
72
|
+
visit(root);
|
|
73
|
+
}
|
|
74
|
+
const isNode = (value) => !!value && typeof value === "object" && typeof value.type === "string";
|
|
75
|
+
const isStatementContainer = (node) => !!node && (node.type === "Program" || node.type === "BlockStatement" || node.type === "StaticBlock");
|
|
76
|
+
/**
|
|
77
|
+
* The statement that contains `node`: the outermost ancestor (or the node
|
|
78
|
+
* itself) whose parent is a statement container.
|
|
79
|
+
*/
|
|
80
|
+
function enclosingStatement(node, ancestors) {
|
|
81
|
+
const chain = [...ancestors, node];
|
|
82
|
+
for (let i = chain.length - 1; i > 0; i--) if (isStatementContainer(chain[i - 1])) return chain[i];
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
/** The innermost node whose range contains [start, end] */
|
|
86
|
+
function innermostContaining(ast, start, end) {
|
|
87
|
+
let best = null;
|
|
88
|
+
walk(ast, (node) => {
|
|
89
|
+
if (node.start <= start && node.end >= end) {
|
|
90
|
+
if (!best || node.start >= best.start && node.end <= best.end) best = node;
|
|
91
|
+
}
|
|
92
|
+
});
|
|
93
|
+
return best;
|
|
94
|
+
}
|
|
95
|
+
//#endregion
|
|
96
|
+
//#region src/compiler/plugins/async-wrapper.ts
|
|
97
|
+
const Open = "async function __fn__() {";
|
|
98
|
+
const Close = "}";
|
|
99
|
+
const USER_CODE_START_MARKER = "/* __LLMZ_USER_CODE_START__ */";
|
|
100
|
+
const USER_CODE_END_MARKER = "/* __LLMZ_USER_CODE_END__ */";
|
|
101
|
+
/**
|
|
102
|
+
* Wraps user code in an async function so top-level `await` and `return` parse,
|
|
103
|
+
* and so plugins can target the `__fn__` declaration. The wrapper is removed
|
|
104
|
+
* after transformation — drivers re-wrap the bare statements themselves.
|
|
105
|
+
*/
|
|
106
|
+
const AsyncWrapper = {
|
|
107
|
+
preProcessing: (code) => {
|
|
108
|
+
return `"use strict";
|
|
109
|
+
${Open}
|
|
110
|
+
${USER_CODE_START_MARKER}
|
|
111
|
+
${code}
|
|
112
|
+
${USER_CODE_END_MARKER}
|
|
113
|
+
${Close}
|
|
114
|
+
`.trim();
|
|
115
|
+
},
|
|
116
|
+
postProcessing: (code) => {
|
|
117
|
+
code = code.slice(code.indexOf(Open) + 25);
|
|
118
|
+
code = code.slice(0, code.lastIndexOf(Close));
|
|
119
|
+
code = code.replace(USER_CODE_START_MARKER, "").replace(USER_CODE_END_MARKER, "");
|
|
120
|
+
return code.trimEnd();
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
//#endregion
|
|
124
|
+
//#region src/compiler/plugins/line-tracking.ts
|
|
125
|
+
const LineTrackingFnIdentifier = "__track__";
|
|
126
|
+
const TRACKED_TYPES = /* @__PURE__ */ new Set([
|
|
127
|
+
"FunctionDeclaration",
|
|
128
|
+
"MethodDefinition",
|
|
129
|
+
"ReturnStatement",
|
|
130
|
+
"AwaitExpression",
|
|
131
|
+
"ForOfStatement",
|
|
132
|
+
"CallExpression",
|
|
133
|
+
"UnaryExpression",
|
|
134
|
+
"VariableDeclaration",
|
|
135
|
+
"AssignmentExpression"
|
|
136
|
+
]);
|
|
137
|
+
const SKIPPED_PARENT_TYPES = /* @__PURE__ */ new Set([
|
|
138
|
+
"ArrowFunctionExpression",
|
|
139
|
+
"Property",
|
|
140
|
+
"AwaitExpression",
|
|
141
|
+
"UnaryExpression",
|
|
142
|
+
"ReturnStatement",
|
|
143
|
+
"ForOfStatement",
|
|
144
|
+
"ForStatement",
|
|
145
|
+
"ForInStatement",
|
|
146
|
+
"VariableDeclaration",
|
|
147
|
+
"BinaryExpression",
|
|
148
|
+
"LogicalExpression"
|
|
149
|
+
]);
|
|
150
|
+
/**
|
|
151
|
+
* Inserts a `__track__(<line>)` call before the statement containing each
|
|
152
|
+
* tracked node — at most one per source line.
|
|
153
|
+
*/
|
|
154
|
+
function applyLineTracking(ctx) {
|
|
155
|
+
const trackedLines = /* @__PURE__ */ new Set();
|
|
156
|
+
walk(ctx.ast, (node, parent, ancestors) => {
|
|
157
|
+
if (!parent || !node.loc) return;
|
|
158
|
+
if (!TRACKED_TYPES.has(node.type) && parent.type !== "BlockStatement") return;
|
|
159
|
+
const line = node.loc.start.line;
|
|
160
|
+
if (trackedLines.has(line) || SKIPPED_PARENT_TYPES.has(parent.type)) return;
|
|
161
|
+
const statement = enclosingStatement(node, ancestors);
|
|
162
|
+
if (!statement) return;
|
|
163
|
+
trackedLines.add(line);
|
|
164
|
+
ctx.ms.appendLeft(statement.start, `${LineTrackingFnIdentifier}(${line});`);
|
|
165
|
+
});
|
|
166
|
+
}
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region src/compiler/plugins/replace-comment.ts
|
|
169
|
+
const CommentFnIdentifier = "__comment__";
|
|
170
|
+
const MARKER_TAGS = [USER_CODE_START_MARKER, USER_CODE_END_MARKER].map((m) => m.replace(/\/\*|\*\/|\s/g, ""));
|
|
171
|
+
/** Blanks a range, keeping newlines so line numbers are preserved */
|
|
172
|
+
const blank = (ctx, start, end) => {
|
|
173
|
+
ctx.ms.update(start, end, ctx.code.slice(start, end).replace(/[^\n]/g, " "));
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
176
|
+
* Replaces comments at statement position with `__comment__("<text>", <line>)`
|
|
177
|
+
* calls so the agent's inline "thinking" comments show up as traces at runtime.
|
|
178
|
+
* Comments inside expressions and the user-code markers are blanked; comments
|
|
179
|
+
* inside instrumented tool-call ranges are left verbatim.
|
|
180
|
+
*/
|
|
181
|
+
function applyCommentReplacement(ctx, skipRanges) {
|
|
182
|
+
for (const comment of ctx.comments) {
|
|
183
|
+
const text = comment.value.trim();
|
|
184
|
+
if (MARKER_TAGS.some((tag) => text.includes(tag))) {
|
|
185
|
+
blank(ctx, comment.start, comment.end);
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (skipRanges.some(([start, end]) => comment.start >= start && comment.end <= end)) continue;
|
|
189
|
+
const container = innermostContaining(ctx.ast, comment.start, comment.end);
|
|
190
|
+
if (isStatementContainer(container)) {
|
|
191
|
+
const newlines = ctx.code.slice(comment.start, comment.end).replace(/[^\n]/g, "");
|
|
192
|
+
ctx.ms.update(comment.start, comment.end, `;${CommentFnIdentifier}(${JSON.stringify(text)}, ${comment.loc.start.line});${newlines}`);
|
|
193
|
+
} else blank(ctx, comment.start, comment.end);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
//#endregion
|
|
197
|
+
//#region src/compiler/plugins/return-async.ts
|
|
198
|
+
/**
|
|
199
|
+
* Plans the instrumentation of the last statement of the `__fn__` wrapper so
|
|
200
|
+
* the generated code always returns an awaited value (the isolated VM cannot
|
|
201
|
+
* return a pending Promise):
|
|
202
|
+
* - `return expr` → `return await (expr)`
|
|
203
|
+
* - a trailing `call()` / `await call()` statement → `return await (…)`
|
|
204
|
+
*
|
|
205
|
+
* The prefix must be applied before, and the suffix after, all other edits so
|
|
206
|
+
* they wrap around the tool-call instrumentation.
|
|
207
|
+
*/
|
|
208
|
+
function planLastLineInstrumentation(ast) {
|
|
209
|
+
const fn = ast.body.find((node) => {
|
|
210
|
+
var _id;
|
|
211
|
+
return node.type === "FunctionDeclaration" && ((_id = node.id) === null || _id === void 0 ? void 0 : _id.name) === "__fn__";
|
|
212
|
+
});
|
|
213
|
+
if (!fn) return null;
|
|
214
|
+
const statements = fn.body.body;
|
|
215
|
+
const last = statements[statements.length - 1];
|
|
216
|
+
if (!last) return null;
|
|
217
|
+
if (last.type === "ReturnStatement") {
|
|
218
|
+
if (!last.argument) return null;
|
|
219
|
+
return {
|
|
220
|
+
prefixPos: last.argument.start,
|
|
221
|
+
prefix: "await (",
|
|
222
|
+
suffixPos: last.argument.end,
|
|
223
|
+
suffix: ")"
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
if (last.type === "ExpressionStatement" && (last.expression.type === "CallExpression" || last.expression.type === "AwaitExpression")) return {
|
|
227
|
+
prefixPos: last.expression.start,
|
|
228
|
+
prefix: "return await (",
|
|
229
|
+
suffixPos: last.expression.end,
|
|
230
|
+
suffix: ")"
|
|
231
|
+
};
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
//#endregion
|
|
235
|
+
//#region src/compiler/plugins/track-tool-calls.ts
|
|
236
|
+
const ToolCallTrackerFnIdentifier = "__toolc__";
|
|
237
|
+
const ToolTrackerRetIdentifier = "__ret__";
|
|
238
|
+
/**
|
|
239
|
+
* Wraps every outermost call expression in an IIFE that reports
|
|
240
|
+
* `__toolc__(<id>, "start" | "end", …)` events around the call:
|
|
241
|
+
*
|
|
242
|
+
* const x = (() => {
|
|
243
|
+
* try {
|
|
244
|
+
* __toolc__(0, "start");
|
|
245
|
+
* const __ret__ = tool();
|
|
246
|
+
* __toolc__(0, "end", __ret__);
|
|
247
|
+
* return __ret__;
|
|
248
|
+
* } catch (err) { __toolc__(1, "end", err); throw new Error(err.message); }
|
|
249
|
+
* })()
|
|
250
|
+
*
|
|
251
|
+
* Calls assigned to a variable are registered in `calls` (keyed by the id used
|
|
252
|
+
* in the catch clause — the id the runtime sees when a tool throws a
|
|
253
|
+
* SnapshotSignal). Awaited calls get an async IIFE that awaits the call.
|
|
254
|
+
*
|
|
255
|
+
* Returns the wrapped source ranges so later passes can avoid editing inside.
|
|
256
|
+
*/
|
|
257
|
+
function applyToolCallTracking(ctx, calls) {
|
|
258
|
+
let callId = 0;
|
|
259
|
+
const wrappedRanges = [];
|
|
260
|
+
const src = ctx.code;
|
|
261
|
+
const sliceOf = (node) => src.slice(node.start, node.end);
|
|
262
|
+
const extractAssignment = (lval) => {
|
|
263
|
+
const source = sliceOf(lval);
|
|
264
|
+
if (lval.type === "Identifier") return {
|
|
265
|
+
type: "single",
|
|
266
|
+
left: source,
|
|
267
|
+
evalFn: `let ${source} = arguments[0]; return { ${source} };`
|
|
268
|
+
};
|
|
269
|
+
if (lval.type === "ArrayPattern") {
|
|
270
|
+
const elements = lval.elements.map((el) => el ? sliceOf(el) : "").join(", ");
|
|
271
|
+
return {
|
|
272
|
+
type: "array",
|
|
273
|
+
left: elements,
|
|
274
|
+
evalFn: `let [${elements}] = arguments[0] ?? []; return { ${elements} };`
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
if (lval.type === "ObjectPattern") return {
|
|
278
|
+
type: "object",
|
|
279
|
+
left: source,
|
|
280
|
+
evalFn: `let ${source} = arguments[0] ?? {}; return ${source};`
|
|
281
|
+
};
|
|
282
|
+
return {
|
|
283
|
+
type: "unsupported",
|
|
284
|
+
left: "",
|
|
285
|
+
evalFn: ""
|
|
286
|
+
};
|
|
287
|
+
};
|
|
288
|
+
walk(ctx.ast, (node, parent, ancestors) => {
|
|
289
|
+
if (node.type !== "CallExpression") return;
|
|
290
|
+
if (wrappedRanges.some(([start, end]) => node.start >= start && node.end <= end)) return;
|
|
291
|
+
if ((parent === null || parent === void 0 ? void 0 : parent.type) === "YieldExpression") return;
|
|
292
|
+
if ((parent === null || parent === void 0 ? void 0 : parent.type) !== "AwaitExpression") {
|
|
293
|
+
let containsAwait = false;
|
|
294
|
+
walk(node, (child, _parent, ancestors) => {
|
|
295
|
+
if (child.type === "AwaitExpression" && !ancestors.some((ancestor) => [
|
|
296
|
+
"FunctionDeclaration",
|
|
297
|
+
"FunctionExpression",
|
|
298
|
+
"ArrowFunctionExpression"
|
|
299
|
+
].includes(ancestor.type))) containsAwait = true;
|
|
300
|
+
});
|
|
301
|
+
if (containsAwait) return;
|
|
302
|
+
}
|
|
303
|
+
const declaration = [...ancestors].reverse().find((n) => n.type === "VariableDeclaration");
|
|
304
|
+
const assignment = [...ancestors].reverse().find((n) => n.type === "AssignmentExpression");
|
|
305
|
+
let lval = null;
|
|
306
|
+
if (declaration) {
|
|
307
|
+
var _;
|
|
308
|
+
lval = ((_ = declaration.declarations[0]) === null || _ === void 0 ? void 0 : _.id) ?? null;
|
|
309
|
+
}
|
|
310
|
+
if (assignment) lval = assignment.left;
|
|
311
|
+
const isAsync = (parent === null || parent === void 0 ? void 0 : parent.type) === "AwaitExpression";
|
|
312
|
+
const start = (id) => `${ToolCallTrackerFnIdentifier}(${id}, "start");`;
|
|
313
|
+
const end = (id, value) => `${ToolCallTrackerFnIdentifier}(${id}, "end", ${value});`;
|
|
314
|
+
const prefix = (id) => `(${isAsync ? "async " : ""}() => {try {${start(id)}const ${ToolTrackerRetIdentifier} = ${isAsync ? "await " : ""}`;
|
|
315
|
+
const successSuffix = (id) => `;${end(id, ToolTrackerRetIdentifier)}return ${ToolTrackerRetIdentifier};}`;
|
|
316
|
+
if (!lval) {
|
|
317
|
+
if (!sliceOf(node).trim().length) return;
|
|
318
|
+
const catchClause = ` catch (err) {${end(callId, "err")}const __newError = new Error(err.message);__newError.stack = err.stack + ("\\n" + __newError.stack);throw __newError;}})()`;
|
|
319
|
+
ctx.ms.appendLeft(node.start, prefix(callId));
|
|
320
|
+
ctx.ms.appendRight(node.end, successSuffix(callId) + catchClause);
|
|
321
|
+
wrappedRanges.push([node.start, node.end]);
|
|
322
|
+
callId++;
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
const assign = extractAssignment(lval);
|
|
326
|
+
if (assign.type === "unsupported") return;
|
|
327
|
+
const tryId = callId;
|
|
328
|
+
callId++;
|
|
329
|
+
const callee = node.callee;
|
|
330
|
+
let object = "global";
|
|
331
|
+
let tool = callee.type === "Identifier" ? callee.name : sliceOf(callee);
|
|
332
|
+
if (callee.type === "MemberExpression") {
|
|
333
|
+
object = sliceOf(callee.object);
|
|
334
|
+
const property = callee.property;
|
|
335
|
+
tool = property.type === "Identifier" ? property.name : property.type === "Literal" ? String(property.value) : sliceOf(property);
|
|
336
|
+
}
|
|
337
|
+
const catchClause = ` catch (err) {${end(callId, "err")}throw new Error(err.message);}})()`;
|
|
338
|
+
ctx.ms.appendLeft(node.start, prefix(tryId));
|
|
339
|
+
ctx.ms.appendRight(node.end, successSuffix(tryId) + catchClause);
|
|
340
|
+
wrappedRanges.push([node.start, node.end]);
|
|
341
|
+
calls.set(callId, {
|
|
342
|
+
object,
|
|
343
|
+
tool,
|
|
344
|
+
assignment: assign
|
|
345
|
+
});
|
|
346
|
+
});
|
|
347
|
+
return wrappedRanges;
|
|
348
|
+
}
|
|
349
|
+
//#endregion
|
|
350
|
+
//#region src/compiler/plugins/variable-extraction.ts
|
|
351
|
+
const VariableTrackingFnIdentifier = "__var__";
|
|
352
|
+
/**
|
|
353
|
+
* Tracks user variables so the VM can read their values between iterations:
|
|
354
|
+
* - after each variable declaration: `__var__("a", () => eval("a"));`
|
|
355
|
+
* - at the top of function bodies, for their parameters
|
|
356
|
+
*
|
|
357
|
+
* The `eval` indirection captures the variable lazily in its own scope.
|
|
358
|
+
*/
|
|
359
|
+
function applyVariableTracking(ctx, variables) {
|
|
360
|
+
const trackerFor = (name) => {
|
|
361
|
+
if (name.startsWith("__")) return null;
|
|
362
|
+
variables.add(name);
|
|
363
|
+
return `${VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => eval(${JSON.stringify(name)}));`;
|
|
364
|
+
};
|
|
365
|
+
const track = (names) => names.map(trackerFor).filter((t) => !!t).join("");
|
|
366
|
+
const declaredNames = (id) => {
|
|
367
|
+
if (id.type === "Identifier") return [id.name];
|
|
368
|
+
if (id.type === "ObjectPattern") {
|
|
369
|
+
const names = [];
|
|
370
|
+
for (const prop of id.properties) {
|
|
371
|
+
if (prop.type !== "Property") continue;
|
|
372
|
+
if (prop.value.type === "Identifier") names.push(prop.value.name);
|
|
373
|
+
else if (prop.value.type === "ObjectPattern") names.push(...declaredNames(prop.value));
|
|
374
|
+
else if (prop.value.type === "AssignmentPattern" && prop.value.left.type === "Identifier") names.push(prop.value.left.name);
|
|
375
|
+
}
|
|
376
|
+
return names;
|
|
377
|
+
}
|
|
378
|
+
if (id.type === "ArrayPattern") {
|
|
379
|
+
const names = [];
|
|
380
|
+
for (const element of id.elements) {
|
|
381
|
+
if (!element) continue;
|
|
382
|
+
if (element.type === "Identifier") names.push(element.name);
|
|
383
|
+
else if (element.type === "RestElement" && element.argument.type === "Identifier") names.push(element.argument.name);
|
|
384
|
+
else if (element.type === "AssignmentPattern" && element.left.type === "Identifier") names.push(element.left.name);
|
|
385
|
+
}
|
|
386
|
+
return names;
|
|
387
|
+
}
|
|
388
|
+
return [];
|
|
389
|
+
};
|
|
390
|
+
const paramNames = (params) => {
|
|
391
|
+
const names = [];
|
|
392
|
+
for (const param of params) if (param.type === "Identifier") names.push(param.name);
|
|
393
|
+
else if (param.type === "AssignmentPattern" && param.left.type === "Identifier") names.push(param.left.name);
|
|
394
|
+
else if (param.type === "ObjectPattern") {
|
|
395
|
+
for (const prop of param.properties) if (prop.type === "Property" && prop.value.type === "Identifier") names.push(prop.value.name);
|
|
396
|
+
} else if (param.type === "ArrayPattern") {
|
|
397
|
+
for (const element of param.elements) if ((element === null || element === void 0 ? void 0 : element.type) === "Identifier") names.push(element.name);
|
|
398
|
+
}
|
|
399
|
+
return names;
|
|
400
|
+
};
|
|
401
|
+
walk(ctx.ast, (node, parent) => {
|
|
402
|
+
if (node.type === "VariableDeclaration") {
|
|
403
|
+
if (parent && (parent.type === "ForStatement" || parent.type === "ForInStatement" || parent.type === "ForOfStatement")) return;
|
|
404
|
+
const trackers = track(node.declarations.flatMap((d) => declaredNames(d.id)));
|
|
405
|
+
if (trackers) {
|
|
406
|
+
const semi = ctx.code[node.end - 1] === ";" ? "" : ";";
|
|
407
|
+
ctx.ms.appendRight(node.end, `${semi}${trackers}`);
|
|
408
|
+
}
|
|
409
|
+
return;
|
|
410
|
+
}
|
|
411
|
+
if (node.type === "FunctionDeclaration" || node.type === "ArrowFunctionExpression") {
|
|
412
|
+
const trackers = track(paramNames(node.params));
|
|
413
|
+
if (!trackers) return;
|
|
414
|
+
const body = node.body;
|
|
415
|
+
if (body.type === "BlockStatement") ctx.ms.appendRight(body.start + 1, trackers);
|
|
416
|
+
else {
|
|
417
|
+
const expressions = trackers.slice(0, -1).replaceAll(";", ",");
|
|
418
|
+
ctx.ms.prependLeft(body.start, `(${expressions}, (`);
|
|
419
|
+
ctx.ms.appendRight(body.end, "))");
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
//#endregion
|
|
425
|
+
//#region src/compiler/compiler.ts
|
|
426
|
+
const Identifiers = {
|
|
427
|
+
ConsoleObjIdentifier: "console",
|
|
428
|
+
LineTrackingFnIdentifier,
|
|
429
|
+
VariableTrackingFnIdentifier,
|
|
430
|
+
ToolCallTrackerFnIdentifier,
|
|
431
|
+
ToolTrackerRetIdentifier,
|
|
432
|
+
CommentFnIdentifier
|
|
433
|
+
};
|
|
434
|
+
const FUNCTION_TYPES = /* @__PURE__ */ new Set([
|
|
435
|
+
"FunctionDeclaration",
|
|
436
|
+
"FunctionExpression",
|
|
437
|
+
"ArrowFunctionExpression"
|
|
438
|
+
]);
|
|
439
|
+
/**
|
|
440
|
+
* Whether the code contains a top-level `return` statement (one that would
|
|
441
|
+
* return from the generated code itself, not from a nested function). Unlike a
|
|
442
|
+
* regex, this ignores `return` inside comments, strings and nested functions.
|
|
443
|
+
* Falls back to a word-boundary match if the code cannot be parsed.
|
|
444
|
+
*/
|
|
445
|
+
function hasTopLevelReturn(code) {
|
|
446
|
+
try {
|
|
447
|
+
const ast = parseScript(code);
|
|
448
|
+
let found = false;
|
|
449
|
+
walk(ast, (node, _parent, ancestors) => {
|
|
450
|
+
if (node.type === "ReturnStatement" && !ancestors.some((a) => FUNCTION_TYPES.has(a.type))) found = true;
|
|
451
|
+
});
|
|
452
|
+
return found;
|
|
453
|
+
} catch {
|
|
454
|
+
return /\breturn\b/.test(code);
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Compiles the agent's generated JavaScript for VM execution:
|
|
459
|
+
*
|
|
460
|
+
* 1. wraps it in an async `__fn__` so top-level `await`/`return` parse
|
|
461
|
+
* 2. instruments it in a single parse + text-edit pass:
|
|
462
|
+
* line tracking, last-line return, tool-call tracking, comment tracing
|
|
463
|
+
* and variable tracking
|
|
464
|
+
* 3. unwraps it — the VM drivers re-wrap the bare statements themselves
|
|
465
|
+
*
|
|
466
|
+
* All edits preserve line numbers 1:1 with the wrapped source, so positions
|
|
467
|
+
* reported at runtime map straight back to the user code.
|
|
468
|
+
*/
|
|
469
|
+
function compile(code) {
|
|
470
|
+
const wrapped = AsyncWrapper.preProcessing(code);
|
|
471
|
+
const comments = [];
|
|
472
|
+
const ast = parseScript(wrapped, { comments });
|
|
473
|
+
const variables = /* @__PURE__ */ new Set();
|
|
474
|
+
const toolCalls = /* @__PURE__ */ new Map();
|
|
475
|
+
const lastLine = planLastLineInstrumentation(ast);
|
|
476
|
+
const msMarkers = new magic_string.default(wrapped);
|
|
477
|
+
if (lastLine) {
|
|
478
|
+
msMarkers.appendLeft(lastLine.prefixPos, lastLine.prefix);
|
|
479
|
+
msMarkers.appendRight(lastLine.suffixPos, lastLine.suffix);
|
|
480
|
+
}
|
|
481
|
+
const codeWithMarkers = msMarkers.toString();
|
|
482
|
+
const ms = new magic_string.default(wrapped);
|
|
483
|
+
const ctx = {
|
|
484
|
+
code: wrapped,
|
|
485
|
+
ms,
|
|
486
|
+
ast,
|
|
487
|
+
comments
|
|
488
|
+
};
|
|
489
|
+
applyLineTracking(ctx);
|
|
490
|
+
if (lastLine) ms.appendLeft(lastLine.prefixPos, lastLine.prefix);
|
|
491
|
+
applyCommentReplacement(ctx, applyToolCallTracking(ctx, toolCalls));
|
|
492
|
+
applyVariableTracking(ctx, variables);
|
|
493
|
+
if (lastLine) ms.appendRight(lastLine.suffixPos, lastLine.suffix);
|
|
494
|
+
return {
|
|
495
|
+
code: AsyncWrapper.postProcessing(ms.toString()),
|
|
496
|
+
codeWithMarkers,
|
|
497
|
+
map: ms.generateMap({
|
|
498
|
+
hires: true,
|
|
499
|
+
source: "<anonymous>"
|
|
500
|
+
}),
|
|
501
|
+
variables,
|
|
502
|
+
toolCalls
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
//#endregion
|
|
506
|
+
Object.defineProperty(exports, "Identifiers", {
|
|
507
|
+
enumerable: true,
|
|
508
|
+
get: function() {
|
|
509
|
+
return Identifiers;
|
|
510
|
+
}
|
|
511
|
+
});
|
|
512
|
+
Object.defineProperty(exports, "USER_CODE_START_MARKER", {
|
|
513
|
+
enumerable: true,
|
|
514
|
+
get: function() {
|
|
515
|
+
return USER_CODE_START_MARKER;
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
Object.defineProperty(exports, "__commonJSMin", {
|
|
519
|
+
enumerable: true,
|
|
520
|
+
get: function() {
|
|
521
|
+
return __commonJSMin;
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
Object.defineProperty(exports, "__exportAll", {
|
|
525
|
+
enumerable: true,
|
|
526
|
+
get: function() {
|
|
527
|
+
return __exportAll;
|
|
528
|
+
}
|
|
529
|
+
});
|
|
530
|
+
Object.defineProperty(exports, "__toESM", {
|
|
531
|
+
enumerable: true,
|
|
532
|
+
get: function() {
|
|
533
|
+
return __toESM;
|
|
534
|
+
}
|
|
535
|
+
});
|
|
536
|
+
Object.defineProperty(exports, "compile", {
|
|
537
|
+
enumerable: true,
|
|
538
|
+
get: function() {
|
|
539
|
+
return compile;
|
|
540
|
+
}
|
|
541
|
+
});
|
|
542
|
+
Object.defineProperty(exports, "hasTopLevelReturn", {
|
|
543
|
+
enumerable: true,
|
|
544
|
+
get: function() {
|
|
545
|
+
return hasTopLevelReturn;
|
|
546
|
+
}
|
|
547
|
+
});
|