llmz 0.0.29 → 0.0.31

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 (30) hide show
  1. package/README.md +25 -12
  2. package/dist/{chunk-WP4F6KMW.cjs → chunk-5BEKU5MZ.cjs} +2 -2
  3. package/dist/{chunk-VADA6DMR.cjs → chunk-66NCLCNT.cjs} +296 -10
  4. package/dist/{chunk-HCC76DDO.js → chunk-AAHUDKBY.js} +2 -2
  5. package/dist/{chunk-FMOTPO76.cjs → chunk-CA7FRCZT.cjs} +1130 -401
  6. package/dist/{chunk-ERK3MOZF.js → chunk-IAYPKHFV.js} +1129 -400
  7. package/dist/{chunk-273DEMEU.cjs → chunk-J57224PD.cjs} +62 -8
  8. package/dist/{chunk-7POUFE5M.js → chunk-RC6YO5UW.js} +62 -8
  9. package/dist/{chunk-KQPGB6GB.js → chunk-WYFTNO2Y.js} +289 -3
  10. package/dist/compiler/compiler.d.ts +1 -0
  11. package/dist/compiler/plugins/async-iterator.d.ts +2 -0
  12. package/dist/compiler/plugins/html-to-markdown.d.ts +21 -0
  13. package/dist/compiler/plugins/jsx-undefined-vars.d.ts +14 -0
  14. package/dist/{dual-modes-DW3KRXT2.js → dual-modes-LEAHGCOF.js} +1 -1
  15. package/dist/{dual-modes-F4UV5VAZ.cjs → dual-modes-UBHAMQW4.cjs} +2 -2
  16. package/dist/exit-parser.d.ts +37 -0
  17. package/dist/index.cjs +12 -10
  18. package/dist/index.d.ts +1 -0
  19. package/dist/index.js +11 -9
  20. package/dist/{llmz-RZUY2RT4.cjs → llmz-NB4CQ5PW.cjs} +29 -50
  21. package/dist/{llmz-QUBEO7EF.js → llmz-VOXE65UW.js} +21 -42
  22. package/dist/prompts/worker-mode/system.md.d.ts +1 -1
  23. package/dist/quickjs-variant.d.ts +2 -0
  24. package/dist/{tool-GEBXW6AQ.js → tool-U6SV6BZ6.js} +1 -1
  25. package/dist/{tool-GMYMVXUK.cjs → tool-YCYYKKB3.cjs} +2 -2
  26. package/dist/tool.d.ts +1 -1
  27. package/dist/{vm-5SJN3OJI.cjs → vm-2LG42J6U.cjs} +2 -4
  28. package/dist/{vm-SQHETBVH.js → vm-FVQBX2XV.js} +1 -3
  29. package/dist/vm.d.ts +7 -1
  30. package/package.json +3 -2
