llmz 0.0.79 → 0.0.81

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 (67) hide show
  1. package/dist/{chunk-W4HLZNF4.js → chunk-22DGAZXC.js} +784 -868
  2. package/dist/{chunk-ESMRQVFC.js → chunk-2UM7PFM3.js} +6 -6
  3. package/dist/{chunk-EKXZXQJB.js → chunk-3NVOHQVY.js} +1 -1
  4. package/dist/{chunk-BSKF4J2E.cjs → chunk-5X5TDCMX.cjs} +51 -51
  5. package/dist/{chunk-BLB44ZDU.cjs → chunk-BXPPMP5X.cjs} +14 -14
  6. package/dist/{chunk-F4OZHUMS.cjs → chunk-DLV5FJ42.cjs} +9 -9
  7. package/dist/{chunk-LR6KTFHO.js → chunk-DO7DN4FZ.js} +1 -1
  8. package/dist/{chunk-UOPTKXLE.js → chunk-E6UFMAW7.js} +1 -1
  9. package/dist/{chunk-E5YW5YQN.js → chunk-E74GBCTT.js} +2 -2
  10. package/dist/{chunk-YTDNCBQW.js → chunk-EQ4JDBE5.js} +1 -1
  11. package/dist/{chunk-4VYDQ3VF.cjs → chunk-FQ4QCUTI.cjs} +7 -7
  12. package/dist/{chunk-5CXOW4DC.cjs → chunk-GFZCNSYW.cjs} +797 -881
  13. package/dist/{chunk-QOM7BK7U.cjs → chunk-H5LCBNN6.cjs} +18 -18
  14. package/dist/{chunk-UI6J4WKQ.js → chunk-HBKQKO3R.js} +3 -3
  15. package/dist/{chunk-2KRDL5AW.js → chunk-HP3T6PF4.js} +4 -4
  16. package/dist/{chunk-54G63644.cjs → chunk-OX3Y2Z5K.cjs} +3 -3
  17. package/dist/{chunk-UCXQ4U7P.cjs → chunk-TB6TCWEB.cjs} +2 -2
  18. package/dist/{chunk-WDYTCDIK.cjs → chunk-VXQ2CZ7B.cjs} +4 -4
  19. package/dist/{chunk-XLUYPCCY.cjs → chunk-X24YFCFY.cjs} +28 -28
  20. package/dist/{chunk-M4WTTARE.js → chunk-YFG53MRF.js} +1 -1
  21. package/dist/{component-DWFDDH5N.js → component-GVCCL5XU.js} +3 -3
  22. package/dist/component-YMPMWSTU.cjs +18 -0
  23. package/dist/dual-modes-KOU5YJ3Q.cjs +12 -0
  24. package/dist/dual-modes-X7YHJBFJ.js +12 -0
  25. package/dist/exit-A34GODDB.cjs +8 -0
  26. package/dist/exit-J55SREDL.js +8 -0
  27. package/dist/index.cjs +49 -49
  28. package/dist/index.js +22 -22
  29. package/dist/{jsx-PCXQVMLU.js → jsx-RIPUQSAU.js} +2 -2
  30. package/dist/jsx-XEUSAKAK.cjs +13 -0
  31. package/dist/{llmz-XRURR7Z5.cjs → llmz-7TDUOEQE.cjs} +29 -29
  32. package/dist/{llmz-F227HVGB.js → llmz-BSI7Y6YH.js} +11 -11
  33. package/dist/quickjs-variant.d.ts +7 -1
  34. package/dist/tool-B3DJ3D2F.js +11 -0
  35. package/dist/tool-IWPZD5OY.cjs +11 -0
  36. package/dist/{truncator-2FSONJM2.js → truncator-HCWH5MJ3.js} +3 -3
  37. package/dist/truncator-SOO6NHLD.cjs +10 -0
  38. package/dist/{typings-DVMU3KVB.js → typings-FPFJ5D5R.js} +3 -3
  39. package/dist/typings-O2FLZGQN.cjs +10 -0
  40. package/dist/{utils-D3J443FA.js → utils-M5KFPSNZ.js} +2 -2
  41. package/dist/utils-PWX3JPCF.cjs +39 -0
  42. package/dist/vm/drivers/node.d.ts +5 -0
  43. package/dist/vm/drivers/quickjs.d.ts +6 -0
  44. package/dist/vm/errors.d.ts +21 -0
  45. package/dist/vm/index.d.ts +3 -0
  46. package/dist/vm/instrument.d.ts +11 -0
  47. package/dist/vm/types.d.ts +20 -0
  48. package/dist/{vm-GDB4GW4S.js → vm-KBBQ7U5L.js} +3 -3
  49. package/dist/vm-R2XBIWE4.cjs +10 -0
  50. package/package.json +4 -4
  51. package/dist/component-RVYDIBUM.cjs +0 -18
  52. package/dist/dual-modes-A4SC4APN.cjs +0 -12
  53. package/dist/dual-modes-FNC3BGK3.js +0 -12
  54. package/dist/exit-56DISPLS.js +0 -8
  55. package/dist/exit-OOGJ3TAS.cjs +0 -8
  56. package/dist/jsx-ENFGHP6S.cjs +0 -13
  57. package/dist/tool-A7EOCUQG.cjs +0 -11
  58. package/dist/tool-FNWHZGDU.js +0 -11
  59. package/dist/truncator-6M2EP2NZ.cjs +0 -10
  60. package/dist/typings-54UIN7ZR.cjs +0 -10
  61. package/dist/utils-BZUEJT4W.cjs +0 -39
  62. package/dist/vm-CR5NE6NS.cjs +0 -10
  63. package/dist/vm.d.ts +0 -9
  64. package/dist/{chunk-RKKRSBX3.cjs → chunk-7XVBJQ53.cjs} +432 -432
  65. package/dist/{chunk-5XC6ZMS5.js → chunk-BJMZIH3M.js} +432 -432
  66. /package/dist/{vm-jsx.test.d.ts → vm/vm-jsx.test.d.ts} +0 -0
  67. /package/dist/{vm.test.d.ts → vm/vm.test.d.ts} +0 -0
@@ -10,14 +10,14 @@ import {
10
10
  } from "./chunk-YEAWWJSJ.js";
11
11
  import {
12
12
  createJsxComponent
13
- } from "./chunk-UOPTKXLE.js";
13
+ } from "./chunk-E6UFMAW7.js";
14
14
  import {
15
15
  __commonJS,
16
16
  __toESM,
17
17
  isFunction_default,
18
18
  mapValues_default,
19
19
  maxBy_default
20
- } from "./chunk-5XC6ZMS5.js";
20
+ } from "./chunk-BJMZIH3M.js";
21
21
 
22
22
  // ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/base64.js
23
23
  var require_base64 = __commonJS({
@@ -1933,9 +1933,8 @@ var require_source_map = __commonJS({
1933
1933
  }
1934
1934
  });
1935
1935
 
1936
- // src/vm.ts
1936
+ // src/vm/index.ts
1937
1937
  var import_source_map_js = __toESM(require_source_map(), 1);
1938
- import { newQuickJSWASMModuleFromVariant, shouldInterruptAfterDeadline } from "quickjs-emscripten-core";
1939
1938
 
1940
1939
  // src/compiler/compiler.ts
1941
1940
  import jsxPlugin from "@babel/plugin-transform-react-jsx";
@@ -2940,8 +2939,153 @@ var BundledReleaseSyncVariant = {
2940
2939
  }
2941
2940
  };
2942
2941
 
2943
- // src/vm.ts
2944
- var MAX_VM_EXECUTION_TIME = 6e4;
2942
+ // src/vm/errors.ts
2943
+ var handleErrorQuickJS = (err, code, _consumer, traces, variables, lines_executed, userCodeStartLine, currentToolCall) => {
2944
+ err = Signals.maybeDeserializeError(err);
2945
+ const lines = code.split("\n");
2946
+ const stackTrace = err.stack || "";
2947
+ const LINE_OFFSET = 1;
2948
+ const regex = /<quickjs>:(\d+)/g;
2949
+ const QUICKJS_WRAPPER_OFFSET = 10;
2950
+ const matches = Array.from(stackTrace.matchAll(regex)).map((x) => {
2951
+ const quickjsLine = Number(x[1]);
2952
+ const transformedCodeLine = quickjsLine - QUICKJS_WRAPPER_OFFSET;
2953
+ const line = Math.max(1, transformedCodeLine - userCodeStartLine + 1);
2954
+ const actualLine = lines[line - LINE_OFFSET] ?? "";
2955
+ const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
2956
+ return { line, column: whiteSpacesCount };
2957
+ });
2958
+ if (matches.length === 0 && lines_executed.size > 0) {
2959
+ const lastLine = Math.max(...Array.from(lines_executed.keys()));
2960
+ const actualLine = lines[lastLine - LINE_OFFSET] ?? "";
2961
+ const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
2962
+ matches.push({ line: lastLine, column: whiteSpacesCount });
2963
+ }
2964
+ return formatError(err, lines, matches, traces, variables, lines_executed, currentToolCall, code);
2965
+ };
2966
+ var handleErrorNode = (err, code, consumer, traces, variables, _lines_executed, currentToolCall) => {
2967
+ var _a, _b;
2968
+ err = Signals.maybeDeserializeError(err);
2969
+ const lines = code.split("\n");
2970
+ const stackTrace = err.stack || "";
2971
+ const LINE_OFFSET = 1;
2972
+ const regex = /<anonymous>:(\d+):(\d+)/g;
2973
+ const matches = [...stackTrace.matchAll(regex)].map((x) => {
2974
+ const originalLine = consumer.originalPositionFor({
2975
+ line: Number(x[1]),
2976
+ column: Number(x[2])
2977
+ });
2978
+ const line = originalLine.line ?? Number(x[1]);
2979
+ const actualLine = lines[line - LINE_OFFSET] ?? "";
2980
+ const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
2981
+ const minColumn = Math.max(whiteSpacesCount, originalLine.column);
2982
+ return { line, column: Math.min(minColumn, Number(x[2])) };
2983
+ });
2984
+ const { debugUserCode, truncatedCode } = buildDebugCode(lines, matches);
2985
+ if (err instanceof VMSignal) {
2986
+ err.stack = debugUserCode;
2987
+ err.truncatedCode = truncatedCode;
2988
+ err.variables = mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter);
2989
+ err.toolCall = currentToolCall;
2990
+ throw err;
2991
+ } else {
2992
+ traces.push({
2993
+ type: "code_execution_exception",
2994
+ position: [((_a = matches[0]) == null ? void 0 : _a.line) ?? 0, ((_b = matches[0]) == null ? void 0 : _b.column) ?? 0],
2995
+ message: err.message,
2996
+ stackTrace: debugUserCode,
2997
+ started_at: Date.now()
2998
+ });
2999
+ throw new CodeExecutionError(err.message, code, debugUserCode);
3000
+ }
3001
+ };
3002
+ var handleCatch = (err, traces, variables, lines_executed) => {
3003
+ err = Signals.maybeDeserializeError(err);
3004
+ return {
3005
+ success: err instanceof VMSignal ? true : false,
3006
+ variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3007
+ error: err,
3008
+ signal: err instanceof VMSignal ? err : void 0,
3009
+ traces,
3010
+ lines_executed: Array.from(lines_executed)
3011
+ };
3012
+ };
3013
+ function buildDebugCode(lines, matches) {
3014
+ var _a;
3015
+ const LINE_OFFSET = 1;
3016
+ const lastLine = ((_a = maxBy_default(matches, (x) => x.line ?? 0)) == null ? void 0 : _a.line) ?? 0;
3017
+ let debugUserCode = "";
3018
+ let truncatedCode = "";
3019
+ let truncated = false;
3020
+ const appendCode = (line) => {
3021
+ debugUserCode += line;
3022
+ if (!truncated) {
3023
+ truncatedCode += line;
3024
+ }
3025
+ };
3026
+ for (let i = 0; i < lines.length; i++) {
3027
+ const VM_OFFSET = 2;
3028
+ const DISPLAY_OFFSET = 0;
3029
+ const line = lines[i];
3030
+ const correctedStackLineIndex = i + LINE_OFFSET + VM_OFFSET;
3031
+ const match = matches.find((x) => x.line + VM_OFFSET === correctedStackLineIndex);
3032
+ const paddedLineNumber = String(correctedStackLineIndex - VM_OFFSET - DISPLAY_OFFSET).padStart(3, "0");
3033
+ if (match) {
3034
+ appendCode(`> ${paddedLineNumber} | ${line}
3035
+ `);
3036
+ appendCode(` ${" ".repeat(paddedLineNumber.length + match.column)}^^^^^^^^^^
3037
+ `);
3038
+ if (match.line >= lastLine) {
3039
+ truncated = true;
3040
+ }
3041
+ } else {
3042
+ appendCode(` ${paddedLineNumber} | ${line}
3043
+ `);
3044
+ }
3045
+ }
3046
+ return {
3047
+ debugUserCode: cleanStackTrace(debugUserCode).trim(),
3048
+ truncatedCode: cleanStackTrace(truncatedCode).trim()
3049
+ };
3050
+ }
3051
+ function formatError(err, lines, matches, traces, variables, lines_executed, currentToolCall, code) {
3052
+ var _a, _b;
3053
+ const { debugUserCode, truncatedCode } = buildDebugCode(lines, matches);
3054
+ if (err instanceof VMSignal) {
3055
+ const signalError = err;
3056
+ signalError.stack = debugUserCode;
3057
+ signalError.truncatedCode = truncatedCode;
3058
+ signalError.variables = mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter);
3059
+ signalError.toolCall = currentToolCall;
3060
+ return {
3061
+ success: true,
3062
+ variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3063
+ signal: err,
3064
+ lines_executed: Array.from(lines_executed)
3065
+ };
3066
+ } else {
3067
+ traces.push({
3068
+ type: "code_execution_exception",
3069
+ position: [((_a = matches[0]) == null ? void 0 : _a.line) ?? 0, ((_b = matches[0]) == null ? void 0 : _b.column) ?? 0],
3070
+ message: err.message,
3071
+ stackTrace: debugUserCode,
3072
+ started_at: Date.now()
3073
+ });
3074
+ const codeError = new CodeExecutionError(err.message, code, debugUserCode);
3075
+ const deserializedError = Signals.maybeDeserializeError(codeError);
3076
+ return {
3077
+ success: false,
3078
+ variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3079
+ error: deserializedError,
3080
+ traces,
3081
+ lines_executed: Array.from(lines_executed)
3082
+ };
3083
+ }
3084
+ }
3085
+
3086
+ // src/vm/instrument.ts
3087
+ var USER_CODE_MARKER_TAG_START = "__LLMZ_USER_CODE_START__";
3088
+ var USER_CODE_MARKER_TAG_END = "__LLMZ_USER_CODE_END__";
2945
3089
  var NO_TRACKING = [
2946
3090
  Identifiers.CommentFnIdentifier,
2947
3091
  Identifiers.ToolCallTrackerFnIdentifier,
@@ -2950,402 +3094,601 @@ var NO_TRACKING = [
2950
3094
  Identifiers.JSXFnIdentifier,
2951
3095
  Identifiers.ConsoleObjIdentifier
2952
3096
  ];
2953
- function getCompiledCode(code, traces = []) {
2954
- try {
2955
- return compile(code);
2956
- } catch (err) {
2957
- traces.push({
2958
- type: "invalid_code_exception",
2959
- message: (err == null ? void 0 : err.message) ?? "Unknown error",
2960
- code,
2961
- started_at: Date.now()
2962
- });
2963
- throw new InvalidCodeError(err.message, code);
2964
- }
3097
+ function instrumentContext(context, transformed, traces, variables, lines_executed, consumer, userCodeStartLine) {
3098
+ const state = { currentToolCall: void 0 };
3099
+ context[Identifiers.CommentFnIdentifier] = (comment, line) => {
3100
+ if (comment.includes(USER_CODE_MARKER_TAG_START) || comment.includes(USER_CODE_MARKER_TAG_END)) {
3101
+ return;
3102
+ }
3103
+ traces.push({ type: "comment", comment, line, started_at: Date.now() });
3104
+ };
3105
+ context[Identifiers.LineTrackingFnIdentifier] = (line) => {
3106
+ const originalLine = consumer.originalPositionFor({ line, column: 0 });
3107
+ const mappedLine = originalLine.line ?? line;
3108
+ const userCodeLine = Math.max(1, mappedLine - userCodeStartLine);
3109
+ lines_executed.set(userCodeLine, (lines_executed.get(userCodeLine) ?? 0) + 1);
3110
+ };
3111
+ context[Identifiers.JSXFnIdentifier] = (tool, props, ...children) => createJsxComponent({ type: tool, props, children });
3112
+ context[Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
3113
+ if (NO_TRACKING.includes(name)) {
3114
+ return;
3115
+ }
3116
+ variables[name] = () => {
3117
+ try {
3118
+ const value = getter();
3119
+ if (typeof value === "function") {
3120
+ return "[[non-primitive]]";
3121
+ }
3122
+ return value;
3123
+ } catch {
3124
+ return "[[non-primitive]]";
3125
+ }
3126
+ };
3127
+ };
3128
+ context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
3129
+ var _a;
3130
+ const temp = Signals.maybeDeserializeError(outputOrError == null ? void 0 : outputOrError.message);
3131
+ if (type === "end" && temp instanceof SnapshotSignal && (temp == null ? void 0 : temp.toolCall)) {
3132
+ state.currentToolCall = {
3133
+ ...temp.toolCall,
3134
+ assignment: (_a = transformed.toolCalls.get(callId)) == null ? void 0 : _a.assignment
3135
+ };
3136
+ }
3137
+ };
3138
+ context[Identifiers.ConsoleObjIdentifier] = {
3139
+ log: (...args) => {
3140
+ const message = args.shift();
3141
+ traces.push({ type: "log", message, args, started_at: Date.now() });
3142
+ }
3143
+ };
3144
+ context[Identifiers.AsyncIterYieldFnIdentifier] = async function(value) {
3145
+ const startedAt = Date.now();
3146
+ try {
3147
+ if (typeof value.type !== "string" || value.type.trim().length === 0) {
3148
+ throw new Error("A yield statement must yield a valid tool");
3149
+ }
3150
+ const toolName = Object.keys(context).find((x) => x.toUpperCase() === value.type.toUpperCase());
3151
+ if (!toolName) {
3152
+ throw new Error(`Yield tool "${value.type}", but tool is not found`);
3153
+ }
3154
+ await context[toolName](value);
3155
+ } finally {
3156
+ traces.push({ type: "yield", value, started_at: startedAt, ended_at: Date.now() });
3157
+ }
3158
+ };
3159
+ return state;
2965
3160
  }
2966
- async function runAsyncFunction(context, code, traces = [], signal = null, timeout = MAX_VM_EXECUTION_TIME) {
2967
- var _a, _b, _c, _d, _e, _f, _g;
2968
- const transformed = getCompiledCode(code, traces);
2969
- const lines_executed = /* @__PURE__ */ new Map();
2970
- const variables = {};
2971
- const consumer = new import_source_map_js.SourceMapConsumer({
2972
- version: transformed.map.version.toString(),
2973
- mappings: transformed.map.mappings,
2974
- names: transformed.map.names,
2975
- sources: [transformed.map.file],
2976
- sourcesContent: [transformed.code],
2977
- file: transformed.map.file,
2978
- sourceRoot: transformed.map.sourceRoot
2979
- });
2980
- context ??= {};
2981
- for (const name of Array.from(transformed.variables)) {
2982
- delete context[name];
2983
- }
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";
3161
+ function findUserCodeStartLine(transformed) {
3162
+ var _a;
3163
+ const codeWithMarkers = transformed.codeWithMarkers || transformed.code;
3164
+ const markerLines = codeWithMarkers.split("\n");
3165
+ for (let i = 0; i < markerLines.length; i++) {
3166
+ if ((_a = markerLines[i]) == null ? void 0 : _a.includes(USER_CODE_START_MARKER)) {
3167
+ return i + 1;
3168
+ }
2987
3169
  }
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;
3170
+ return -1;
3171
+ }
3172
+
3173
+ // src/vm/drivers/node.ts
3174
+ var NodeDriver = class {
3175
+ async execute(ctx) {
3176
+ const { transformed, consumer, context, traces, code, lines_executed, variables } = ctx;
3177
+ const state = instrumentContext(context, transformed, traces, variables, lines_executed, consumer, 0);
3178
+ const AsyncFunction = async function* () {
3179
+ }.constructor;
3180
+ return await (async () => {
3181
+ const descriptors = Object.getOwnPropertyDescriptors(context);
3182
+ const topLevelProperties = Object.keys(descriptors).filter(
3183
+ (x) => !NO_TRACKING.includes(x) && descriptors[x] && typeof descriptors[x].value !== "function" && typeof descriptors[x].value !== "object"
3184
+ );
3185
+ const __report = (name, value) => {
3186
+ if (context[name] !== void 0 && context[name] !== value) {
3187
+ context[name] = value;
2993
3188
  }
2994
- traces.push({ type: "comment", comment, line, started_at: Date.now() });
2995
3189
  };
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;
3190
+ context.__report = __report;
3191
+ const reportAll = topLevelProperties.map((x) => `__report("${x}", ${x})`).join(";");
3192
+ const assigner = `let __${Identifiers.LineTrackingFnIdentifier} = ${Identifiers.LineTrackingFnIdentifier}; ${Identifiers.LineTrackingFnIdentifier} = function(line) { ${reportAll}; __${Identifiers.LineTrackingFnIdentifier}(line);}`;
3193
+ const wrapper = `"use strict"; try { ${assigner};${transformed.code} } finally { ${reportAll} };`;
3194
+ const fn = AsyncFunction(...Object.keys(context), wrapper);
3195
+ const res = fn(...Object.values(context));
3196
+ do {
3197
+ const { value, done } = await res.next();
3198
+ if (done) {
3199
+ return value;
3004
3200
  }
3005
- }
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);
3201
+ await context[Identifiers.AsyncIterYieldFnIdentifier](value);
3202
+ } while (true);
3203
+ })().then((res) => {
3204
+ res = Signals.maybeDeserializeError(res);
3205
+ return {
3206
+ success: true,
3207
+ variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3208
+ signal: res instanceof VMSignal ? res : void 0,
3209
+ lines_executed: Array.from(lines_executed),
3210
+ return_value: res
3014
3211
  };
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;
3212
+ }).catch((err) => handleErrorNode(err, code, consumer, traces, variables, lines_executed, state.currentToolCall)).catch((err) => handleCatch(err, traces, variables, lines_executed));
3213
+ }
3214
+ };
3215
+
3216
+ // src/vm/drivers/quickjs.ts
3217
+ import {
3218
+ newQuickJSWASMModuleFromVariant,
3219
+ shouldInterruptAfterDeadline
3220
+ } from "quickjs-emscripten-core";
3221
+ var QuickJSDriver = class {
3222
+ async execute(ctx) {
3223
+ const { transformed, consumer, context, traces, signal, timeout, code, lines_executed, variables } = ctx;
3224
+ const userCodeStartLine = findUserCodeStartLine(transformed);
3225
+ const state = instrumentContext(
3226
+ context,
3227
+ transformed,
3228
+ traces,
3229
+ variables,
3230
+ lines_executed,
3231
+ consumer,
3232
+ userCodeStartLine
3233
+ );
3234
+ const QuickJS = await newQuickJSWASMModuleFromVariant(BundledReleaseSyncVariant);
3235
+ const runtime = QuickJS.newRuntime();
3236
+ runtime.setMemoryLimit(128 * 1024 * 1024);
3237
+ const startTime = Date.now();
3238
+ const timeoutHandler = shouldInterruptAfterDeadline(startTime + timeout);
3239
+ runtime.setInterruptHandler(() => {
3240
+ if (signal == null ? void 0 : signal.aborted) {
3241
+ return true;
3242
+ }
3243
+ return timeoutHandler(runtime);
3244
+ });
3245
+ const vm = runtime.newContext();
3246
+ const trackedProperties = /* @__PURE__ */ new Set();
3247
+ const referenceProperties = /* @__PURE__ */ new Set();
3248
+ const pendingPromises = [];
3249
+ const toVmValue = (value) => {
3250
+ var _a;
3251
+ if (typeof value === "string") {
3252
+ return vm.newString(value);
3253
+ } else if (typeof value === "number") {
3254
+ return vm.newNumber(value);
3255
+ } else if (typeof value === "boolean") {
3256
+ return value ? vm.true : vm.false;
3257
+ } else if (value === null) {
3258
+ return vm.null;
3259
+ } else if (value === void 0) {
3260
+ return vm.undefined;
3261
+ } else if (Array.isArray(value)) {
3262
+ const items = value.map((item) => {
3263
+ if (typeof item === "string")
3264
+ return JSON.stringify(item);
3265
+ else if (typeof item === "number" || typeof item === "boolean")
3266
+ return String(item);
3267
+ else if (item === null)
3268
+ return "null";
3269
+ else if (item === void 0)
3270
+ return "undefined";
3271
+ else if (typeof item === "object")
3272
+ return JSON.stringify(item);
3273
+ return "undefined";
3274
+ });
3275
+ const result = vm.evalCode(`[${items.join(",")}]`);
3276
+ if ("error" in result) {
3277
+ (_a = result.error) == null ? void 0 : _a.dispose();
3278
+ return vm.undefined;
3023
3279
  }
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]]";
3280
+ return result.value;
3281
+ } else if (typeof value === "object") {
3282
+ const obj = vm.newObject();
3283
+ for (const [k, v] of Object.entries(value)) {
3284
+ if (typeof v !== "function") {
3285
+ const propHandle = toVmValue(v);
3286
+ vm.setProp(obj, k, propHandle);
3287
+ disposeIfNeeded(propHandle);
3033
3288
  }
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
3289
  }
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();
3290
+ return obj;
3291
+ }
3292
+ return vm.undefined;
3293
+ };
3294
+ const disposeIfNeeded = (handle) => {
3295
+ if (handle !== vm.true && handle !== vm.false && handle !== vm.null && handle !== vm.undefined) {
3296
+ ;
3297
+ handle.dispose();
3298
+ }
3299
+ };
3300
+ const bridgeFunction = (fn, _fnName = "anonymous") => {
3301
+ return (...argHandles) => {
3302
+ const args = argHandles.map((h) => vm.dump(h));
3055
3303
  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`);
3304
+ const result = fn(...args);
3305
+ if (result && typeof result.then === "function") {
3306
+ const promise = vm.newPromise();
3307
+ pendingPromises.push({ hostPromise: result, deferredPromise: promise });
3308
+ void promise.settled.then(() => {
3309
+ if (runtime.alive) {
3310
+ runtime.executePendingJobs();
3311
+ }
3312
+ });
3313
+ return promise.handle;
3062
3314
  }
3063
- await context[toolName](value);
3064
- } finally {
3065
- traces.push({ type: "yield", value, started_at: startedAt, ended_at: Date.now() });
3315
+ return toVmValue(result);
3316
+ } catch (err) {
3317
+ const serialized = err instanceof Error ? err.message : String(err);
3318
+ throw new Error(serialized);
3066
3319
  }
3067
3320
  };
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
- disposeIfNeeded(propHandle);
3321
+ };
3322
+ try {
3323
+ bridgeContextToVM(context, vm, trackedProperties, referenceProperties, toVmValue, disposeIfNeeded, bridgeFunction);
3324
+ setupVariableTrackingBridge(vm, variables);
3325
+ const scriptCode = buildScriptCode(transformed.code);
3326
+ const copyBackContextFromVM = () => {
3327
+ for (const key of trackedProperties) {
3328
+ if (referenceProperties.has(key))
3329
+ continue;
3330
+ try {
3331
+ const valueResult = vm.evalCode(`globalThis['${key}']`);
3332
+ const vmValue = vm.dump(valueResult.unwrap());
3333
+ valueResult.unwrap().dispose();
3334
+ try {
3335
+ context[key] = vmValue;
3336
+ } catch {
3125
3337
  }
3338
+ } catch {
3126
3339
  }
3127
- return obj;
3128
3340
  }
3129
- return vm.undefined;
3130
3341
  };
3131
- const disposeIfNeeded = (handle) => {
3132
- if (handle !== vm.true && handle !== vm.false && handle !== vm.null && handle !== vm.undefined) {
3133
- handle.dispose();
3342
+ const execResult = vm.evalCode(scriptCode, "<quickjs>");
3343
+ if ("error" in execResult) {
3344
+ if (execResult.error) {
3345
+ const err = vm.dump(execResult.error);
3346
+ execResult.error.dispose();
3347
+ throw new Error((err == null ? void 0 : err.message) || "Execution failed");
3348
+ }
3349
+ throw new Error("Execution failed");
3350
+ }
3351
+ execResult.value.dispose();
3352
+ await this._pumpEventLoop(runtime, vm, pendingPromises, signal, toVmValue, disposeIfNeeded);
3353
+ const errorResult = vm.evalCode("globalThis.__llmz_error");
3354
+ const errorValue = vm.dump(errorResult.unwrap());
3355
+ errorResult.unwrap().dispose();
3356
+ if (signal == null ? void 0 : signal.aborted) {
3357
+ const reason = signal.reason;
3358
+ if (reason instanceof Error)
3359
+ throw reason;
3360
+ throw new Error(reason ? String(reason) : "Execution was aborted");
3361
+ }
3362
+ if (errorValue !== null && errorValue !== "") {
3363
+ try {
3364
+ copyBackContextFromVM();
3365
+ } catch {
3134
3366
  }
3367
+ const errorStackResult = vm.evalCode("globalThis.__llmz_error_stack");
3368
+ const errorStack = vm.dump(errorStackResult.unwrap()) || "";
3369
+ errorStackResult.unwrap().dispose();
3370
+ const deserializedError = Signals.maybeDeserializeError(errorValue);
3371
+ if (deserializedError instanceof VMSignal) {
3372
+ deserializedError.stack = errorStack;
3373
+ throw deserializedError;
3374
+ }
3375
+ const error = new Error(errorValue);
3376
+ error.stack = errorStack;
3377
+ throw error;
3378
+ }
3379
+ copyBackContextFromVM();
3380
+ const resultSetResult = vm.evalCode("globalThis.__llmz_result_set");
3381
+ const resultSet = vm.dump(resultSetResult.unwrap());
3382
+ resultSetResult.unwrap().dispose();
3383
+ let returnValue = void 0;
3384
+ if (resultSet) {
3385
+ const resultResult = vm.evalCode("globalThis.__llmz_result");
3386
+ returnValue = vm.dump(resultResult.unwrap());
3387
+ resultResult.unwrap().dispose();
3388
+ }
3389
+ returnValue = Signals.maybeDeserializeError(returnValue);
3390
+ return {
3391
+ success: true,
3392
+ variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3393
+ signal: returnValue instanceof VMSignal ? returnValue : void 0,
3394
+ lines_executed: Array.from(lines_executed),
3395
+ return_value: returnValue
3135
3396
  };
3136
- const bridgeFunction = (fn, _fnName = "anonymous") => {
3137
- return (...argHandles) => {
3138
- const args = argHandles.map((h) => vm.dump(h));
3397
+ } catch (err) {
3398
+ if (signal == null ? void 0 : signal.aborted) {
3399
+ const reason = signal.reason;
3400
+ const abortError = reason instanceof Error ? reason : new Error(reason ? String(reason) : "Execution was aborted");
3401
+ return handleErrorQuickJS(
3402
+ abortError,
3403
+ code,
3404
+ consumer,
3405
+ traces,
3406
+ variables,
3407
+ lines_executed,
3408
+ userCodeStartLine,
3409
+ ctx.currentToolCall ?? state.currentToolCall
3410
+ );
3411
+ }
3412
+ await Promise.all(
3413
+ pendingPromises.map(async ({ hostPromise, deferredPromise }) => {
3139
3414
  try {
3140
- const result = fn(...args);
3141
- if (result && typeof result.then === "function") {
3142
- const promise = vm.newPromise();
3143
- pendingPromises.push({
3144
- hostPromise: result,
3145
- deferredPromise: promise
3146
- });
3147
- void promise.settled.then(() => {
3148
- if (runtime.alive) {
3149
- runtime.executePendingJobs();
3150
- }
3151
- });
3152
- return promise.handle;
3153
- }
3154
- return toVmValue(result);
3155
- } catch (err) {
3156
- const serialized = err instanceof Error ? err.message : String(err);
3157
- throw new Error(serialized);
3158
- }
3159
- };
3160
- };
3415
+ const value = await hostPromise;
3416
+ const vmValue = toVmValue(value);
3417
+ deferredPromise.resolve(vmValue);
3418
+ disposeIfNeeded(vmValue);
3419
+ } catch (err2) {
3420
+ const serialized = err2 instanceof Error ? err2.message : String(err2);
3421
+ const errValue = vm.newString(serialized);
3422
+ deferredPromise.reject(errValue);
3423
+ errValue.dispose();
3424
+ }
3425
+ })
3426
+ ).catch(() => {
3427
+ });
3428
+ return handleErrorQuickJS(
3429
+ err,
3430
+ code,
3431
+ consumer,
3432
+ traces,
3433
+ variables,
3434
+ lines_executed,
3435
+ userCodeStartLine,
3436
+ ctx.currentToolCall ?? state.currentToolCall
3437
+ );
3438
+ } finally {
3161
3439
  try {
3162
- for (const [key, value] of Object.entries(context)) {
3163
- const descriptor = Object.getOwnPropertyDescriptor(context, key);
3164
- if (descriptor && (descriptor.get || descriptor.set)) {
3165
- referenceProperties.add(key);
3166
- trackedProperties.add(key);
3167
- let getterCode = "undefined";
3168
- if (descriptor.get) {
3169
- const getterBridge = vm.newFunction(`get_${key}`, () => {
3170
- try {
3171
- const hostValue = context[key];
3172
- return toVmValue(hostValue);
3173
- } catch (err) {
3174
- const serialized = err instanceof Error ? err.message : String(err);
3175
- throw new Error(serialized);
3176
- }
3177
- });
3178
- const getterName = `__getter_${key}__`;
3179
- vm.setProp(vm.global, getterName, getterBridge);
3180
- getterBridge.dispose();
3181
- getterCode = getterName;
3182
- }
3183
- let setterCode = "undefined";
3184
- if (descriptor.set) {
3185
- const setterBridge = vm.newFunction(`set_${key}`, (valueHandle) => {
3186
- try {
3187
- const jsValue = vm.dump(valueHandle);
3188
- context[key] = jsValue;
3189
- return vm.undefined;
3190
- } catch (err) {
3191
- const serialized = err instanceof Error ? err.message : String(err);
3192
- throw new Error(serialized);
3193
- }
3194
- });
3195
- const setterName = `__setter_${key}__`;
3196
- vm.setProp(vm.global, setterName, setterBridge);
3197
- setterBridge.dispose();
3198
- setterCode = setterName;
3199
- }
3200
- const definePropertyCode = `
3201
- Object.defineProperty(globalThis, '${key}', {
3202
- enumerable: true,
3203
- configurable: ${descriptor.configurable !== false},
3204
- get: ${getterCode},
3205
- set: ${setterCode}
3206
- });
3207
- `;
3208
- const result = vm.evalCode(definePropertyCode);
3209
- if ("error" in result) {
3210
- (_c = result.error) == null ? void 0 : _c.dispose();
3211
- } else {
3212
- result.value.dispose();
3213
- }
3214
- continue;
3215
- }
3216
- if (typeof value === "function") {
3217
- const fnHandle = vm.newFunction(key, bridgeFunction(value, key));
3218
- vm.setProp(vm.global, key, fnHandle);
3219
- fnHandle.dispose();
3220
- } else if (Array.isArray(value)) {
3221
- trackedProperties.add(key);
3222
- const arrayHandle = toVmValue(value);
3223
- vm.setProp(vm.global, key, arrayHandle);
3224
- disposeIfNeeded(arrayHandle);
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
- disposeIfNeeded(propHandle);
3243
- }
3244
- }
3245
- vm.setProp(vm.global, key, objHandle);
3246
- objHandle.dispose();
3247
- for (const { prop, descriptor: descriptor2 } of getterSetterProps) {
3248
- let getterCode = "undefined";
3249
- if (descriptor2.get) {
3250
- const getterBridge = vm.newFunction(`get_${prop}`, () => {
3251
- try {
3252
- const hostValue = context[key][prop];
3253
- return toVmValue(hostValue);
3254
- } catch (err) {
3255
- const serialized = err instanceof Error ? err.message : String(err);
3256
- throw new Error(serialized);
3257
- }
3258
- });
3259
- const getterName = `__getter_${key}_${prop}__`;
3260
- vm.setProp(vm.global, getterName, getterBridge);
3261
- getterBridge.dispose();
3262
- getterCode = getterName;
3263
- }
3264
- let setterCode = "undefined";
3265
- if (descriptor2.set) {
3266
- const setterBridge = vm.newFunction(`set_${prop}`, (valueHandle) => {
3267
- try {
3268
- const jsValue = vm.dump(valueHandle);
3269
- context[key][prop] = jsValue;
3270
- return vm.undefined;
3271
- } catch (err) {
3272
- const serialized = err instanceof Error ? err.message : String(err);
3273
- throw new Error(serialized);
3274
- }
3275
- });
3276
- const setterName = `__setter_${key}_${prop}__`;
3277
- vm.setProp(vm.global, setterName, setterBridge);
3278
- setterBridge.dispose();
3279
- setterCode = setterName;
3280
- }
3281
- const definePropertyCode = `
3282
- Object.defineProperty(${key}, '${prop}', {
3283
- enumerable: true,
3284
- configurable: ${descriptor2.configurable !== false},
3285
- get: ${getterCode},
3286
- set: ${setterCode}
3287
- });
3288
- `;
3289
- const result = vm.evalCode(definePropertyCode);
3290
- if ("error" in result) {
3291
- (_d = result.error) == null ? void 0 : _d.dispose();
3292
- } else {
3293
- result.value.dispose();
3294
- }
3295
- }
3296
- if (Object.isSealed(value)) {
3297
- const sealResult = vm.evalCode(`Object.seal(globalThis['${key}']);`);
3298
- if ("error" in sealResult) {
3299
- (_e = sealResult.error) == null ? void 0 : _e.dispose();
3300
- } else {
3301
- sealResult.value.dispose();
3302
- }
3303
- }
3304
- if (!Object.isExtensible(value)) {
3305
- const preventResult = vm.evalCode(`Object.preventExtensions(globalThis['${key}']);`);
3306
- if ("error" in preventResult) {
3307
- (_f = preventResult.error) == null ? void 0 : _f.dispose();
3308
- } else {
3309
- preventResult.value.dispose();
3310
- }
3311
- }
3312
- } else {
3313
- trackedProperties.add(key);
3314
- const valueHandle = toVmValue(value);
3315
- vm.setProp(vm.global, key, valueHandle);
3316
- disposeIfNeeded(valueHandle);
3440
+ vm.dispose();
3441
+ } catch {
3442
+ }
3443
+ try {
3444
+ runtime.dispose();
3445
+ } catch {
3446
+ }
3447
+ }
3448
+ }
3449
+ // QuickJS has no event loop — we manually drain pending microtasks and resolve
3450
+ // host promises in a loop until all async work completes or the signal aborts.
3451
+ async _pumpEventLoop(runtime, vm, pendingPromises, signal, toVmValue, disposeIfNeeded) {
3452
+ var _a;
3453
+ const maxIterations = 1e3;
3454
+ let iteration = 0;
3455
+ while (iteration < maxIterations) {
3456
+ let hasJobs = false;
3457
+ const maxJobs = 1e4;
3458
+ for (let i = 0; i < maxJobs; i++) {
3459
+ const pending = (_a = runtime.executePendingJobs) == null ? void 0 : _a.call(runtime, -1);
3460
+ const jobCount = pending === void 0 ? 0 : pending.unwrap();
3461
+ if (jobCount <= 0)
3462
+ break;
3463
+ hasJobs = true;
3464
+ }
3465
+ const currentPromises = [...pendingPromises];
3466
+ pendingPromises.length = 0;
3467
+ if (currentPromises.length > 0) {
3468
+ if (signal == null ? void 0 : signal.aborted) {
3469
+ const reason = signal.reason;
3470
+ const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3471
+ for (const { deferredPromise } of currentPromises) {
3472
+ const errValue = vm.newString(abortMessage);
3473
+ deferredPromise.reject(errValue);
3474
+ errValue.dispose();
3317
3475
  }
3476
+ runtime.executePendingJobs();
3477
+ break;
3318
3478
  }
3319
- const varTrackFnHandle = vm.newFunction(
3320
- Identifiers.VariableTrackingFnIdentifier,
3321
- (nameHandle, getterHandle) => {
3322
- var _a2;
3323
- const name = vm.getString(nameHandle);
3324
- if (NO_TRACKING.includes(name)) {
3325
- return;
3479
+ let abortListener = null;
3480
+ if (signal) {
3481
+ abortListener = () => {
3482
+ const reason = signal.reason;
3483
+ const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3484
+ for (const { deferredPromise } of currentPromises) {
3485
+ const errValue = vm.newString(abortMessage);
3486
+ deferredPromise.reject(errValue);
3487
+ errValue.dispose();
3326
3488
  }
3327
- try {
3328
- const valueResult = vm.callFunction(getterHandle, vm.undefined);
3329
- if ("error" in valueResult) {
3330
- variables[name] = "[[non-primitive]]";
3331
- (_a2 = valueResult.error) == null ? void 0 : _a2.dispose();
3489
+ runtime.executePendingJobs();
3490
+ };
3491
+ signal.addEventListener("abort", abortListener);
3492
+ }
3493
+ try {
3494
+ await Promise.all(
3495
+ currentPromises.map(async ({ hostPromise, deferredPromise }) => {
3496
+ if (signal == null ? void 0 : signal.aborted)
3332
3497
  return;
3498
+ try {
3499
+ const value = await hostPromise;
3500
+ if (signal == null ? void 0 : signal.aborted)
3501
+ return;
3502
+ const vmValue = toVmValue(value);
3503
+ deferredPromise.resolve(vmValue);
3504
+ disposeIfNeeded(vmValue);
3505
+ } catch (err) {
3506
+ if (signal == null ? void 0 : signal.aborted)
3507
+ return;
3508
+ const serialized = err instanceof Error ? err.message : String(err);
3509
+ const createErrorResult = vm.evalCode(`new Error(${JSON.stringify(serialized)})`);
3510
+ if ("error" in createErrorResult) {
3511
+ const errValue = vm.newString(serialized);
3512
+ deferredPromise.reject(errValue);
3513
+ errValue.dispose();
3514
+ } else {
3515
+ const errorHandle = createErrorResult.value;
3516
+ deferredPromise.reject(errorHandle);
3517
+ errorHandle.dispose();
3518
+ }
3333
3519
  }
3334
- const value = vm.dump(valueResult.value);
3335
- valueResult.value.dispose();
3336
- if (typeof value === "function" || typeof value === "string" && value.includes("=>")) {
3337
- variables[name] = "[[non-primitive]]";
3338
- } else {
3339
- variables[name] = value;
3340
- }
3341
- } catch {
3342
- variables[name] = "[[non-primitive]]";
3343
- }
3520
+ })
3521
+ );
3522
+ } finally {
3523
+ if (signal && abortListener) {
3524
+ signal.removeEventListener("abort", abortListener);
3344
3525
  }
3345
- );
3346
- vm.setProp(vm.global, Identifiers.VariableTrackingFnIdentifier, varTrackFnHandle);
3347
- varTrackFnHandle.dispose();
3348
- const scriptCode = `
3526
+ }
3527
+ runtime.executePendingJobs();
3528
+ if (signal == null ? void 0 : signal.aborted)
3529
+ break;
3530
+ }
3531
+ if (!hasJobs && pendingPromises.length === 0)
3532
+ break;
3533
+ iteration++;
3534
+ }
3535
+ if (iteration >= maxIterations) {
3536
+ throw new Error("Maximum event loop iterations exceeded");
3537
+ }
3538
+ }
3539
+ };
3540
+ function bridgeContextToVM(context, vm, trackedProperties, referenceProperties, toVmValue, disposeIfNeeded, bridgeFunction) {
3541
+ var _a, _b;
3542
+ for (const [key, value] of Object.entries(context)) {
3543
+ const descriptor = Object.getOwnPropertyDescriptor(context, key);
3544
+ if (descriptor && (descriptor.get || descriptor.set)) {
3545
+ referenceProperties.add(key);
3546
+ trackedProperties.add(key);
3547
+ bridgeGetterSetter(vm, key, void 0, descriptor, context, toVmValue);
3548
+ continue;
3549
+ }
3550
+ if (typeof value === "function") {
3551
+ const fnHandle = vm.newFunction(key, bridgeFunction(value, key));
3552
+ vm.setProp(vm.global, key, fnHandle);
3553
+ fnHandle.dispose();
3554
+ } else if (Array.isArray(value)) {
3555
+ trackedProperties.add(key);
3556
+ const arrayHandle = toVmValue(value);
3557
+ vm.setProp(vm.global, key, arrayHandle);
3558
+ disposeIfNeeded(arrayHandle);
3559
+ } else if (typeof value === "object" && value !== null) {
3560
+ trackedProperties.add(key);
3561
+ const objHandle = vm.newObject();
3562
+ const props = /* @__PURE__ */ new Set([...Object.keys(value), ...Object.getOwnPropertyNames(value)]);
3563
+ const getterSetterProps = [];
3564
+ for (const prop of props) {
3565
+ const propDescriptor = Object.getOwnPropertyDescriptor(value, prop);
3566
+ if (propDescriptor && (propDescriptor.get || propDescriptor.set)) {
3567
+ referenceProperties.add(`${key}.${prop}`);
3568
+ getterSetterProps.push({ prop, descriptor: propDescriptor });
3569
+ } else if (typeof value[prop] === "function") {
3570
+ const propFnHandle = vm.newFunction(prop, bridgeFunction(value[prop], `${key}.${prop}`));
3571
+ vm.setProp(objHandle, prop, propFnHandle);
3572
+ propFnHandle.dispose();
3573
+ } else {
3574
+ const propHandle = toVmValue(value[prop]);
3575
+ vm.setProp(objHandle, prop, propHandle);
3576
+ disposeIfNeeded(propHandle);
3577
+ }
3578
+ }
3579
+ vm.setProp(vm.global, key, objHandle);
3580
+ objHandle.dispose();
3581
+ for (const { prop, descriptor: descriptor2 } of getterSetterProps) {
3582
+ bridgeGetterSetter(vm, key, prop, descriptor2, context, toVmValue);
3583
+ }
3584
+ if (Object.isSealed(value)) {
3585
+ const sealResult = vm.evalCode(`Object.seal(globalThis['${key}']);`);
3586
+ if ("error" in sealResult)
3587
+ (_a = sealResult.error) == null ? void 0 : _a.dispose();
3588
+ else
3589
+ sealResult.value.dispose();
3590
+ }
3591
+ if (!Object.isExtensible(value)) {
3592
+ const preventResult = vm.evalCode(`Object.preventExtensions(globalThis['${key}']);`);
3593
+ if ("error" in preventResult)
3594
+ (_b = preventResult.error) == null ? void 0 : _b.dispose();
3595
+ else
3596
+ preventResult.value.dispose();
3597
+ }
3598
+ } else {
3599
+ trackedProperties.add(key);
3600
+ const valueHandle = toVmValue(value);
3601
+ vm.setProp(vm.global, key, valueHandle);
3602
+ disposeIfNeeded(valueHandle);
3603
+ }
3604
+ }
3605
+ }
3606
+ function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue) {
3607
+ var _a;
3608
+ const target = prop ? `${key}` : "globalThis";
3609
+ const propName = prop ?? key;
3610
+ const prefix = prop ? `${key}_${prop}` : key;
3611
+ let getterCode = "undefined";
3612
+ if (descriptor.get) {
3613
+ const getterBridge = vm.newFunction(`get_${propName}`, () => {
3614
+ try {
3615
+ const hostValue = prop ? context[key][prop] : context[key];
3616
+ return toVmValue(hostValue);
3617
+ } catch (err) {
3618
+ throw new Error(err instanceof Error ? err.message : String(err));
3619
+ }
3620
+ });
3621
+ const getterName = `__getter_${prefix}__`;
3622
+ vm.setProp(vm.global, getterName, getterBridge);
3623
+ getterBridge.dispose();
3624
+ getterCode = getterName;
3625
+ }
3626
+ let setterCode = "undefined";
3627
+ if (descriptor.set) {
3628
+ const setterBridge = vm.newFunction(`set_${propName}`, (valueHandle) => {
3629
+ try {
3630
+ const jsValue = vm.dump(valueHandle);
3631
+ if (prop) {
3632
+ context[key][prop] = jsValue;
3633
+ } else {
3634
+ context[key] = jsValue;
3635
+ }
3636
+ return vm.undefined;
3637
+ } catch (err) {
3638
+ throw new Error(err instanceof Error ? err.message : String(err));
3639
+ }
3640
+ });
3641
+ const setterName = `__setter_${prefix}__`;
3642
+ vm.setProp(vm.global, setterName, setterBridge);
3643
+ setterBridge.dispose();
3644
+ setterCode = setterName;
3645
+ }
3646
+ const definePropertyCode = `
3647
+ Object.defineProperty(${target}, '${propName}', {
3648
+ enumerable: true,
3649
+ configurable: ${descriptor.configurable !== false},
3650
+ get: ${getterCode},
3651
+ set: ${setterCode}
3652
+ });
3653
+ `;
3654
+ const result = vm.evalCode(definePropertyCode);
3655
+ if ("error" in result)
3656
+ (_a = result.error) == null ? void 0 : _a.dispose();
3657
+ else
3658
+ result.value.dispose();
3659
+ }
3660
+ function setupVariableTrackingBridge(vm, variables) {
3661
+ const varTrackFnHandle = vm.newFunction(
3662
+ Identifiers.VariableTrackingFnIdentifier,
3663
+ (nameHandle, getterHandle) => {
3664
+ var _a;
3665
+ const name = vm.getString(nameHandle);
3666
+ if (NO_TRACKING.includes(name))
3667
+ return;
3668
+ try {
3669
+ const valueResult = vm.callFunction(getterHandle, vm.undefined);
3670
+ if ("error" in valueResult) {
3671
+ variables[name] = "[[non-primitive]]";
3672
+ (_a = valueResult.error) == null ? void 0 : _a.dispose();
3673
+ return;
3674
+ }
3675
+ const value = vm.dump(valueResult.value);
3676
+ valueResult.value.dispose();
3677
+ if (typeof value === "function" || typeof value === "string" && value.includes("=>")) {
3678
+ variables[name] = "[[non-primitive]]";
3679
+ } else {
3680
+ variables[name] = value;
3681
+ }
3682
+ } catch {
3683
+ variables[name] = "[[non-primitive]]";
3684
+ }
3685
+ }
3686
+ );
3687
+ vm.setProp(vm.global, Identifiers.VariableTrackingFnIdentifier, varTrackFnHandle);
3688
+ varTrackFnHandle.dispose();
3689
+ }
3690
+ function buildScriptCode(transformedCode) {
3691
+ return `
3349
3692
  "use strict";
3350
3693
  globalThis.__llmz_result = undefined;
3351
3694
  globalThis.__llmz_result_set = false;
@@ -3356,12 +3699,12 @@ globalThis.__llmz_yields = [];
3356
3699
  (async () => {
3357
3700
  try {
3358
3701
  async function* __fn__() {
3359
- ${transformed.code}
3702
+ ${transformedCode}
3360
3703
  }
3361
3704
 
3362
3705
  const fn = __fn__();
3363
3706
  let iteration = 0;
3364
- const maxIterations = 10000; // Safety limit
3707
+ const maxIterations = 10000;
3365
3708
 
3366
3709
  while (iteration < maxIterations) {
3367
3710
  const { value, done } = await fn.next();
@@ -3372,12 +3715,8 @@ ${transformed.code}
3372
3715
  break;
3373
3716
  }
3374
3717
 
3375
- // Store yielded value
3376
3718
  globalThis.__llmz_yields.push(value);
3377
-
3378
- // Call yield handler
3379
3719
  await ${Identifiers.AsyncIterYieldFnIdentifier}(value);
3380
-
3381
3720
  iteration++;
3382
3721
  }
3383
3722
 
@@ -3385,229 +3724,62 @@ ${transformed.code}
3385
3724
  throw new Error('Maximum iterations exceeded');
3386
3725
  }
3387
3726
  } catch (err) {
3388
- // Store both the error message (which may contain serialized signal data)
3389
- // and the stack trace from QuickJS
3390
- // If err is a string (as thrown from promise rejection), use it directly
3391
- // Otherwise extract the message property
3392
3727
  globalThis.__llmz_error = typeof err === 'string' ? err : String(err.message || err || '');
3393
- // Force the stack to be converted to a string in QuickJS context
3394
3728
  globalThis.__llmz_error_stack = '' + (err.stack || '');
3395
3729
  }
3396
3730
  })();
3397
3731
  `.trim();
3398
- const copyBackContextFromVM = () => {
3399
- for (const key of trackedProperties) {
3400
- if (referenceProperties.has(key)) {
3401
- continue;
3402
- }
3403
- try {
3404
- const valueResult = vm.evalCode(`globalThis['${key}']`);
3405
- const vmValue = vm.dump(valueResult.unwrap());
3406
- valueResult.unwrap().dispose();
3407
- try {
3408
- context[key] = vmValue;
3409
- } catch {
3410
- }
3411
- } catch {
3412
- }
3413
- }
3414
- };
3415
- const execResult = vm.evalCode(scriptCode, "<quickjs>");
3416
- if ("error" in execResult) {
3417
- if (execResult.error) {
3418
- const err = vm.dump(execResult.error);
3419
- execResult.error.dispose();
3420
- throw new Error((err == null ? void 0 : err.message) || "Execution failed");
3421
- }
3422
- throw new Error("Execution failed");
3423
- }
3424
- execResult.value.dispose();
3425
- const maxIterations = 1e3;
3426
- let iteration = 0;
3427
- while (iteration < maxIterations) {
3428
- let hasJobs = false;
3429
- const maxJobs = 1e4;
3430
- for (let i = 0; i < maxJobs; i++) {
3431
- const pending = (_g = runtime.executePendingJobs) == null ? void 0 : _g.call(runtime, -1);
3432
- const jobCount = pending === void 0 ? 0 : pending.unwrap();
3433
- if (jobCount <= 0)
3434
- break;
3435
- hasJobs = true;
3436
- }
3437
- const currentPromises = [...pendingPromises];
3438
- pendingPromises.length = 0;
3439
- if (currentPromises.length > 0) {
3440
- if (signal == null ? void 0 : signal.aborted) {
3441
- const reason = signal.reason;
3442
- const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3443
- for (const { deferredPromise } of currentPromises) {
3444
- const errValue = vm.newString(abortMessage);
3445
- deferredPromise.reject(errValue);
3446
- errValue.dispose();
3447
- }
3448
- runtime.executePendingJobs();
3449
- break;
3450
- }
3451
- let abortListener = null;
3452
- if (signal) {
3453
- abortListener = () => {
3454
- const reason = signal.reason;
3455
- const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3456
- for (const { deferredPromise } of currentPromises) {
3457
- const errValue = vm.newString(abortMessage);
3458
- deferredPromise.reject(errValue);
3459
- errValue.dispose();
3460
- }
3461
- runtime.executePendingJobs();
3462
- };
3463
- signal.addEventListener("abort", abortListener);
3464
- }
3465
- try {
3466
- await Promise.all(
3467
- currentPromises.map(async ({ hostPromise, deferredPromise }) => {
3468
- if (signal == null ? void 0 : signal.aborted) {
3469
- return;
3470
- }
3471
- try {
3472
- const value = await hostPromise;
3473
- if (signal == null ? void 0 : signal.aborted) {
3474
- return;
3475
- }
3476
- const vmValue = toVmValue(value);
3477
- deferredPromise.resolve(vmValue);
3478
- disposeIfNeeded(vmValue);
3479
- } catch (err) {
3480
- if (signal == null ? void 0 : signal.aborted) {
3481
- return;
3482
- }
3483
- const serialized = err instanceof Error ? err.message : String(err);
3484
- const createErrorResult = vm.evalCode(`new Error(${JSON.stringify(serialized)})`);
3485
- if ("error" in createErrorResult) {
3486
- const errValue = vm.newString(serialized);
3487
- deferredPromise.reject(errValue);
3488
- errValue.dispose();
3489
- } else {
3490
- const errorHandle = createErrorResult.value;
3491
- deferredPromise.reject(errorHandle);
3492
- errorHandle.dispose();
3493
- }
3494
- }
3495
- })
3496
- );
3497
- } finally {
3498
- if (signal && abortListener) {
3499
- signal.removeEventListener("abort", abortListener);
3500
- }
3501
- }
3502
- runtime.executePendingJobs();
3503
- if (signal == null ? void 0 : signal.aborted) {
3504
- break;
3505
- }
3506
- }
3507
- if (!hasJobs && pendingPromises.length === 0) {
3508
- break;
3509
- }
3510
- iteration++;
3511
- }
3512
- if (iteration >= maxIterations) {
3513
- throw new Error("Maximum event loop iterations exceeded");
3514
- }
3515
- const errorResult = vm.evalCode("globalThis.__llmz_error");
3516
- const errorValue = vm.dump(errorResult.unwrap());
3517
- errorResult.unwrap().dispose();
3518
- if (signal == null ? void 0 : signal.aborted) {
3519
- const reason = signal.reason;
3520
- if (reason instanceof Error) {
3521
- throw reason;
3522
- }
3523
- throw new Error(reason ? String(reason) : "Execution was aborted");
3524
- }
3525
- if (errorValue !== null && errorValue !== "") {
3526
- try {
3527
- copyBackContextFromVM();
3528
- } catch {
3529
- }
3530
- const errorStackResult = vm.evalCode("globalThis.__llmz_error_stack");
3531
- const errorStack = vm.dump(errorStackResult.unwrap()) || "";
3532
- errorStackResult.unwrap().dispose();
3533
- const deserializedError = Signals.maybeDeserializeError(errorValue);
3534
- if (deserializedError instanceof VMSignal) {
3535
- deserializedError.stack = errorStack;
3536
- throw deserializedError;
3537
- }
3538
- const error = new Error(errorValue);
3539
- error.stack = errorStack;
3540
- throw error;
3541
- }
3542
- copyBackContextFromVM();
3543
- const resultSetResult = vm.evalCode("globalThis.__llmz_result_set");
3544
- const resultSet = vm.dump(resultSetResult.unwrap());
3545
- resultSetResult.unwrap().dispose();
3546
- let returnValue = void 0;
3547
- if (resultSet) {
3548
- const resultResult = vm.evalCode("globalThis.__llmz_result");
3549
- returnValue = vm.dump(resultResult.unwrap());
3550
- resultResult.unwrap().dispose();
3551
- }
3552
- returnValue = Signals.maybeDeserializeError(returnValue);
3553
- return {
3554
- success: true,
3555
- variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3556
- signal: returnValue instanceof VMSignal ? returnValue : void 0,
3557
- lines_executed: Array.from(lines_executed),
3558
- return_value: returnValue
3559
- };
3560
- } catch (err) {
3561
- if (signal == null ? void 0 : signal.aborted) {
3562
- const reason = signal.reason;
3563
- const abortError = reason instanceof Error ? reason : new Error(reason ? String(reason) : "Execution was aborted");
3564
- return handleErrorQuickJS(
3565
- abortError,
3566
- code,
3567
- consumer,
3568
- traces,
3569
- variables,
3570
- lines_executed,
3571
- userCodeStartLine,
3572
- currentToolCall
3573
- );
3574
- }
3575
- await Promise.all(
3576
- pendingPromises.map(async ({ hostPromise, deferredPromise }) => {
3577
- try {
3578
- const value = await hostPromise;
3579
- const vmValue = toVmValue(value);
3580
- deferredPromise.resolve(vmValue);
3581
- disposeIfNeeded(vmValue);
3582
- } catch (err2) {
3583
- const serialized = err2 instanceof Error ? err2.message : String(err2);
3584
- const errValue = vm.newString(serialized);
3585
- deferredPromise.reject(errValue);
3586
- errValue.dispose();
3587
- }
3588
- })
3589
- ).catch(() => {
3590
- });
3591
- return handleErrorQuickJS(
3592
- err,
3593
- code,
3594
- consumer,
3595
- traces,
3596
- variables,
3597
- lines_executed,
3598
- userCodeStartLine,
3599
- currentToolCall
3600
- );
3601
- } finally {
3602
- try {
3603
- vm.dispose();
3604
- } catch {
3605
- }
3606
- try {
3607
- runtime.dispose();
3608
- } catch {
3609
- }
3610
- }
3732
+ }
3733
+
3734
+ // src/vm/index.ts
3735
+ var MAX_VM_EXECUTION_TIME = 6e4;
3736
+ async function runAsyncFunction(context, code, traces = [], signal = null, timeout = MAX_VM_EXECUTION_TIME) {
3737
+ var _a;
3738
+ const transformed = (() => {
3739
+ try {
3740
+ return compile(code);
3741
+ } catch (err) {
3742
+ traces.push({
3743
+ type: "invalid_code_exception",
3744
+ message: (err == null ? void 0 : err.message) ?? "Unknown error",
3745
+ code,
3746
+ started_at: Date.now()
3747
+ });
3748
+ throw new InvalidCodeError(err.message, code);
3749
+ }
3750
+ })();
3751
+ const lines_executed = /* @__PURE__ */ new Map();
3752
+ const variables = {};
3753
+ const consumer = new import_source_map_js.SourceMapConsumer({
3754
+ version: transformed.map.version.toString(),
3755
+ mappings: transformed.map.mappings,
3756
+ names: transformed.map.names,
3757
+ sources: [transformed.map.file],
3758
+ sourcesContent: [transformed.code],
3759
+ file: transformed.map.file,
3760
+ sourceRoot: transformed.map.sourceRoot
3761
+ });
3762
+ context ??= {};
3763
+ for (const name of Array.from(transformed.variables)) {
3764
+ delete context[name];
3765
+ }
3766
+ let driver;
3767
+ const useQuickJS = typeof process === "undefined" || ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.USE_QUICKJS) !== "false";
3768
+ if (useQuickJS) {
3769
+ try {
3770
+ driver = new QuickJSDriver();
3771
+ return await driver.execute({
3772
+ transformed,
3773
+ consumer,
3774
+ context,
3775
+ traces,
3776
+ signal,
3777
+ timeout,
3778
+ code,
3779
+ lines_executed,
3780
+ variables,
3781
+ currentToolCall: void 0
3782
+ });
3611
3783
  } catch (quickjsError) {
3612
3784
  const debugInfo = {
3613
3785
  error: (quickjsError == null ? void 0 : quickjsError.message) || String(quickjsError),
@@ -3622,278 +3794,22 @@ ${transformed.code}
3622
3794
  console.warn("QuickJS failed to load, falling back to node driver.");
3623
3795
  console.warn("Error:", (quickjsError == null ? void 0 : quickjsError.message) || quickjsError);
3624
3796
  console.warn("Debug info:", JSON.stringify(debugInfo, null, 2));
3625
- DRIVER = "node";
3626
- }
3627
- }
3628
- if (DRIVER === "node") {
3629
- context[Identifiers.CommentFnIdentifier] = (comment, line) => traces.push({ type: "comment", comment, line, started_at: Date.now() });
3630
- context[Identifiers.LineTrackingFnIdentifier] = (line) => {
3631
- lines_executed.set(line, (lines_executed.get(line) ?? 0) + 1);
3632
- };
3633
- context[Identifiers.JSXFnIdentifier] = (tool, props, ...children) => createJsxComponent({
3634
- type: tool,
3635
- props,
3636
- children
3637
- });
3638
- context[Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
3639
- if (NO_TRACKING.includes(name)) {
3640
- return;
3641
- }
3642
- variables[name] = () => {
3643
- try {
3644
- const value = getter();
3645
- if (typeof value === "function") {
3646
- return "[[non-primitive]]";
3647
- }
3648
- return value;
3649
- } catch {
3650
- return "[[non-primitive]]";
3651
- }
3652
- };
3653
- };
3654
- let currentToolCall;
3655
- context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
3656
- var _a2;
3657
- const temp = Signals.maybeDeserializeError(outputOrError == null ? void 0 : outputOrError.message);
3658
- if (type === "end" && temp instanceof SnapshotSignal && (temp == null ? void 0 : temp.toolCall)) {
3659
- currentToolCall = {
3660
- ...temp.toolCall,
3661
- assignment: (_a2 = transformed.toolCalls.get(callId)) == null ? void 0 : _a2.assignment
3662
- };
3663
- }
3664
- };
3665
- context[Identifiers.ConsoleObjIdentifier] = {
3666
- log: (...args) => {
3667
- const message = args.shift();
3668
- traces.push({ type: "log", message, args, started_at: Date.now() });
3669
- }
3670
- };
3671
- context[Identifiers.AsyncIterYieldFnIdentifier] = async function(value) {
3672
- const startedAt = Date.now();
3673
- try {
3674
- if (typeof value.type !== "string" || value.type.trim().length === 0) {
3675
- throw new Error("A yield statement must yield a valid tool");
3676
- }
3677
- const toolName = Object.keys(context).find((x) => x.toUpperCase() === value.type.toUpperCase());
3678
- if (!toolName) {
3679
- throw new Error(`Yield tool "${value.type}", but tool is not found`);
3680
- }
3681
- await context[toolName](value);
3682
- } finally {
3683
- traces.push({ type: "yield", value, started_at: startedAt, ended_at: Date.now() });
3684
- }
3685
- };
3686
- const AsyncFunction = async function* () {
3687
- }.constructor;
3688
- return await (async () => {
3689
- const descriptors = Object.getOwnPropertyDescriptors(context);
3690
- const topLevelProperties = Object.keys(descriptors).filter(
3691
- (x) => !NO_TRACKING.includes(x) && descriptors[x] && typeof descriptors[x].value !== "function" && typeof descriptors[x].value !== "object"
3692
- );
3693
- const __report = (name, value) => {
3694
- if (context[name] !== void 0 && context[name] !== value) {
3695
- context[name] = value;
3696
- }
3697
- };
3698
- context.__report = __report;
3699
- const reportAll = topLevelProperties.map((x) => `__report("${x}", ${x})`).join(";");
3700
- const assigner = `let __${Identifiers.LineTrackingFnIdentifier} = ${Identifiers.LineTrackingFnIdentifier}; ${Identifiers.LineTrackingFnIdentifier} = function(line) { ${reportAll}; __${Identifiers.LineTrackingFnIdentifier}(line);}`;
3701
- const wrapper = `"use strict"; try { ${assigner};${transformed.code} } finally { ${reportAll} };`;
3702
- const fn = AsyncFunction(...Object.keys(context), wrapper);
3703
- const res = fn(...Object.values(context));
3704
- do {
3705
- const { value, done } = await res.next();
3706
- if (done) {
3707
- return value;
3708
- }
3709
- await context[Identifiers.AsyncIterYieldFnIdentifier](value);
3710
- } while (true);
3711
- })().then((res) => {
3712
- res = Signals.maybeDeserializeError(res);
3713
- return {
3714
- success: true,
3715
- variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3716
- signal: res instanceof VMSignal ? res : void 0,
3717
- lines_executed: Array.from(lines_executed),
3718
- return_value: res
3719
- };
3720
- }).catch((err) => handleErrorNode(err, code, consumer, traces, variables, lines_executed, currentToolCall)).catch((err) => handleCatch(err, traces, variables, lines_executed));
3721
- }
3722
- throw new Error(`Unknown driver: ${DRIVER}`);
3723
- }
3724
- var handleErrorQuickJS = (err, code, _consumer, traces, variables, lines_executed, userCodeStartLine, currentToolCall) => {
3725
- var _a, _b, _c;
3726
- err = Signals.maybeDeserializeError(err);
3727
- const lines = code.split("\n");
3728
- const stackTrace = err.stack || "";
3729
- const LINE_OFFSET = 1;
3730
- const regex = /<quickjs>:(\d+)/g;
3731
- const QUICKJS_WRAPPER_OFFSET = 10;
3732
- const matches = Array.from(stackTrace.matchAll(regex)).map((x) => {
3733
- const quickjsLine = Number(x[1]);
3734
- const transformedCodeLine = quickjsLine - QUICKJS_WRAPPER_OFFSET;
3735
- const line = Math.max(1, transformedCodeLine - userCodeStartLine + 1);
3736
- const actualLine = lines[line - LINE_OFFSET] ?? "";
3737
- const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
3738
- const minColumn = whiteSpacesCount;
3739
- return {
3740
- line,
3741
- column: minColumn
3742
- };
3743
- });
3744
- if (matches.length === 0 && lines_executed.size > 0) {
3745
- const lastLine2 = Math.max(...Array.from(lines_executed.keys()));
3746
- const actualLine = lines[lastLine2 - LINE_OFFSET] ?? "";
3747
- const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
3748
- matches.push({
3749
- line: lastLine2,
3750
- column: whiteSpacesCount
3751
- });
3752
- }
3753
- const lastLine = ((_a = maxBy_default(matches, (x) => x.line ?? 0)) == null ? void 0 : _a.line) ?? 0;
3754
- let debugUserCode = "";
3755
- let truncatedCode = "";
3756
- let truncated = false;
3757
- const appendCode = (line) => {
3758
- debugUserCode += line;
3759
- if (!truncated) {
3760
- truncatedCode += line;
3761
- }
3762
- };
3763
- for (let i = 0; i < lines.length; i++) {
3764
- const VM_OFFSET = 2;
3765
- const DISPLAY_OFFSET = 0;
3766
- const line = lines[i];
3767
- const correctedStackLineIndex = i + LINE_OFFSET + VM_OFFSET;
3768
- const match = matches.find((x) => x.line + VM_OFFSET === correctedStackLineIndex);
3769
- const paddedLineNumber = String(correctedStackLineIndex - VM_OFFSET - DISPLAY_OFFSET).padStart(3, "0");
3770
- if (match) {
3771
- appendCode(`> ${paddedLineNumber} | ${line}
3772
- `);
3773
- appendCode(` ${" ".repeat(paddedLineNumber.length + match.column)}^^^^^^^^^^
3774
- `);
3775
- if (match.line >= lastLine) {
3776
- truncated = true;
3777
- }
3778
- } else {
3779
- appendCode(` ${paddedLineNumber} | ${line}
3780
- `);
3781
- }
3782
- }
3783
- debugUserCode = cleanStackTrace(debugUserCode).trim();
3784
- truncatedCode = cleanStackTrace(truncatedCode).trim();
3785
- if (err instanceof VMSignal) {
3786
- const signalError = err;
3787
- signalError.stack = debugUserCode;
3788
- signalError.truncatedCode = truncatedCode;
3789
- signalError.variables = mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter);
3790
- signalError.toolCall = currentToolCall;
3791
- return {
3792
- success: true,
3793
- variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3794
- signal: err,
3795
- lines_executed: Array.from(lines_executed)
3796
- };
3797
- } else {
3798
- traces.push({
3799
- type: "code_execution_exception",
3800
- position: [((_b = matches[0]) == null ? void 0 : _b.line) ?? 0, ((_c = matches[0]) == null ? void 0 : _c.column) ?? 0],
3801
- message: err.message,
3802
- stackTrace: debugUserCode,
3803
- started_at: Date.now()
3804
- });
3805
- const codeError = new CodeExecutionError(err.message, code, debugUserCode);
3806
- const deserializedError = Signals.maybeDeserializeError(codeError);
3807
- return {
3808
- success: false,
3809
- variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3810
- error: deserializedError,
3811
- traces,
3812
- lines_executed: Array.from(lines_executed)
3813
- };
3814
- }
3815
- };
3816
- var handleErrorNode = (err, code, consumer, traces, variables, _lines_executed, currentToolCall) => {
3817
- var _a, _b, _c;
3818
- err = Signals.maybeDeserializeError(err);
3819
- const lines = code.split("\n");
3820
- const stackTrace = err.stack || "";
3821
- const LINE_OFFSET = 1;
3822
- const regex = /<anonymous>:(\d+):(\d+)/g;
3823
- const matches = [...stackTrace.matchAll(regex)].map((x) => {
3824
- const originalLine = consumer.originalPositionFor({
3825
- line: Number(x[1]),
3826
- column: Number(x[2])
3827
- });
3828
- const line = originalLine.line ?? Number(x[1]);
3829
- const actualLine = lines[line - LINE_OFFSET] ?? "";
3830
- const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
3831
- const minColumn = Math.max(whiteSpacesCount, originalLine.column);
3832
- return {
3833
- line,
3834
- column: Math.min(minColumn, Number(x[2]))
3835
- };
3836
- });
3837
- const lastLine = ((_a = maxBy_default(matches, (x) => x.line ?? 0)) == null ? void 0 : _a.line) ?? 0;
3838
- let debugUserCode = "";
3839
- let truncatedCode = "";
3840
- let truncated = false;
3841
- const appendCode = (line) => {
3842
- debugUserCode += line;
3843
- if (!truncated) {
3844
- truncatedCode += line;
3845
3797
  }
3846
- };
3847
- for (let i = 0; i < lines.length; i++) {
3848
- const VM_OFFSET = 2;
3849
- const DISPLAY_OFFSET = 0;
3850
- const line = lines[i];
3851
- const correctedStackLineIndex = i + LINE_OFFSET + VM_OFFSET;
3852
- const match = matches.find((x) => x.line + VM_OFFSET === correctedStackLineIndex);
3853
- const paddedLineNumber = String(correctedStackLineIndex - VM_OFFSET - DISPLAY_OFFSET).padStart(3, "0");
3854
- if (match) {
3855
- appendCode(`> ${paddedLineNumber} | ${line}
3856
- `);
3857
- appendCode(` ${" ".repeat(paddedLineNumber.length + match.column)}^^^^^^^^^^
3858
- `);
3859
- if (match.line >= lastLine) {
3860
- truncated = true;
3861
- }
3862
- } else {
3863
- appendCode(` ${paddedLineNumber} | ${line}
3864
- `);
3865
- }
3866
- }
3867
- debugUserCode = cleanStackTrace(debugUserCode).trim();
3868
- truncatedCode = cleanStackTrace(truncatedCode).trim();
3869
- if (err instanceof VMSignal) {
3870
- err.stack = debugUserCode;
3871
- err.truncatedCode = truncatedCode;
3872
- err.variables = mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter);
3873
- err.toolCall = currentToolCall;
3874
- throw err;
3875
- } else {
3876
- traces.push({
3877
- type: "code_execution_exception",
3878
- position: [((_b = matches[0]) == null ? void 0 : _b.line) ?? 0, ((_c = matches[0]) == null ? void 0 : _c.column) ?? 0],
3879
- message: err.message,
3880
- stackTrace: debugUserCode,
3881
- started_at: Date.now()
3882
- });
3883
- throw new CodeExecutionError(err.message, code, debugUserCode);
3884
3798
  }
3885
- };
3886
- var handleCatch = (err, traces, variables, lines_executed) => {
3887
- err = Signals.maybeDeserializeError(err);
3888
- return {
3889
- success: err instanceof VMSignal ? true : false,
3890
- variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3891
- error: err,
3892
- signal: err instanceof VMSignal ? err : void 0,
3799
+ driver = new NodeDriver();
3800
+ return await driver.execute({
3801
+ transformed,
3802
+ consumer,
3803
+ context,
3893
3804
  traces,
3894
- lines_executed: Array.from(lines_executed)
3895
- };
3896
- };
3805
+ signal,
3806
+ timeout,
3807
+ code,
3808
+ lines_executed,
3809
+ variables,
3810
+ currentToolCall: void 0
3811
+ });
3812
+ }
3897
3813
 
3898
3814
  export {
3899
3815
  runAsyncFunction