@@ -1,5 +1,4 @@
1
1
  import {
2
- AssignmentError,
3
2
  CodeExecutionError,
4
3
  InvalidCodeError,
5
4
  Signals,
@@ -1936,6 +1935,7 @@ var require_source_map = __commonJS({
1936
1935
 
1937
1936
  // src/vm.ts
1938
1937
  var import_source_map_js = __toESM(require_source_map(), 1);
1938
+ import { newQuickJSWASMModuleFromVariant, shouldInterruptAfterDeadline } from "quickjs-emscripten-core";
1939
1939
 
1940
1940
  // src/compiler/compiler.ts
1941
1941
  import jsxPlugin from "@babel/plugin-transform-react-jsx";
@@ -1944,17 +1944,22 @@ import * as Babel from "@babel/standalone";
1944
1944
  // src/compiler/plugins/async-iterator.ts
1945
1945
  var Open = "async function* __fn__() {";
1946
1946
  var Close = "}";
1947
+ var USER_CODE_START_MARKER = "/* __LLMZ_USER_CODE_START__ */";
1948
+ var USER_CODE_END_MARKER = "/* __LLMZ_USER_CODE_END__ */";
1947
1949
  var AsyncIterator = {
1948
1950
  preProcessing: (code) => {
1949
1951
  return `"use strict";
1950
1952
  ${Open}
1953
+ ${USER_CODE_START_MARKER}
1951
1954
  ${code}
1955
+ ${USER_CODE_END_MARKER}
1952
1956
  ${Close}
1953
1957
  `.trim();
1954
1958
  },
1955
1959
  postProcessing: (code) => {
1956
1960
  code = code.slice(code.indexOf(Open) + Open.length).trim();
1957
1961
  code = code.slice(0, code.lastIndexOf(Close));
1962
+ code = code.replace(USER_CODE_START_MARKER, "").replace(USER_CODE_END_MARKER, "");
1958
1963
  return code;
1959
1964
  }
1960
1965
  };
@@ -2096,6 +2101,207 @@ var JSXMarkdown = {
2096
2101
  }
2097
2102
  };
2098
2103
 
2104
+ // src/compiler/plugins/html-to-markdown.ts
2105
+ import { types as t } from "@babel/core";
2106
+ function htmlToMarkdownPlugin() {
2107
+ return {
2108
+ name: "html-to-markdown",
2109
+ visitor: {
2110
+ JSXElement(path) {
2111
+ const { openingElement } = path.node;
2112
+ const tagName = t.isJSXIdentifier(openingElement.name) ? openingElement.name.name : null;
2113
+ if (!tagName)
2114
+ return;
2115
+ const lowerTagName = tagName.toLowerCase();
2116
+ if (lowerTagName === "strong" || lowerTagName === "b") {
2117
+ convertToMarkdown(path, "**", "**");
2118
+ } else if (lowerTagName === "em" || lowerTagName === "i") {
2119
+ convertToMarkdown(path, "*", "*");
2120
+ } else if (lowerTagName === "u") {
2121
+ convertToMarkdown(path, "__", "__");
2122
+ } else if (lowerTagName === "a") {
2123
+ convertLinkToMarkdown(path);
2124
+ } else if (lowerTagName === "br") {
2125
+ convertBrToNewline(path);
2126
+ } else if (lowerTagName === "p") {
2127
+ convertParagraphToMarkdown(path);
2128
+ } else if (lowerTagName === "ul") {
2129
+ convertUnorderedListToMarkdown(path);
2130
+ } else if (lowerTagName === "ol") {
2131
+ convertOrderedListToMarkdown(path);
2132
+ }
2133
+ }
2134
+ }
2135
+ };
2136
+ }
2137
+ function hasOnlyTextChildren(children) {
2138
+ return children.every(
2139
+ (child) => t.isJSXText(child) || t.isJSXExpressionContainer(child) && !t.isJSXElement(child.expression) || t.isJSXElement(child) && canConvertToMarkdown(child)
2140
+ );
2141
+ }
2142
+ function canConvertToMarkdown(element) {
2143
+ const { openingElement } = element;
2144
+ const tagName = t.isJSXIdentifier(openingElement.name) ? openingElement.name.name.toLowerCase() : null;
2145
+ if (!tagName)
2146
+ return false;
2147
+ const allowedTags = ["strong", "b", "em", "i", "u", "br", "p", "a", "li", "ul", "ol"];
2148
+ if (!allowedTags.includes(tagName))
2149
+ return false;
2150
+ if (tagName === "a") {
2151
+ return openingElement.attributes.length === 1 && t.isJSXAttribute(openingElement.attributes[0]) && t.isJSXIdentifier(openingElement.attributes[0].name) && openingElement.attributes[0].name.name === "href";
2152
+ }
2153
+ if (tagName === "br") {
2154
+ return openingElement.attributes.length === 0;
2155
+ }
2156
+ return openingElement.attributes.length === 0;
2157
+ }
2158
+ function convertToMarkdown(path, prefix, suffix) {
2159
+ const element = path.node;
2160
+ if (!canConvertToMarkdown(element))
2161
+ return;
2162
+ const children = element.children;
2163
+ if (!hasOnlyTextChildren(children))
2164
+ return;
2165
+ const textContent = extractTextContent(children);
2166
+ if (!textContent)
2167
+ return;
2168
+ const markdownText = `${prefix}${textContent}${suffix}`;
2169
+ path.replaceWith(t.jsxText(markdownText));
2170
+ }
2171
+ function convertLinkToMarkdown(path) {
2172
+ const element = path.node;
2173
+ if (!canConvertToMarkdown(element))
2174
+ return;
2175
+ const children = element.children;
2176
+ if (!hasOnlyTextChildren(children))
2177
+ return;
2178
+ const hrefAttr = element.openingElement.attributes.find(
2179
+ (attr) => t.isJSXAttribute(attr) && t.isJSXIdentifier(attr.name) && attr.name.name === "href"
2180
+ );
2181
+ if (!hrefAttr || !t.isJSXAttribute(hrefAttr))
2182
+ return;
2183
+ let href = "";
2184
+ if (t.isStringLiteral(hrefAttr.value)) {
2185
+ href = hrefAttr.value.value;
2186
+ } else if (t.isJSXExpressionContainer(hrefAttr.value) && t.isStringLiteral(hrefAttr.value.expression)) {
2187
+ href = hrefAttr.value.expression.value;
2188
+ } else {
2189
+ return;
2190
+ }
2191
+ const textContent = extractTextContent(children);
2192
+ if (!textContent)
2193
+ return;
2194
+ const markdownText = `[${textContent}](${href})`;
2195
+ path.replaceWith(t.jsxText(markdownText));
2196
+ }
2197
+ function convertBrToNewline(path) {
2198
+ const element = path.node;
2199
+ if (!canConvertToMarkdown(element))
2200
+ return;
2201
+ path.replaceWith(t.jsxText("\n"));
2202
+ }
2203
+ function convertParagraphToMarkdown(path) {
2204
+ const element = path.node;
2205
+ if (!canConvertToMarkdown(element))
2206
+ return;
2207
+ const children = element.children;
2208
+ if (!hasOnlyTextChildren(children))
2209
+ return;
2210
+ const textContent = extractTextContent(children);
2211
+ if (!textContent)
2212
+ return;
2213
+ const markdownText = `${textContent}
2214
+
2215
+ `;
2216
+ path.replaceWith(t.jsxText(markdownText));
2217
+ }
2218
+ function convertUnorderedListToMarkdown(path) {
2219
+ const element = path.node;
2220
+ if (element.openingElement.attributes.length > 0)
2221
+ return;
2222
+ const children = element.children;
2223
+ const listItems = [];
2224
+ for (const child of children) {
2225
+ if (t.isJSXElement(child)) {
2226
+ const tagName = t.isJSXIdentifier(child.openingElement.name) ? child.openingElement.name.name : null;
2227
+ if ((tagName == null ? void 0 : tagName.toLowerCase()) === "li" && canConvertToMarkdown(child)) {
2228
+ const itemText = extractTextContent(child.children);
2229
+ if (itemText) {
2230
+ listItems.push(`- ${itemText}`);
2231
+ }
2232
+ } else {
2233
+ return;
2234
+ }
2235
+ } else if (t.isJSXText(child) && child.value.trim()) {
2236
+ return;
2237
+ }
2238
+ }
2239
+ if (listItems.length === 0)
2240
+ return;
2241
+ const markdownText = listItems.join("\n") + "\n";
2242
+ path.replaceWith(t.jsxText(markdownText));
2243
+ }
2244
+ function convertOrderedListToMarkdown(path) {
2245
+ const element = path.node;
2246
+ if (element.openingElement.attributes.length > 0)
2247
+ return;
2248
+ const children = element.children;
2249
+ const listItems = [];
2250
+ for (const child of children) {
2251
+ if (t.isJSXElement(child)) {
2252
+ const tagName = t.isJSXIdentifier(child.openingElement.name) ? child.openingElement.name.name : null;
2253
+ if ((tagName == null ? void 0 : tagName.toLowerCase()) === "li" && canConvertToMarkdown(child)) {
2254
+ const itemText = extractTextContent(child.children);
2255
+ if (itemText) {
2256
+ listItems.push(`${listItems.length + 1}. ${itemText}`);
2257
+ }
2258
+ } else {
2259
+ return;
2260
+ }
2261
+ } else if (t.isJSXText(child) && child.value.trim()) {
2262
+ return;
2263
+ }
2264
+ }
2265
+ if (listItems.length === 0)
2266
+ return;
2267
+ const markdownText = listItems.join("\n") + "\n";
2268
+ path.replaceWith(t.jsxText(markdownText));
2269
+ }
2270
+ function extractTextContent(children) {
2271
+ let text = "";
2272
+ for (const child of children) {
2273
+ if (t.isJSXText(child)) {
2274
+ text += child.value;
2275
+ } else if (t.isJSXExpressionContainer(child)) {
2276
+ return "";
2277
+ } else if (t.isJSXElement(child)) {
2278
+ const nestedText = extractTextContent(child.children);
2279
+ if (!nestedText)
2280
+ return "";
2281
+ const tagName = t.isJSXIdentifier(child.openingElement.name) ? child.openingElement.name.name.toLowerCase() : null;
2282
+ switch (tagName) {
2283
+ case "strong":
2284
+ case "b":
2285
+ text += `**${nestedText}**`;
2286
+ break;
2287
+ case "em":
2288
+ case "i":
2289
+ text += `*${nestedText}*`;
2290
+ break;
2291
+ case "u":
2292
+ text += `__${nestedText}__`;
2293
+ break;
2294
+ case "br":
2295
+ text += "\n";
2296
+ break;
2297
+ default:
2298
+ return "";
2299
+ }
2300
+ }
2301
+ }
2302
+ return text;
2303
+ }
2304
+
2099
2305
  // src/compiler/plugins/jsx-preserve-newlines.ts
2100
2306
  import {
2101
2307
  isJSXIdentifier,
@@ -2132,10 +2338,71 @@ var JSXNewLines = {
2132
2338
  postProcessing
2133
2339
  };
2134
2340
 
2341
+ // src/compiler/plugins/jsx-undefined-vars.ts
2342
+ import { types as t2 } from "@babel/core";
2343
+ function jsxUndefinedVarsPlugin() {
2344
+ return {
2345
+ name: "jsx-undefined-vars",
2346
+ visitor: {
2347
+ JSXExpressionContainer(path) {
2348
+ const expression = path.node.expression;
2349
+ if (t2.isJSXEmptyExpression(expression)) {
2350
+ return;
2351
+ }
2352
+ if (!t2.isIdentifier(expression)) {
2353
+ return;
2354
+ }
2355
+ const varName = expression.name;
2356
+ const knownGlobals = /* @__PURE__ */ new Set([
2357
+ "undefined",
2358
+ "null",
2359
+ "true",
2360
+ "false",
2361
+ "NaN",
2362
+ "Infinity",
2363
+ "console",
2364
+ "Math",
2365
+ "JSON",
2366
+ "Object",
2367
+ "Array",
2368
+ "String",
2369
+ "Number",
2370
+ "Boolean",
2371
+ "Date",
2372
+ "RegExp",
2373
+ "Error",
2374
+ "Promise",
2375
+ "Symbol"
2376
+ ]);
2377
+ if (knownGlobals.has(varName)) {
2378
+ return;
2379
+ }
2380
+ const iife = t2.callExpression(
2381
+ t2.arrowFunctionExpression(
2382
+ [],
2383
+ t2.blockStatement([
2384
+ t2.tryStatement(
2385
+ t2.blockStatement([t2.returnStatement(t2.identifier(varName))]),
2386
+ t2.catchClause(
2387
+ null,
2388
+ // no error binding needed
2389
+ t2.blockStatement([t2.returnStatement(t2.stringLiteral(varName))])
2390
+ )
2391
+ )
2392
+ ])
2393
+ ),
2394
+ []
2395
+ );
2396
+ path.node.expression = iife;
2397
+ }
2398
+ }
2399
+ };
2400
+ }
2401
+
2135
2402
  // src/compiler/plugins/line-tracking.ts
2136
2403
  import { callExpression, expressionStatement, identifier, numericLiteral } from "@babel/types";
2137
2404
  var LineTrackingFnIdentifier = "__track__";
2138
- var lineTrackingBabelPlugin = function({ types: t }) {
2405
+ var lineTrackingBabelPlugin = function({ types: t3 }) {
2139
2406
  return {
2140
2407
  visitor: {
2141
2408
  Program(path) {
@@ -2156,8 +2423,8 @@ var lineTrackingBabelPlugin = function({ types: t }) {
2156
2423
  console.error(e);
2157
2424
  }
2158
2425
  };
2159
- 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)) {
2160
- 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)) {
2426
+ if (t3.isFunctionDeclaration(node) || t3.isClassMethod(node) || t3.isReturnStatement(node) || t3.isAwaitExpression(node) || t3.isForOfStatement(node) || t3.isCallExpression(node) || t3.isUnaryExpression(node) || t3.isVariableDeclaration(node) || t3.isBlockStatement(path2.parent) || t3.isAssignmentExpression(node)) {
2427
+ if (!trackedLines.has(startLine) && !t3.isArrowFunctionExpression(path2.parent) && !t3.isObjectProperty(path2.parent) && !t3.isAwaitExpression(path2.parent) && !t3.isUnaryExpression(path2.parent) && !t3.isReturnStatement(path2.parent) && !t3.isForOfStatement(path2.parent) && !t3.isForStatement(path2.parent) && !t3.isForInStatement(path2.parent) && !t3.isVariableDeclaration(path2.parent) && !t3.isBinaryExpression(path2.parent) && !t3.isLogicalExpression(path2.parent)) {
2161
2428
  track();
2162
2429
  }
2163
2430
  }
@@ -2172,7 +2439,7 @@ var lineTrackingBabelPlugin = function({ types: t }) {
2172
2439
  // src/compiler/plugins/replace-comment.ts
2173
2440
  var CommentFnIdentifier = "__comment__";
2174
2441
  var replaceCommentBabelPlugin = function({
2175
- types: t
2442
+ types: t3
2176
2443
  }) {
2177
2444
  return {
2178
2445
  visitor: {
@@ -2186,18 +2453,18 @@ var replaceCommentBabelPlugin = function({
2186
2453
  return;
2187
2454
  }
2188
2455
  comments.sort((a, b) => a.start > b.start ? -1 : 1).forEach((comment) => {
2189
- var _a3;
2456
+ var _a;
2190
2457
  if (processed.has(comment.loc)) {
2191
2458
  return;
2192
2459
  }
2193
2460
  processed.add(comment.loc);
2194
- const commentCall = t.expressionStatement(
2195
- t.callExpression(t.identifier(CommentFnIdentifier), [
2196
- t.stringLiteral(comment.value.trim()),
2197
- t.numericLiteral(((_a3 = comment.loc) == null ? void 0 : _a3.start.line) ?? 0)
2461
+ const commentCall = t3.expressionStatement(
2462
+ t3.callExpression(t3.identifier(CommentFnIdentifier), [
2463
+ t3.stringLiteral(comment.value.trim()),
2464
+ t3.numericLiteral(((_a = comment.loc) == null ? void 0 : _a.start.line) ?? 0)
2198
2465
  ])
2199
2466
  );
2200
- const isInsideObjectProperty = t.isObjectProperty(node) || path2.findParent((path3) => t.isObjectProperty(path3.node));
2467
+ const isInsideObjectProperty = t3.isObjectProperty(node) || path2.findParent((path3) => t3.isObjectProperty(path3.node));
2201
2468
  if (!isInsideObjectProperty) {
2202
2469
  insertMethod(commentCall);
2203
2470
  }
@@ -2216,13 +2483,13 @@ var replaceCommentBabelPlugin = function({
2216
2483
 
2217
2484
  // src/compiler/plugins/return-async.ts
2218
2485
  var instrumentLastLinePlugin = function({
2219
- types: t
2486
+ types: t3
2220
2487
  }) {
2221
2488
  return {
2222
2489
  visitor: {
2223
2490
  FunctionDeclaration(path) {
2224
- var _a3, _b;
2225
- if (((_a3 = path.node.id) == null ? void 0 : _a3.name) !== "__fn__") {
2491
+ var _a, _b;
2492
+ if (((_a = path.node.id) == null ? void 0 : _a.name) !== "__fn__") {
2226
2493
  return;
2227
2494
  }
2228
2495
  const statements = path.node.body.body;
@@ -2230,14 +2497,14 @@ var instrumentLastLinePlugin = function({
2230
2497
  return;
2231
2498
  }
2232
2499
  const lastStatement = statements[statements.length - 1];
2233
- if (t.isReturnStatement(lastStatement)) {
2234
- if (t.isExpression(lastStatement.argument)) {
2235
- lastStatement.argument = t.awaitExpression(lastStatement.argument);
2500
+ if (t3.isReturnStatement(lastStatement)) {
2501
+ if (t3.isExpression(lastStatement.argument)) {
2502
+ lastStatement.argument = t3.awaitExpression(lastStatement.argument);
2236
2503
  }
2237
2504
  return;
2238
2505
  }
2239
- if (t.isExpressionStatement(lastStatement) && (t.isCallExpression(lastStatement.expression) || t.isAwaitExpression(lastStatement.expression))) {
2240
- const returnStatement3 = t.returnStatement(t.awaitExpression(lastStatement.expression));
2506
+ if (t3.isExpressionStatement(lastStatement) && (t3.isCallExpression(lastStatement.expression) || t3.isAwaitExpression(lastStatement.expression))) {
2507
+ const returnStatement3 = t3.returnStatement(t3.awaitExpression(lastStatement.expression));
2241
2508
  (_b = path.get("body").get("body")[statements.length - 1]) == null ? void 0 : _b.replaceWith(returnStatement3);
2242
2509
  }
2243
2510
  }
@@ -2308,7 +2575,7 @@ var toolCallTrackingPlugin = (calls = /* @__PURE__ */ new Map()) => function({})
2308
2575
  skip.clear();
2309
2576
  },
2310
2577
  CallExpression(path) {
2311
- var _a3;
2578
+ var _a;
2312
2579
  if (skip.has(path.node) || path.findParent((p) => skip.has(p.node))) {
2313
2580
  return;
2314
2581
  }
@@ -2323,7 +2590,7 @@ var toolCallTrackingPlugin = (calls = /* @__PURE__ */ new Map()) => function({})
2323
2590
  (p) => p.isAssignmentExpression()
2324
2591
  );
2325
2592
  if (declaration) {
2326
- lval = (_a3 = declaration.get("declarations")[0]) == null ? void 0 : _a3.get("id");
2593
+ lval = (_a = declaration.get("declarations")[0]) == null ? void 0 : _a.get("id");
2327
2594
  }
2328
2595
  if (assignment) {
2329
2596
  const left = assignment.get("left");
@@ -2455,7 +2722,7 @@ import {
2455
2722
  returnStatement as returnStatement2
2456
2723
  } from "@babel/types";
2457
2724
  var VariableTrackingFnIdentifier = "__var__";
2458
- var variableTrackingPlugin = (variables = /* @__PURE__ */ new Set()) => function({ types: t }) {
2725
+ var variableTrackingPlugin = (variables = /* @__PURE__ */ new Set()) => function({ types: t3 }) {
2459
2726
  let trackingStatements = [];
2460
2727
  const trackVariable = (variableName) => {
2461
2728
  if (variableName.startsWith("__")) {
@@ -2475,19 +2742,19 @@ var variableTrackingPlugin = (variables = /* @__PURE__ */ new Set()) => function
2475
2742
  visitor: {
2476
2743
  FunctionDeclaration(path) {
2477
2744
  path.node.params.forEach((param) => {
2478
- if (t.isIdentifier(param)) {
2745
+ if (t3.isIdentifier(param)) {
2479
2746
  trackVariable(param.name);
2480
- } else if (t.isAssignmentPattern(param) && t.isIdentifier(param.left)) {
2747
+ } else if (t3.isAssignmentPattern(param) && t3.isIdentifier(param.left)) {
2481
2748
  trackVariable(param.left.name);
2482
- } else if (t.isObjectPattern(param)) {
2749
+ } else if (t3.isObjectPattern(param)) {
2483
2750
  param.properties.forEach((prop) => {
2484
- if (t.isObjectProperty(prop) && t.isIdentifier(prop.value)) {
2751
+ if (t3.isObjectProperty(prop) && t3.isIdentifier(prop.value)) {
2485
2752
  trackVariable(prop.value.name);
2486
2753
  }
2487
2754
  });
2488
- } else if (t.isArrayPattern(param)) {
2755
+ } else if (t3.isArrayPattern(param)) {
2489
2756
  param.elements.forEach((element) => {
2490
- if (t.isIdentifier(element)) {
2757
+ if (t3.isIdentifier(element)) {
2491
2758
  trackVariable(element.name);
2492
2759
  }
2493
2760
  });
@@ -2500,19 +2767,19 @@ var variableTrackingPlugin = (variables = /* @__PURE__ */ new Set()) => function
2500
2767
  },
2501
2768
  ArrowFunctionExpression(path) {
2502
2769
  path.node.params.forEach((param) => {
2503
- if (t.isIdentifier(param)) {
2770
+ if (t3.isIdentifier(param)) {
2504
2771
  trackVariable(param.name);
2505
- } else if (t.isAssignmentPattern(param) && t.isIdentifier(param.left)) {
2772
+ } else if (t3.isAssignmentPattern(param) && t3.isIdentifier(param.left)) {
2506
2773
  trackVariable(param.left.name);
2507
- } else if (t.isObjectPattern(param)) {
2774
+ } else if (t3.isObjectPattern(param)) {
2508
2775
  param.properties.forEach((prop) => {
2509
- if (t.isObjectProperty(prop) && t.isIdentifier(prop.value)) {
2776
+ if (t3.isObjectProperty(prop) && t3.isIdentifier(prop.value)) {
2510
2777
  trackVariable(prop.value.name);
2511
2778
  }
2512
2779
  });
2513
- } else if (t.isArrayPattern(param)) {
2780
+ } else if (t3.isArrayPattern(param)) {
2514
2781
  param.elements.forEach((element) => {
2515
- if (t.isIdentifier(element)) {
2782
+ if (t3.isIdentifier(element)) {
2516
2783
  trackVariable(element.name);
2517
2784
  }
2518
2785
  });
@@ -2533,11 +2800,11 @@ var variableTrackingPlugin = (variables = /* @__PURE__ */ new Set()) => function
2533
2800
  const parent = path.parentPath;
2534
2801
  const handleObjectPattern = (pattern) => {
2535
2802
  pattern.properties.forEach((prop) => {
2536
- if (t.isObjectProperty(prop) && t.isIdentifier(prop.value)) {
2803
+ if (t3.isObjectProperty(prop) && t3.isIdentifier(prop.value)) {
2537
2804
  trackVariable(prop.value.name);
2538
- } else if (t.isObjectProperty(prop) && t.isObjectPattern(prop.value)) {
2805
+ } else if (t3.isObjectProperty(prop) && t3.isObjectPattern(prop.value)) {
2539
2806
  handleObjectPattern(prop.value);
2540
- } else if (t.isObjectProperty(prop) && t.isAssignmentPattern(prop.value) && t.isIdentifier(prop.value.left)) {
2807
+ } else if (t3.isObjectProperty(prop) && t3.isAssignmentPattern(prop.value) && t3.isIdentifier(prop.value.left)) {
2541
2808
  trackVariable(prop.value.left.name);
2542
2809
  }
2543
2810
  });
@@ -2546,19 +2813,19 @@ var variableTrackingPlugin = (variables = /* @__PURE__ */ new Set()) => function
2546
2813
  if (parent.isForXStatement() || parent.isForStatement()) {
2547
2814
  return;
2548
2815
  }
2549
- if (t.isIdentifier(declarator.id)) {
2816
+ if (t3.isIdentifier(declarator.id)) {
2550
2817
  trackVariable(declarator.id.name);
2551
2818
  }
2552
- if (t.isObjectPattern(declarator.id)) {
2819
+ if (t3.isObjectPattern(declarator.id)) {
2553
2820
  handleObjectPattern(declarator.id);
2554
2821
  }
2555
- if (t.isArrayPattern(declarator.id)) {
2822
+ if (t3.isArrayPattern(declarator.id)) {
2556
2823
  declarator.id.elements.forEach((element) => {
2557
- if (t.isIdentifier(element)) {
2824
+ if (t3.isIdentifier(element)) {
2558
2825
  trackVariable(element.name);
2559
- } else if (t.isRestElement(element) && t.isIdentifier(element.argument)) {
2826
+ } else if (t3.isRestElement(element) && t3.isIdentifier(element.argument)) {
2560
2827
  trackVariable(element.argument.name);
2561
- } else if (t.isAssignmentPattern(element) && t.isIdentifier(element.left)) {
2828
+ } else if (t3.isAssignmentPattern(element) && t3.isIdentifier(element.left)) {
2562
2829
  trackVariable(element.left.name);
2563
2830
  }
2564
2831
  });
@@ -2602,12 +2869,15 @@ function compile(code) {
2602
2869
  let output = Babel.transform(code, {
2603
2870
  parserOpts: {
2604
2871
  allowReturnOutsideFunction: true,
2605
- allowAwaitOutsideFunction: true,
2606
- startLine: -1
2872
+ allowAwaitOutsideFunction: true
2607
2873
  },
2608
2874
  presets: ["typescript"],
2609
2875
  plugins: [
2610
2876
  JSXNewLines.babelPlugin,
2877
+ htmlToMarkdownPlugin,
2878
+ // Convert simple HTML to markdown first
2879
+ jsxUndefinedVarsPlugin,
2880
+ // Must run BEFORE JSX transform
2611
2881
  [
2612
2882
  jsxPlugin,
2613
2883
  {
@@ -2626,46 +2896,52 @@ function compile(code) {
2626
2896
  });
2627
2897
  const variables = /* @__PURE__ */ new Set();
2628
2898
  const toolCalls = /* @__PURE__ */ new Map();
2899
+ const codeWithMarkers = output.code;
2629
2900
  output = Babel.transform(output.code, {
2630
2901
  ...DEFAULT_TRANSFORM_OPTIONS,
2631
2902
  parserOpts: {
2632
- ...DEFAULT_TRANSFORM_OPTIONS.parserOpts,
2633
- startLine: -1
2903
+ ...DEFAULT_TRANSFORM_OPTIONS.parserOpts
2634
2904
  },
2635
2905
  plugins: [
2636
2906
  lineTrackingBabelPlugin,
2637
2907
  replaceCommentBabelPlugin,
2638
2908
  variableTrackingPlugin(variables),
2639
2909
  toolCallTrackingPlugin(toolCalls)
2640
- ]
2910
+ ],
2911
+ retainLines: true
2641
2912
  });
2642
2913
  let outputCode = output.code;
2643
2914
  outputCode = AsyncIterator.postProcessing(outputCode);
2644
2915
  outputCode = JSXNewLines.postProcessing(outputCode);
2645
2916
  return {
2646
2917
  code: outputCode,
2918
+ codeWithMarkers,
2919
+ // Code from before second transform, still has literal markers
2647
2920
  map: output.map,
2648
2921
  variables,
2649
2922
  toolCalls
2650
2923
  };
2651
2924
  }
2652
2925
 
2653
- // src/vm.ts
2654
- var IS_NODE = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
2655
- var _a;
2656
- var IS_CI = typeof process !== "undefined" && !!((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.CI);
2657
- var _a2;
2658
- var VM_DRIVER = (typeof process !== "undefined" && ((_a2 = process == null ? void 0 : process.env) == null ? void 0 : _a2.VM_DRIVER)) ?? (IS_CI ? "node" : "isolated-vm");
2659
- var CAN_USE_ISOLATED_VM = IS_NODE && VM_DRIVER === "isolated-vm";
2660
- var MAX_VM_EXECUTION_TIME = 6e4;
2661
- var requireEsm = async (id) => {
2662
- if (typeof globalThis.window === "undefined" && typeof globalThis.require !== "undefined") {
2663
- return eval("require")(id);
2664
- } else {
2665
- return await import(id).then((m) => m.default ?? m);
2926
+ // src/quickjs-variant.ts
2927
+ var getVariant = async () => {
2928
+ const module = await import("@jitl/quickjs-singlefile-browser-release-sync");
2929
+ return module.default;
2930
+ };
2931
+ var BundledReleaseSyncVariant = {
2932
+ type: "sync",
2933
+ importFFI: async () => {
2934
+ const variant = await getVariant();
2935
+ return variant.importFFI();
2936
+ },
2937
+ importModuleLoader: async () => {
2938
+ const variant = await getVariant();
2939
+ return variant.importModuleLoader();
2666
2940
  }
2667
2941
  };
2668
- var getIsolatedVm = async () => await requireEsm("isolated-vm");
2942
+
2943
+ // src/vm.ts
2944
+ var MAX_VM_EXECUTION_TIME = 6e4;
2669
2945
  var NO_TRACKING = [
2670
2946
  Identifiers.CommentFnIdentifier,
2671
2947
  Identifiers.ToolCallTrackerFnIdentifier,
@@ -2688,7 +2964,7 @@ function getCompiledCode(code, traces = []) {
2688
2964
  }
2689
2965
  }
2690
2966
  async function runAsyncFunction(context, code, traces = [], signal = null, timeout = MAX_VM_EXECUTION_TIME) {
2691
- var _a3;
2967
+ var _a, _b, _c, _d, _e, _f, _g;
2692
2968
  const transformed = getCompiledCode(code, traces);
2693
2969
  const lines_executed = /* @__PURE__ */ new Map();
2694
2970
  const variables = {};
@@ -2702,76 +2978,714 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
2702
2978
  sourceRoot: transformed.map.sourceRoot
2703
2979
  });
2704
2980
  context ??= {};
2705
- for (const name of transformed.variables) {
2981
+ for (const name of Array.from(transformed.variables)) {
2706
2982
  delete context[name];
2707
2983
  }
2708
- context[Identifiers.CommentFnIdentifier] = (comment, line) => traces.push({ type: "comment", comment, line, started_at: Date.now() });
2709
- context[Identifiers.LineTrackingFnIdentifier] = (line) => {
2710
- lines_executed.set(line, (lines_executed.get(line) ?? 0) + 1);
2711
- };
2712
- context[Identifiers.JSXFnIdentifier] = (tool, props, ...children) => createJsxComponent({
2713
- type: tool,
2714
- props,
2715
- children
2716
- });
2717
- context[Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
2718
- if (NO_TRACKING.includes(name)) {
2719
- return;
2720
- }
2721
- variables[name] = () => {
2722
- try {
2723
- const value = getter();
2724
- if (typeof value === "function") {
2725
- return "[[non-primitive]]";
2984
+ let DRIVER = "quickjs";
2985
+ if (typeof process !== "undefined" && ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.USE_QUICKJS) === "false") {
2986
+ DRIVER = "node";
2987
+ }
2988
+ if (DRIVER === "quickjs") {
2989
+ try {
2990
+ context[Identifiers.CommentFnIdentifier] = (comment, line) => {
2991
+ if (comment.includes("__LLMZ_USER_CODE_START__") || comment.includes("__LLMZ_USER_CODE_END__")) {
2992
+ return;
2993
+ }
2994
+ traces.push({ type: "comment", comment, line, started_at: Date.now() });
2995
+ };
2996
+ const codeWithMarkers = transformed.codeWithMarkers || transformed.code;
2997
+ const markerLines = codeWithMarkers.split("\n");
2998
+ const USER_CODE_START_MARKER2 = "/* __LLMZ_USER_CODE_START__ */";
2999
+ let userCodeStartLine = -1;
3000
+ for (let i = 0; i < markerLines.length; i++) {
3001
+ if ((_b = markerLines[i]) == null ? void 0 : _b.includes(USER_CODE_START_MARKER2)) {
3002
+ userCodeStartLine = i + 1;
3003
+ break;
2726
3004
  }
2727
- return value;
2728
- } catch {
2729
- return "[[non-primitive]]";
2730
3005
  }
2731
- };
2732
- };
2733
- let currentToolCall;
2734
- context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
2735
- var _a4;
2736
- const temp = Signals.maybeDeserializeError(outputOrError == null ? void 0 : outputOrError.message);
2737
- if (type === "end" && temp instanceof SnapshotSignal && (temp == null ? void 0 : temp.toolCall)) {
2738
- currentToolCall = {
2739
- ...temp.toolCall,
2740
- assignment: (_a4 = transformed.toolCalls.get(callId)) == null ? void 0 : _a4.assignment
3006
+ context[Identifiers.LineTrackingFnIdentifier] = (line) => {
3007
+ const originalLine = consumer.originalPositionFor({
3008
+ line,
3009
+ column: 0
3010
+ });
3011
+ const mappedLine = originalLine.line ?? line;
3012
+ const userCodeLine = Math.max(1, mappedLine - userCodeStartLine);
3013
+ lines_executed.set(userCodeLine, (lines_executed.get(userCodeLine) ?? 0) + 1);
2741
3014
  };
3015
+ context[Identifiers.JSXFnIdentifier] = (tool, props, ...children) => createJsxComponent({
3016
+ type: tool,
3017
+ props,
3018
+ children
3019
+ });
3020
+ context[Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
3021
+ if (NO_TRACKING.includes(name)) {
3022
+ return;
3023
+ }
3024
+ variables[name] = () => {
3025
+ try {
3026
+ const value = getter();
3027
+ if (typeof value === "function") {
3028
+ return "[[non-primitive]]";
3029
+ }
3030
+ return value;
3031
+ } catch {
3032
+ return "[[non-primitive]]";
3033
+ }
3034
+ };
3035
+ };
3036
+ let currentToolCall;
3037
+ context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
3038
+ var _a2;
3039
+ const temp = Signals.maybeDeserializeError(outputOrError == null ? void 0 : outputOrError.message);
3040
+ if (type === "end" && temp instanceof SnapshotSignal && (temp == null ? void 0 : temp.toolCall)) {
3041
+ currentToolCall = {
3042
+ ...temp.toolCall,
3043
+ assignment: (_a2 = transformed.toolCalls.get(callId)) == null ? void 0 : _a2.assignment
3044
+ };
3045
+ }
3046
+ };
3047
+ context[Identifiers.ConsoleObjIdentifier] = {
3048
+ log: (...args) => {
3049
+ const message = args.shift();
3050
+ traces.push({ type: "log", message, args, started_at: Date.now() });
3051
+ }
3052
+ };
3053
+ context[Identifiers.AsyncIterYieldFnIdentifier] = async function(value) {
3054
+ const startedAt = Date.now();
3055
+ try {
3056
+ if (typeof value.type !== "string" || value.type.trim().length === 0) {
3057
+ throw new Error("A yield statement must yield a valid tool");
3058
+ }
3059
+ const toolName = Object.keys(context).find((x) => x.toUpperCase() === value.type.toUpperCase());
3060
+ if (!toolName) {
3061
+ throw new Error(`Yield tool "${value.type}", but tool is not found`);
3062
+ }
3063
+ await context[toolName](value);
3064
+ } finally {
3065
+ traces.push({ type: "yield", value, started_at: startedAt, ended_at: Date.now() });
3066
+ }
3067
+ };
3068
+ const QuickJS = await newQuickJSWASMModuleFromVariant(BundledReleaseSyncVariant);
3069
+ const runtime = QuickJS.newRuntime();
3070
+ runtime.setMemoryLimit(128 * 1024 * 1024);
3071
+ const startTime = Date.now();
3072
+ const timeoutHandler = shouldInterruptAfterDeadline(startTime + timeout);
3073
+ runtime.setInterruptHandler(() => {
3074
+ if (signal == null ? void 0 : signal.aborted) {
3075
+ return true;
3076
+ }
3077
+ return timeoutHandler(runtime);
3078
+ });
3079
+ const vm = runtime.newContext();
3080
+ const trackedProperties = /* @__PURE__ */ new Set();
3081
+ const referenceProperties = /* @__PURE__ */ new Set();
3082
+ const pendingPromises = [];
3083
+ const toVmValue = (value) => {
3084
+ var _a2;
3085
+ if (typeof value === "string") {
3086
+ return vm.newString(value);
3087
+ } else if (typeof value === "number") {
3088
+ return vm.newNumber(value);
3089
+ } else if (typeof value === "boolean") {
3090
+ return value ? vm.true : vm.false;
3091
+ } else if (value === null) {
3092
+ return vm.null;
3093
+ } else if (value === void 0) {
3094
+ return vm.undefined;
3095
+ } else if (Array.isArray(value)) {
3096
+ const items = value.map((item) => {
3097
+ if (typeof item === "string") {
3098
+ return JSON.stringify(item);
3099
+ } else if (typeof item === "number" || typeof item === "boolean") {
3100
+ return String(item);
3101
+ } else if (item === null) {
3102
+ return "null";
3103
+ } else if (item === void 0) {
3104
+ return "undefined";
3105
+ } else if (typeof item === "object") {
3106
+ return JSON.stringify(item);
3107
+ }
3108
+ return "undefined";
3109
+ });
3110
+ const arrayLiteral = `[${items.join(",")}]`;
3111
+ const result = vm.evalCode(arrayLiteral);
3112
+ if ("error" in result) {
3113
+ (_a2 = result.error) == null ? void 0 : _a2.dispose();
3114
+ return vm.undefined;
3115
+ }
3116
+ const arrHandle = result.value;
3117
+ return arrHandle;
3118
+ } else if (typeof value === "object") {
3119
+ const obj = vm.newObject();
3120
+ for (const [k, v] of Object.entries(value)) {
3121
+ if (typeof v !== "function") {
3122
+ const propHandle = toVmValue(v);
3123
+ vm.setProp(obj, k, propHandle);
3124
+ if (propHandle !== vm.true && propHandle !== vm.false && propHandle !== vm.null && propHandle !== vm.undefined) {
3125
+ propHandle.dispose();
3126
+ }
3127
+ }
3128
+ }
3129
+ return obj;
3130
+ }
3131
+ return vm.undefined;
3132
+ };
3133
+ const bridgeFunction = (fn, _fnName = "anonymous") => {
3134
+ return (...argHandles) => {
3135
+ const args = argHandles.map((h) => vm.dump(h));
3136
+ try {
3137
+ const result = fn(...args);
3138
+ if (result && typeof result.then === "function") {
3139
+ const promise = vm.newPromise();
3140
+ pendingPromises.push({
3141
+ hostPromise: result,
3142
+ deferredPromise: promise
3143
+ });
3144
+ void promise.settled.then(() => {
3145
+ if (runtime.alive) {
3146
+ runtime.executePendingJobs();
3147
+ }
3148
+ });
3149
+ return promise.handle;
3150
+ }
3151
+ return toVmValue(result);
3152
+ } catch (err) {
3153
+ const serialized = err instanceof Error ? err.message : String(err);
3154
+ throw new Error(serialized);
3155
+ }
3156
+ };
3157
+ };
3158
+ try {
3159
+ for (const [key, value] of Object.entries(context)) {
3160
+ const descriptor = Object.getOwnPropertyDescriptor(context, key);
3161
+ if (descriptor && (descriptor.get || descriptor.set)) {
3162
+ referenceProperties.add(key);
3163
+ trackedProperties.add(key);
3164
+ let getterCode = "undefined";
3165
+ if (descriptor.get) {
3166
+ const getterBridge = vm.newFunction(`get_${key}`, () => {
3167
+ try {
3168
+ const hostValue = context[key];
3169
+ return toVmValue(hostValue);
3170
+ } catch (err) {
3171
+ const serialized = err instanceof Error ? err.message : String(err);
3172
+ throw new Error(serialized);
3173
+ }
3174
+ });
3175
+ const getterName = `__getter_${key}__`;
3176
+ vm.setProp(vm.global, getterName, getterBridge);
3177
+ getterBridge.dispose();
3178
+ getterCode = getterName;
3179
+ }
3180
+ let setterCode = "undefined";
3181
+ if (descriptor.set) {
3182
+ const setterBridge = vm.newFunction(`set_${key}`, (valueHandle) => {
3183
+ try {
3184
+ const jsValue = vm.dump(valueHandle);
3185
+ context[key] = jsValue;
3186
+ return vm.undefined;
3187
+ } catch (err) {
3188
+ const serialized = err instanceof Error ? err.message : String(err);
3189
+ throw new Error(serialized);
3190
+ }
3191
+ });
3192
+ const setterName = `__setter_${key}__`;
3193
+ vm.setProp(vm.global, setterName, setterBridge);
3194
+ setterBridge.dispose();
3195
+ setterCode = setterName;
3196
+ }
3197
+ const definePropertyCode = `
3198
+ Object.defineProperty(globalThis, '${key}', {
3199
+ enumerable: true,
3200
+ configurable: ${descriptor.configurable !== false},
3201
+ get: ${getterCode},
3202
+ set: ${setterCode}
3203
+ });
3204
+ `;
3205
+ const result = vm.evalCode(definePropertyCode);
3206
+ if ("error" in result) {
3207
+ (_c = result.error) == null ? void 0 : _c.dispose();
3208
+ } else {
3209
+ result.value.dispose();
3210
+ }
3211
+ continue;
3212
+ }
3213
+ if (typeof value === "function") {
3214
+ const fnHandle = vm.newFunction(key, bridgeFunction(value, key));
3215
+ vm.setProp(vm.global, key, fnHandle);
3216
+ fnHandle.dispose();
3217
+ } else if (Array.isArray(value)) {
3218
+ trackedProperties.add(key);
3219
+ const arrayHandle = toVmValue(value);
3220
+ vm.setProp(vm.global, key, arrayHandle);
3221
+ const shouldDispose = arrayHandle !== vm.true && arrayHandle !== vm.false && arrayHandle !== vm.null && arrayHandle !== vm.undefined;
3222
+ if (shouldDispose) {
3223
+ arrayHandle.dispose();
3224
+ }
3225
+ } else if (typeof value === "object" && value !== null) {
3226
+ trackedProperties.add(key);
3227
+ const objHandle = vm.newObject();
3228
+ const props = /* @__PURE__ */ new Set([...Object.keys(value), ...Object.getOwnPropertyNames(value)]);
3229
+ const getterSetterProps = [];
3230
+ for (const prop of props) {
3231
+ const propDescriptor = Object.getOwnPropertyDescriptor(value, prop);
3232
+ if (propDescriptor && (propDescriptor.get || propDescriptor.set)) {
3233
+ referenceProperties.add(`${key}.${prop}`);
3234
+ getterSetterProps.push({ prop, descriptor: propDescriptor });
3235
+ } else if (typeof value[prop] === "function") {
3236
+ const propFnHandle = vm.newFunction(prop, bridgeFunction(value[prop], `${key}.${prop}`));
3237
+ vm.setProp(objHandle, prop, propFnHandle);
3238
+ propFnHandle.dispose();
3239
+ } else {
3240
+ const propHandle = toVmValue(value[prop]);
3241
+ vm.setProp(objHandle, prop, propHandle);
3242
+ const shouldDispose = propHandle !== vm.true && propHandle !== vm.false && propHandle !== vm.null && propHandle !== vm.undefined;
3243
+ if (shouldDispose) {
3244
+ propHandle.dispose();
3245
+ }
3246
+ }
3247
+ }
3248
+ vm.setProp(vm.global, key, objHandle);
3249
+ objHandle.dispose();
3250
+ for (const { prop, descriptor: descriptor2 } of getterSetterProps) {
3251
+ let getterCode = "undefined";
3252
+ if (descriptor2.get) {
3253
+ const getterBridge = vm.newFunction(`get_${prop}`, () => {
3254
+ try {
3255
+ const hostValue = context[key][prop];
3256
+ return toVmValue(hostValue);
3257
+ } catch (err) {
3258
+ const serialized = err instanceof Error ? err.message : String(err);
3259
+ throw new Error(serialized);
3260
+ }
3261
+ });
3262
+ const getterName = `__getter_${key}_${prop}__`;
3263
+ vm.setProp(vm.global, getterName, getterBridge);
3264
+ getterBridge.dispose();
3265
+ getterCode = getterName;
3266
+ }
3267
+ let setterCode = "undefined";
3268
+ if (descriptor2.set) {
3269
+ const setterBridge = vm.newFunction(`set_${prop}`, (valueHandle) => {
3270
+ try {
3271
+ const jsValue = vm.dump(valueHandle);
3272
+ context[key][prop] = jsValue;
3273
+ return vm.undefined;
3274
+ } catch (err) {
3275
+ const serialized = err instanceof Error ? err.message : String(err);
3276
+ throw new Error(serialized);
3277
+ }
3278
+ });
3279
+ const setterName = `__setter_${key}_${prop}__`;
3280
+ vm.setProp(vm.global, setterName, setterBridge);
3281
+ setterBridge.dispose();
3282
+ setterCode = setterName;
3283
+ }
3284
+ const definePropertyCode = `
3285
+ Object.defineProperty(${key}, '${prop}', {
3286
+ enumerable: true,
3287
+ configurable: ${descriptor2.configurable !== false},
3288
+ get: ${getterCode},
3289
+ set: ${setterCode}
3290
+ });
3291
+ `;
3292
+ const result = vm.evalCode(definePropertyCode);
3293
+ if ("error" in result) {
3294
+ (_d = result.error) == null ? void 0 : _d.dispose();
3295
+ } else {
3296
+ result.value.dispose();
3297
+ }
3298
+ }
3299
+ if (Object.isSealed(value)) {
3300
+ const sealResult = vm.evalCode(`Object.seal(globalThis['${key}']);`);
3301
+ if ("error" in sealResult) {
3302
+ (_e = sealResult.error) == null ? void 0 : _e.dispose();
3303
+ } else {
3304
+ sealResult.value.dispose();
3305
+ }
3306
+ }
3307
+ if (!Object.isExtensible(value)) {
3308
+ const preventResult = vm.evalCode(`Object.preventExtensions(globalThis['${key}']);`);
3309
+ if ("error" in preventResult) {
3310
+ (_f = preventResult.error) == null ? void 0 : _f.dispose();
3311
+ } else {
3312
+ preventResult.value.dispose();
3313
+ }
3314
+ }
3315
+ } else {
3316
+ trackedProperties.add(key);
3317
+ const valueHandle = toVmValue(value);
3318
+ vm.setProp(vm.global, key, valueHandle);
3319
+ const shouldDispose = valueHandle !== vm.true && valueHandle !== vm.false && valueHandle !== vm.null && valueHandle !== vm.undefined;
3320
+ if (shouldDispose) {
3321
+ valueHandle.dispose();
3322
+ }
3323
+ }
3324
+ }
3325
+ const varTrackFnHandle = vm.newFunction(
3326
+ Identifiers.VariableTrackingFnIdentifier,
3327
+ (nameHandle, getterHandle) => {
3328
+ var _a2;
3329
+ const name = vm.getString(nameHandle);
3330
+ if (NO_TRACKING.includes(name)) {
3331
+ return;
3332
+ }
3333
+ try {
3334
+ const valueResult = vm.callFunction(getterHandle, vm.undefined);
3335
+ if ("error" in valueResult) {
3336
+ variables[name] = "[[non-primitive]]";
3337
+ (_a2 = valueResult.error) == null ? void 0 : _a2.dispose();
3338
+ return;
3339
+ }
3340
+ const value = vm.dump(valueResult.value);
3341
+ valueResult.value.dispose();
3342
+ if (typeof value === "function" || typeof value === "string" && value.includes("=>")) {
3343
+ variables[name] = "[[non-primitive]]";
3344
+ } else {
3345
+ variables[name] = value;
3346
+ }
3347
+ } catch {
3348
+ variables[name] = "[[non-primitive]]";
3349
+ }
3350
+ }
3351
+ );
3352
+ vm.setProp(vm.global, Identifiers.VariableTrackingFnIdentifier, varTrackFnHandle);
3353
+ varTrackFnHandle.dispose();
3354
+ const scriptCode = `
3355
+ "use strict";
3356
+ globalThis.__llmz_result = undefined;
3357
+ globalThis.__llmz_result_set = false;
3358
+ globalThis.__llmz_error = null;
3359
+ globalThis.__llmz_error_stack = null;
3360
+ globalThis.__llmz_yields = [];
3361
+
3362
+ (async () => {
3363
+ try {
3364
+ async function* __fn__() {
3365
+ ${transformed.code}
2742
3366
  }
2743
- };
2744
- context[Identifiers.ConsoleObjIdentifier] = {
2745
- log: (...args) => {
2746
- const message = args.shift();
2747
- traces.push({ type: "log", message, args, started_at: Date.now() });
2748
- }
2749
- };
2750
- context[Identifiers.AsyncIterYieldFnIdentifier] = async function(value) {
2751
- const startedAt = Date.now();
2752
- try {
2753
- if (typeof value.type !== "string" || value.type.trim().length === 0) {
2754
- throw new Error("A yield statement must yield a valid tool");
2755
- }
2756
- const toolName = Object.keys(context).find((x) => x.toUpperCase() === value.type.toUpperCase());
2757
- if (!toolName) {
2758
- throw new Error(`Yield tool "${value.type}", but tool is not found`);
3367
+
3368
+ const fn = __fn__();
3369
+ let iteration = 0;
3370
+ const maxIterations = 10000; // Safety limit
3371
+
3372
+ while (iteration < maxIterations) {
3373
+ const { value, done } = await fn.next();
3374
+
3375
+ if (done) {
3376
+ globalThis.__llmz_result = value;
3377
+ globalThis.__llmz_result_set = true;
3378
+ break;
2759
3379
  }
2760
- await context[toolName](value);
2761
- } finally {
2762
- traces.push({ type: "yield", value, started_at: startedAt, ended_at: Date.now() });
3380
+
3381
+ // Store yielded value
3382
+ globalThis.__llmz_yields.push(value);
3383
+
3384
+ // Call yield handler
3385
+ await ${Identifiers.AsyncIterYieldFnIdentifier}(value);
3386
+
3387
+ iteration++;
2763
3388
  }
2764
- };
2765
- let DRIVER = CAN_USE_ISOLATED_VM ? "isolated-vm" : "node";
2766
- let isolatedVm;
2767
- if (DRIVER === "isolated-vm") {
2768
- try {
2769
- isolatedVm = await getIsolatedVm();
2770
- } catch {
3389
+
3390
+ if (iteration >= maxIterations) {
3391
+ throw new Error('Maximum iterations exceeded');
3392
+ }
3393
+ } catch (err) {
3394
+ // Store both the error message (which may contain serialized signal data)
3395
+ // and the stack trace from QuickJS
3396
+ // If err is a string (as thrown from promise rejection), use it directly
3397
+ // Otherwise extract the message property
3398
+ globalThis.__llmz_error = typeof err === 'string' ? err : String(err.message || err || '');
3399
+ // Force the stack to be converted to a string in QuickJS context
3400
+ globalThis.__llmz_error_stack = '' + (err.stack || '');
3401
+ }
3402
+ })();
3403
+ `.trim();
3404
+ const copyBackContextFromVM = () => {
3405
+ for (const key of trackedProperties) {
3406
+ if (referenceProperties.has(key)) {
3407
+ continue;
3408
+ }
3409
+ try {
3410
+ const valueResult = vm.evalCode(`globalThis['${key}']`);
3411
+ const vmValue = vm.dump(valueResult.unwrap());
3412
+ valueResult.unwrap().dispose();
3413
+ try {
3414
+ context[key] = vmValue;
3415
+ } catch {
3416
+ }
3417
+ } catch {
3418
+ }
3419
+ }
3420
+ };
3421
+ const execResult = vm.evalCode(scriptCode, "<quickjs>");
3422
+ if ("error" in execResult) {
3423
+ if (execResult.error) {
3424
+ const err = vm.dump(execResult.error);
3425
+ execResult.error.dispose();
3426
+ throw new Error((err == null ? void 0 : err.message) || "Execution failed");
3427
+ }
3428
+ throw new Error("Execution failed");
3429
+ }
3430
+ execResult.value.dispose();
3431
+ const maxIterations = 1e3;
3432
+ let iteration = 0;
3433
+ while (iteration < maxIterations) {
3434
+ let hasJobs = false;
3435
+ const maxJobs = 1e4;
3436
+ for (let i = 0; i < maxJobs; i++) {
3437
+ const pending = (_g = runtime.executePendingJobs) == null ? void 0 : _g.call(runtime, -1);
3438
+ const jobCount = pending === void 0 ? 0 : pending.unwrap();
3439
+ if (jobCount <= 0)
3440
+ break;
3441
+ hasJobs = true;
3442
+ }
3443
+ const currentPromises = [...pendingPromises];
3444
+ pendingPromises.length = 0;
3445
+ if (currentPromises.length > 0) {
3446
+ if (signal == null ? void 0 : signal.aborted) {
3447
+ const reason = signal.reason;
3448
+ const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3449
+ for (const { deferredPromise } of currentPromises) {
3450
+ const errValue = vm.newString(abortMessage);
3451
+ deferredPromise.reject(errValue);
3452
+ errValue.dispose();
3453
+ }
3454
+ runtime.executePendingJobs();
3455
+ break;
3456
+ }
3457
+ let abortListener = null;
3458
+ if (signal) {
3459
+ abortListener = () => {
3460
+ const reason = signal.reason;
3461
+ const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3462
+ for (const { deferredPromise } of currentPromises) {
3463
+ const errValue = vm.newString(abortMessage);
3464
+ deferredPromise.reject(errValue);
3465
+ errValue.dispose();
3466
+ }
3467
+ runtime.executePendingJobs();
3468
+ };
3469
+ signal.addEventListener("abort", abortListener);
3470
+ }
3471
+ try {
3472
+ await Promise.all(
3473
+ currentPromises.map(async ({ hostPromise, deferredPromise }) => {
3474
+ if (signal == null ? void 0 : signal.aborted) {
3475
+ return;
3476
+ }
3477
+ try {
3478
+ const value = await hostPromise;
3479
+ if (signal == null ? void 0 : signal.aborted) {
3480
+ return;
3481
+ }
3482
+ const vmValue = toVmValue(value);
3483
+ deferredPromise.resolve(vmValue);
3484
+ } catch (err) {
3485
+ if (signal == null ? void 0 : signal.aborted) {
3486
+ return;
3487
+ }
3488
+ const serialized = err instanceof Error ? err.message : String(err);
3489
+ const createErrorResult = vm.evalCode(`new Error(${JSON.stringify(serialized)})`);
3490
+ if ("error" in createErrorResult) {
3491
+ const errValue = vm.newString(serialized);
3492
+ deferredPromise.reject(errValue);
3493
+ errValue.dispose();
3494
+ } else {
3495
+ const errorHandle = createErrorResult.value;
3496
+ deferredPromise.reject(errorHandle);
3497
+ errorHandle.dispose();
3498
+ }
3499
+ }
3500
+ })
3501
+ );
3502
+ } finally {
3503
+ if (signal && abortListener) {
3504
+ signal.removeEventListener("abort", abortListener);
3505
+ }
3506
+ }
3507
+ runtime.executePendingJobs();
3508
+ if (signal == null ? void 0 : signal.aborted) {
3509
+ break;
3510
+ }
3511
+ }
3512
+ if (!hasJobs && pendingPromises.length === 0) {
3513
+ break;
3514
+ }
3515
+ iteration++;
3516
+ }
3517
+ if (iteration >= maxIterations) {
3518
+ throw new Error("Maximum event loop iterations exceeded");
3519
+ }
3520
+ const errorResult = vm.evalCode("globalThis.__llmz_error");
3521
+ const errorValue = vm.dump(errorResult.unwrap());
3522
+ errorResult.unwrap().dispose();
3523
+ if (signal == null ? void 0 : signal.aborted) {
3524
+ const reason = signal.reason;
3525
+ if (reason instanceof Error) {
3526
+ throw reason;
3527
+ }
3528
+ throw new Error(reason ? String(reason) : "Execution was aborted");
3529
+ }
3530
+ if (errorValue !== null && errorValue !== "") {
3531
+ try {
3532
+ copyBackContextFromVM();
3533
+ } catch {
3534
+ }
3535
+ const errorStackResult = vm.evalCode("globalThis.__llmz_error_stack");
3536
+ const errorStack = vm.dump(errorStackResult.unwrap()) || "";
3537
+ errorStackResult.unwrap().dispose();
3538
+ const deserializedError = Signals.maybeDeserializeError(errorValue);
3539
+ if (deserializedError instanceof VMSignal) {
3540
+ deserializedError.stack = errorStack;
3541
+ throw deserializedError;
3542
+ }
3543
+ const error = new Error(errorValue);
3544
+ error.stack = errorStack;
3545
+ throw error;
3546
+ }
3547
+ copyBackContextFromVM();
3548
+ const resultSetResult = vm.evalCode("globalThis.__llmz_result_set");
3549
+ const resultSet = vm.dump(resultSetResult.unwrap());
3550
+ resultSetResult.unwrap().dispose();
3551
+ let returnValue = void 0;
3552
+ if (resultSet) {
3553
+ const resultResult = vm.evalCode("globalThis.__llmz_result");
3554
+ returnValue = vm.dump(resultResult.unwrap());
3555
+ resultResult.unwrap().dispose();
3556
+ }
3557
+ returnValue = Signals.maybeDeserializeError(returnValue);
3558
+ return {
3559
+ success: true,
3560
+ variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3561
+ signal: returnValue instanceof VMSignal ? returnValue : void 0,
3562
+ lines_executed: Array.from(lines_executed),
3563
+ return_value: returnValue
3564
+ };
3565
+ } catch (err) {
3566
+ if (signal == null ? void 0 : signal.aborted) {
3567
+ const reason = signal.reason;
3568
+ const abortError = reason instanceof Error ? reason : new Error(reason ? String(reason) : "Execution was aborted");
3569
+ return handleErrorQuickJS(
3570
+ abortError,
3571
+ code,
3572
+ consumer,
3573
+ traces,
3574
+ variables,
3575
+ lines_executed,
3576
+ userCodeStartLine,
3577
+ currentToolCall
3578
+ );
3579
+ }
3580
+ await Promise.all(
3581
+ pendingPromises.map(async ({ hostPromise, deferredPromise }) => {
3582
+ try {
3583
+ const value = await hostPromise;
3584
+ const vmValue = toVmValue(value);
3585
+ deferredPromise.resolve(vmValue);
3586
+ } catch (err2) {
3587
+ const serialized = err2 instanceof Error ? err2.message : String(err2);
3588
+ const errValue = vm.newString(serialized);
3589
+ deferredPromise.reject(errValue);
3590
+ }
3591
+ })
3592
+ ).catch(() => {
3593
+ });
3594
+ return handleErrorQuickJS(
3595
+ err,
3596
+ code,
3597
+ consumer,
3598
+ traces,
3599
+ variables,
3600
+ lines_executed,
3601
+ userCodeStartLine,
3602
+ currentToolCall
3603
+ );
3604
+ } finally {
3605
+ try {
3606
+ vm.dispose();
3607
+ } catch {
3608
+ }
3609
+ try {
3610
+ runtime.dispose();
3611
+ } catch {
3612
+ }
3613
+ }
3614
+ } catch (quickjsError) {
3615
+ const debugInfo = {
3616
+ error: (quickjsError == null ? void 0 : quickjsError.message) || String(quickjsError),
3617
+ errorStack: quickjsError == null ? void 0 : quickjsError.stack,
3618
+ wasmSource: BundledReleaseSyncVariant._wasmSource,
3619
+ wasmLoadedSuccessfully: BundledReleaseSyncVariant._wasmLoadedSuccessfully,
3620
+ wasmSize: BundledReleaseSyncVariant._wasmSize,
3621
+ wasmLoadError: BundledReleaseSyncVariant._wasmLoadError,
3622
+ nodeVersion: typeof process !== "undefined" && process.version ? process.version : "undefined",
3623
+ platform: typeof process !== "undefined" && process.platform ? process.platform : "undefined"
3624
+ };
3625
+ console.warn("QuickJS failed to load, falling back to node driver.");
3626
+ console.warn("Error:", (quickjsError == null ? void 0 : quickjsError.message) || quickjsError);
3627
+ console.warn("Debug info:", JSON.stringify(debugInfo, null, 2));
2771
3628
  DRIVER = "node";
2772
3629
  }
2773
3630
  }
2774
3631
  if (DRIVER === "node") {
3632
+ context[Identifiers.CommentFnIdentifier] = (comment, line) => traces.push({ type: "comment", comment, line, started_at: Date.now() });
3633
+ context[Identifiers.LineTrackingFnIdentifier] = (line) => {
3634
+ lines_executed.set(line, (lines_executed.get(line) ?? 0) + 1);
3635
+ };
3636
+ context[Identifiers.JSXFnIdentifier] = (tool, props, ...children) => createJsxComponent({
3637
+ type: tool,
3638
+ props,
3639
+ children
3640
+ });
3641
+ context[Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
3642
+ if (NO_TRACKING.includes(name)) {
3643
+ return;
3644
+ }
3645
+ variables[name] = () => {
3646
+ try {
3647
+ const value = getter();
3648
+ if (typeof value === "function") {
3649
+ return "[[non-primitive]]";
3650
+ }
3651
+ return value;
3652
+ } catch {
3653
+ return "[[non-primitive]]";
3654
+ }
3655
+ };
3656
+ };
3657
+ let currentToolCall;
3658
+ context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
3659
+ var _a2;
3660
+ const temp = Signals.maybeDeserializeError(outputOrError == null ? void 0 : outputOrError.message);
3661
+ if (type === "end" && temp instanceof SnapshotSignal && (temp == null ? void 0 : temp.toolCall)) {
3662
+ currentToolCall = {
3663
+ ...temp.toolCall,
3664
+ assignment: (_a2 = transformed.toolCalls.get(callId)) == null ? void 0 : _a2.assignment
3665
+ };
3666
+ }
3667
+ };
3668
+ context[Identifiers.ConsoleObjIdentifier] = {
3669
+ log: (...args) => {
3670
+ const message = args.shift();
3671
+ traces.push({ type: "log", message, args, started_at: Date.now() });
3672
+ }
3673
+ };
3674
+ context[Identifiers.AsyncIterYieldFnIdentifier] = async function(value) {
3675
+ const startedAt = Date.now();
3676
+ try {
3677
+ if (typeof value.type !== "string" || value.type.trim().length === 0) {
3678
+ throw new Error("A yield statement must yield a valid tool");
3679
+ }
3680
+ const toolName = Object.keys(context).find((x) => x.toUpperCase() === value.type.toUpperCase());
3681
+ if (!toolName) {
3682
+ throw new Error(`Yield tool "${value.type}", but tool is not found`);
3683
+ }
3684
+ await context[toolName](value);
3685
+ } finally {
3686
+ traces.push({ type: "yield", value, started_at: startedAt, ended_at: Date.now() });
3687
+ }
3688
+ };
2775
3689
  const AsyncFunction = async function* () {
2776
3690
  }.constructor;
2777
3691
  return await (async () => {
@@ -2806,293 +3720,109 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
2806
3720
  lines_executed: Array.from(lines_executed),
2807
3721
  return_value: res
2808
3722
  };
2809
- }).catch((err) => handleError(err, code, consumer, traces, variables, lines_executed, currentToolCall, DRIVER)).catch((err) => handleCatch(err, traces, variables, lines_executed));
2810
- }
2811
- if (!isolatedVm) {
2812
- throw new Error("isolated-vm is not available");
2813
- }
2814
- const isolate = new isolatedVm.Isolate({ memoryLimit: 128 });
2815
- const isolatedContext = await isolate.createContext();
2816
- const jail = isolatedContext.global;
2817
- const trackedProperties = /* @__PURE__ */ new Set();
2818
- const referenceProperties = /* @__PURE__ */ new Set();
2819
- const abort = () => {
2820
- if (DRIVER === "isolated-vm") {
2821
- isolate.dispose();
2822
- isolatedContext.release();
2823
- }
2824
- };
2825
- if (signal) {
2826
- signal.addEventListener("abort", abort);
3723
+ }).catch((err) => handleErrorNode(err, code, consumer, traces, variables, lines_executed, currentToolCall)).catch((err) => handleCatch(err, traces, variables, lines_executed));
2827
3724
  }
2828
- await jail.set("global", jail.derefInto());
2829
- for (const key of Object.keys(context)) {
2830
- if (typeof context[key] === "function") {
2831
- await isolatedContext.evalClosure(
2832
- `global['${key}'] = (...args) => $0.applySyncPromise(null, args, {arguments: {copy: true}});`,
2833
- [async (...args) => new isolatedVm.ExternalCopy(await context[key](...args)).copyInto()],
2834
- {
2835
- arguments: { reference: true }
2836
- }
2837
- );
2838
- } else if (typeof context[key] === "object" && !((_a3 = Object.getOwnPropertyDescriptor(context, key)) == null ? void 0 : _a3.get)) {
2839
- try {
2840
- trackedProperties.add(key);
2841
- const initial = Array.isArray(context[key]) ? new Array(context[key].length) : {};
2842
- await jail.set(key, initial, { copy: true });
2843
- const props = /* @__PURE__ */ new Set([...Object.keys(context[key]), ...Object.getOwnPropertyNames(context[key])]);
2844
- for (const prop of props) {
2845
- try {
2846
- if (typeof context[key][prop] === "function") {
2847
- await isolatedContext.evalClosure(
2848
- `global['${key}']['${prop}'] = (...args) => $0.applySyncPromise(null, args, {arguments: {copy: true}});`,
2849
- [async (...args) => new isolatedVm.ExternalCopy(await context[key][prop](...args)).copyInto()],
2850
- {
2851
- arguments: { reference: true }
2852
- }
2853
- );
2854
- } else {
2855
- const descriptor = Object.getOwnPropertyDescriptor(context[key], prop);
2856
- if (descriptor && (descriptor.get || descriptor.set)) {
2857
- referenceProperties.add(`${key}.${prop}`);
2858
- await isolatedContext.evalClosure(
2859
- `Object.defineProperty(global['${key}'], '${prop}', {
2860
- get: () => $0.applySync(null, [], {arguments: {copy: true}}),
2861
- set: (value) => $1.applySync(null, [value], {arguments: {copy: true}})
2862
- });`,
2863
- [
2864
- () => context[key][prop],
2865
- (value) => {
2866
- context[key][prop] = value;
2867
- return value;
2868
- }
2869
- ],
2870
- { arguments: { reference: true } }
2871
- );
2872
- } else {
2873
- await isolatedContext.evalClosure(`global['${key}']['${prop}'] = $0;`, [context[key][prop]], {
2874
- arguments: { copy: true }
2875
- });
2876
- }
2877
- }
2878
- } catch (err) {
2879
- console.error(`Could not copy "${key}.${prop}" (typeof = ${typeof context[key][prop]}) to the sandbox`, err);
2880
- }
2881
- }
2882
- } catch (err) {
2883
- console.error(`Could not create object "${key}" (typeof = ${typeof context[key]}) in the sandbox`, err);
2884
- }
2885
- } else {
2886
- try {
2887
- const descriptor = Object.getOwnPropertyDescriptor(context, key);
2888
- if (descriptor && (descriptor.get || descriptor.set)) {
2889
- referenceProperties.add(key);
2890
- await isolatedContext.evalClosure(
2891
- `Object.defineProperty(global, '${key}', {
2892
- get: () => $0.applySync(null, [], {arguments: {copy: true}}),
2893
- set: (value) => $1.applySync(null, [value], {arguments: {copy: true}})
2894
- });`,
2895
- [
2896
- () => context[key],
2897
- (value) => {
2898
- context[key] = value;
2899
- return value;
2900
- }
2901
- ],
2902
- { arguments: { reference: true } }
2903
- );
2904
- } else {
2905
- await jail.set(key, context[key], { copy: true });
2906
- }
2907
- trackedProperties.add(key);
2908
- } catch (err) {
2909
- console.error(`Could not copy "${key}" to the sandbox (typeof = ${typeof context[key]})`, err);
2910
- }
2911
- }
2912
- }
2913
- for (const key of Object.keys(context)) {
2914
- if (Object.isSealed(context[key])) {
2915
- await isolatedContext.evalClosure(`Object.seal(global['${key}']);`, []);
2916
- }
2917
- if (!Object.isExtensible(context[key])) {
2918
- await isolatedContext.evalClosure(`Object.preventExtensions(global['${key}']);`, []);
2919
- }
2920
- }
2921
- const Console = await jail.get(Identifiers.ConsoleObjIdentifier, { reference: true });
2922
- await Console.set("log", (...args) => {
2923
- const message = args.shift();
2924
- traces.push({ type: "log", message, args, started_at: Date.now() });
2925
- });
2926
- await isolatedContext.evalClosure(
2927
- `${Identifiers.VariableTrackingFnIdentifier} = (name, getter) => {
2928
- const value = getter();
2929
- try {
2930
- $0.applySync(null, [name, getter()], { arguments: { copy: true } });
2931
- } catch {
2932
- $0.applySync(null, [name, '[[non-primitive]]'], { arguments: { copy: true } });
2933
- }
2934
- };`,
2935
- [
2936
- (name, value) => {
2937
- variables[name] = value;
2938
- }
2939
- ],
2940
- {
2941
- arguments: { reference: true }
2942
- }
2943
- );
2944
- const scriptCode = `
2945
- "use strict";
2946
- new Promise(async (resolve) => {
2947
-
2948
- async function* __fn__() {
2949
- ${transformed.code}
3725
+ throw new Error(`Unknown driver: ${DRIVER}`);
2950
3726
  }
2951
-
2952
- const fn = __fn__();
2953
- do {
2954
- const { value, done } = await fn.next();
2955
- if (done) {
2956
- const ret = await value;
2957
- return resolve(ret);
3727
+ var handleErrorQuickJS = (err, code, _consumer, traces, variables, lines_executed, userCodeStartLine, currentToolCall) => {
3728
+ var _a, _b, _c;
3729
+ err = Signals.maybeDeserializeError(err);
3730
+ const lines = code.split("\n");
3731
+ const stackTrace = err.stack || "";
3732
+ const LINE_OFFSET = 1;
3733
+ const regex = /<quickjs>:(\d+)/g;
3734
+ const QUICKJS_WRAPPER_OFFSET = 10;
3735
+ const matches = Array.from(stackTrace.matchAll(regex)).map((x) => {
3736
+ const quickjsLine = Number(x[1]);
3737
+ const transformedCodeLine = quickjsLine - QUICKJS_WRAPPER_OFFSET;
3738
+ const line = Math.max(1, transformedCodeLine - userCodeStartLine + 1);
3739
+ const actualLine = lines[line - LINE_OFFSET] ?? "";
3740
+ const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
3741
+ const minColumn = whiteSpacesCount;
3742
+ return {
3743
+ line,
3744
+ column: minColumn
3745
+ };
3746
+ });
3747
+ if (matches.length === 0 && lines_executed.size > 0) {
3748
+ const lastLine2 = Math.max(...Array.from(lines_executed.keys()));
3749
+ const actualLine = lines[lastLine2 - LINE_OFFSET] ?? "";
3750
+ const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
3751
+ matches.push({
3752
+ line: lastLine2,
3753
+ column: whiteSpacesCount
3754
+ });
2958
3755
  }
2959
- await ${Identifiers.AsyncIterYieldFnIdentifier}(value);
2960
- } while(true);
2961
-
2962
- })`.trim();
2963
- const script = await isolate.compileScript(scriptCode, { filename: "<isolated-vm>", columnOffset: 0, lineOffset: 0 });
2964
- const copyErrors = [];
2965
- let copied = false;
2966
- const copyBackContextFromJail = () => {
2967
- if (copied) {
2968
- return;
2969
- }
2970
- copied = true;
2971
- for (const key of trackedProperties) {
2972
- if (typeof context[key] === "object" && !referenceProperties.has(key)) {
2973
- try {
2974
- let properties = [];
2975
- try {
2976
- properties = isolatedContext.evalClosureSync(`return Object.getOwnPropertyNames(global['${key}'])`, [], {
2977
- result: { copy: true }
2978
- }) ?? [];
2979
- } catch (err) {
2980
- console.error(`Could not get properties of object "${key}" from the sandbox`, err);
2981
- }
2982
- const propsToDelete = Object.getOwnPropertyNames(context[key]).filter((x) => !properties.includes(x));
2983
- for (const prop of propsToDelete) {
2984
- delete context[key][prop];
2985
- }
2986
- for (const prop of properties) {
2987
- if (typeof context[key][prop] === "function" || referenceProperties.has(`${key}.${prop}`)) {
2988
- continue;
2989
- }
2990
- try {
2991
- const obj = isolatedContext.evalClosureSync(`return global['${key}']['${prop}']`, [], {
2992
- result: { copy: true }
2993
- });
2994
- try {
2995
- Object.assign(context[key], { [prop]: obj });
2996
- } catch (err) {
2997
- if (err instanceof AssignmentError) {
2998
- traces.push({
2999
- type: "code_execution_exception",
3000
- position: [0, 0],
3001
- message: err.message,
3002
- stackTrace: "",
3003
- started_at: Date.now(),
3004
- ended_at: Date.now()
3005
- });
3006
- copyErrors.push(err);
3007
- }
3008
- }
3009
- } catch (err) {
3010
- console.error(`Could not copy back "${key}.${prop}" from the sandbox`, err);
3011
- }
3012
- }
3013
- } catch (err) {
3014
- console.error(`Could not copy back object "${key}" from the sandbox`, err);
3015
- }
3016
- } else {
3017
- try {
3018
- if (referenceProperties.has(key)) {
3019
- continue;
3020
- }
3021
- const value = jail.getSync(key, { copy: true });
3022
- try {
3023
- Object.assign(context, { [key]: value });
3024
- } catch (err) {
3025
- if (err instanceof AssignmentError) {
3026
- traces.push({
3027
- type: "code_execution_exception",
3028
- position: [0, 0],
3029
- message: err.message,
3030
- stackTrace: "",
3031
- started_at: Date.now(),
3032
- ended_at: Date.now()
3033
- });
3034
- copyErrors.push(err);
3035
- }
3036
- }
3037
- } catch (err) {
3038
- console.error(`Could not copy back "${key}" from the sandbox`, err);
3039
- }
3040
- }
3756
+ const lastLine = ((_a = maxBy_default(matches, (x) => x.line ?? 0)) == null ? void 0 : _a.line) ?? 0;
3757
+ let debugUserCode = "";
3758
+ let truncatedCode = "";
3759
+ let truncated = false;
3760
+ const appendCode = (line) => {
3761
+ debugUserCode += line;
3762
+ if (!truncated) {
3763
+ truncatedCode += line;
3041
3764
  }
3042
3765
  };
3043
- const final = await script.run(isolatedContext, {
3044
- timeout,
3045
- copy: true,
3046
- promise: true
3047
- }).then((res) => {
3048
- copyBackContextFromJail();
3049
- if (copyErrors.length) {
3050
- throw new CodeExecutionError(copyErrors.map((x) => x.message).join(", "), code, "");
3051
- }
3052
- return res;
3053
- }).then(
3054
- (res) => {
3055
- res = Signals.maybeDeserializeError(res);
3056
- return {
3057
- success: true,
3058
- variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3059
- signal: res instanceof VMSignal ? res : void 0,
3060
- lines_executed: Array.from(lines_executed),
3061
- return_value: res
3062
- };
3063
- },
3064
- (err) => {
3065
- return handleError(err, code, consumer, traces, variables, lines_executed, currentToolCall, DRIVER);
3066
- }
3067
- ).catch((err) => {
3068
- if (signal == null ? void 0 : signal.aborted) {
3069
- return handleCatch(new Error("Execution was aborted"), traces, variables, lines_executed);
3766
+ for (let i = 0; i < lines.length; i++) {
3767
+ const VM_OFFSET = 2;
3768
+ const DISPLAY_OFFSET = 0;
3769
+ const line = lines[i];
3770
+ const correctedStackLineIndex = i + LINE_OFFSET + VM_OFFSET;
3771
+ const match = matches.find((x) => x.line + VM_OFFSET === correctedStackLineIndex);
3772
+ const paddedLineNumber = String(correctedStackLineIndex - VM_OFFSET - DISPLAY_OFFSET).padStart(3, "0");
3773
+ if (match) {
3774
+ appendCode(`> ${paddedLineNumber} | ${line}
3775
+ `);
3776
+ appendCode(` ${" ".repeat(paddedLineNumber.length + match.column)}^^^^^^^^^^
3777
+ `);
3778
+ if (match.line >= lastLine) {
3779
+ truncated = true;
3780
+ }
3070
3781
  } else {
3071
- copyBackContextFromJail();
3782
+ appendCode(` ${paddedLineNumber} | ${line}
3783
+ `);
3072
3784
  }
3073
- return handleCatch(err, traces, variables, lines_executed);
3074
- });
3075
- signal == null ? void 0 : signal.removeEventListener("abort", abort);
3076
- try {
3077
- isolate.dispose();
3078
- } catch {
3079
3785
  }
3080
- try {
3081
- isolatedContext.release();
3082
- } catch {
3786
+ debugUserCode = cleanStackTrace(debugUserCode).trim();
3787
+ truncatedCode = cleanStackTrace(truncatedCode).trim();
3788
+ if (err instanceof VMSignal) {
3789
+ const signalError = err;
3790
+ signalError.stack = debugUserCode;
3791
+ signalError.truncatedCode = truncatedCode;
3792
+ signalError.variables = mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter);
3793
+ signalError.toolCall = currentToolCall;
3794
+ return {
3795
+ success: true,
3796
+ variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3797
+ signal: err,
3798
+ lines_executed: Array.from(lines_executed)
3799
+ };
3800
+ } else {
3801
+ traces.push({
3802
+ type: "code_execution_exception",
3803
+ position: [((_b = matches[0]) == null ? void 0 : _b.line) ?? 0, ((_c = matches[0]) == null ? void 0 : _c.column) ?? 0],
3804
+ message: err.message,
3805
+ stackTrace: debugUserCode,
3806
+ started_at: Date.now()
3807
+ });
3808
+ const codeError = new CodeExecutionError(err.message, code, debugUserCode);
3809
+ const deserializedError = Signals.maybeDeserializeError(codeError);
3810
+ return {
3811
+ success: false,
3812
+ variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3813
+ error: deserializedError,
3814
+ traces,
3815
+ lines_executed: Array.from(lines_executed)
3816
+ };
3083
3817
  }
3084
- return final;
3085
- }
3086
- var handleError = (err, code, consumer, traces, variables, lines_executed, currentToolCall, driver = "isolated-vm") => {
3087
- var _a3, _b, _c;
3818
+ };
3819
+ var handleErrorNode = (err, code, consumer, traces, variables, _lines_executed, currentToolCall) => {
3820
+ var _a, _b, _c;
3088
3821
  err = Signals.maybeDeserializeError(err);
3089
3822
  const lines = code.split("\n");
3090
3823
  const stackTrace = err.stack || "";
3091
- const LINE_OFFSET = driver === "isolated-vm" ? 3 : 1;
3092
- let regex = /\(<isolated-vm>:(\d+):(\d+)/g;
3093
- if (driver === "node") {
3094
- regex = /<anonymous>:(\d+):(\d+)/g;
3095
- }
3824
+ const LINE_OFFSET = 1;
3825
+ const regex = /<anonymous>:(\d+):(\d+)/g;
3096
3826
  const matches = [...stackTrace.matchAll(regex)].map((x) => {
3097
3827
  const originalLine = consumer.originalPositionFor({
3098
3828
  line: Number(x[1]),
@@ -3107,7 +3837,7 @@ var handleError = (err, code, consumer, traces, variables, lines_executed, curre
3107
3837
  column: Math.min(minColumn, Number(x[2]))
3108
3838
  };
3109
3839
  });
3110
- const lastLine = ((_a3 = maxBy_default(matches, (x) => x.line ?? 0)) == null ? void 0 : _a3.line) ?? 0;
3840
+ const lastLine = ((_a = maxBy_default(matches, (x) => x.line ?? 0)) == null ? void 0 : _a.line) ?? 0;
3111
3841
  let debugUserCode = "";
3112
3842
  let truncatedCode = "";
3113
3843
  let truncated = false;
@@ -3118,8 +3848,8 @@ var handleError = (err, code, consumer, traces, variables, lines_executed, curre
3118
3848
  }
3119
3849
  };
3120
3850
  for (let i = 0; i < lines.length; i++) {
3121
- const VM_OFFSET = driver === "isolated-vm" ? 2 : 2;
3122
- const DISPLAY_OFFSET = driver === "isolated-vm" ? 2 : 0;
3851
+ const VM_OFFSET = 2;
3852
+ const DISPLAY_OFFSET = 0;
3123
3853
  const line = lines[i];
3124
3854
  const correctedStackLineIndex = i + LINE_OFFSET + VM_OFFSET;
3125
3855
  const match = matches.find((x) => x.line + VM_OFFSET === correctedStackLineIndex);
@@ -3169,6 +3899,5 @@ var handleCatch = (err, traces, variables, lines_executed) => {
3169
3899
  };
3170
3900
 
3171
3901
  export {
3172
- CAN_USE_ISOLATED_VM,
3173
3902
  runAsyncFunction
3174
3903
  };