llmz 0.0.28 → 0.0.30

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.
@@ -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
  };
@@ -2031,19 +2036,59 @@ function escapeBracesInCodeFences(tsx) {
2031
2036
  let i = 0;
2032
2037
  let output = "";
2033
2038
  let insideFencedBlock = false;
2039
+ let jsxDepth = 0;
2040
+ let braceDepth = 0;
2034
2041
  while (i < tsx.length) {
2042
+ const char = tsx[i];
2043
+ if (char === "<" && !insideFencedBlock) {
2044
+ if (tsx[i + 1] !== "/") {
2045
+ jsxDepth++;
2046
+ } else {
2047
+ jsxDepth--;
2048
+ }
2049
+ output += char;
2050
+ i++;
2051
+ continue;
2052
+ }
2053
+ if (jsxDepth > 0 && !insideFencedBlock) {
2054
+ if (char === "{") {
2055
+ braceDepth++;
2056
+ output += char;
2057
+ i++;
2058
+ continue;
2059
+ } else if (char === "}") {
2060
+ braceDepth--;
2061
+ output += char;
2062
+ i++;
2063
+ continue;
2064
+ }
2065
+ }
2035
2066
  if (tsx.startsWith("```", i)) {
2036
2067
  insideFencedBlock = !insideFencedBlock;
2037
2068
  output += "```";
2038
2069
  i += 3;
2039
2070
  continue;
2040
2071
  }
2041
- if (insideFencedBlock && tsx[i] in HTML_ENTITIES) {
2042
- output += HTML_ENTITIES[tsx[i]];
2072
+ if (jsxDepth > 0 && braceDepth === 0 && !insideFencedBlock && char === "`") {
2073
+ const closingIndex = tsx.indexOf("`", i + 1);
2074
+ if (closingIndex !== -1) {
2075
+ const inlineCode = tsx.slice(i + 1, closingIndex);
2076
+ let escaped = "`";
2077
+ for (const c of inlineCode) {
2078
+ escaped += HTML_ENTITIES[c] || c;
2079
+ }
2080
+ escaped += "`";
2081
+ output += escaped;
2082
+ i = closingIndex + 1;
2083
+ continue;
2084
+ }
2085
+ }
2086
+ if (insideFencedBlock && char in HTML_ENTITIES) {
2087
+ output += HTML_ENTITIES[char];
2043
2088
  i++;
2044
2089
  continue;
2045
2090
  }
2046
- output += tsx[i];
2091
+ output += char;
2047
2092
  i++;
2048
2093
  }
2049
2094
  return output;
@@ -2146,7 +2191,7 @@ var replaceCommentBabelPlugin = function({
2146
2191
  return;
2147
2192
  }
2148
2193
  comments.sort((a, b) => a.start > b.start ? -1 : 1).forEach((comment) => {
2149
- var _a3;
2194
+ var _a;
2150
2195
  if (processed.has(comment.loc)) {
2151
2196
  return;
2152
2197
  }
@@ -2154,7 +2199,7 @@ var replaceCommentBabelPlugin = function({
2154
2199
  const commentCall = t.expressionStatement(
2155
2200
  t.callExpression(t.identifier(CommentFnIdentifier), [
2156
2201
  t.stringLiteral(comment.value.trim()),
2157
- t.numericLiteral(((_a3 = comment.loc) == null ? void 0 : _a3.start.line) ?? 0)
2202
+ t.numericLiteral(((_a = comment.loc) == null ? void 0 : _a.start.line) ?? 0)
2158
2203
  ])
2159
2204
  );
2160
2205
  const isInsideObjectProperty = t.isObjectProperty(node) || path2.findParent((path3) => t.isObjectProperty(path3.node));
@@ -2181,8 +2226,8 @@ var instrumentLastLinePlugin = function({
2181
2226
  return {
2182
2227
  visitor: {
2183
2228
  FunctionDeclaration(path) {
2184
- var _a3, _b;
2185
- if (((_a3 = path.node.id) == null ? void 0 : _a3.name) !== "__fn__") {
2229
+ var _a, _b;
2230
+ if (((_a = path.node.id) == null ? void 0 : _a.name) !== "__fn__") {
2186
2231
  return;
2187
2232
  }
2188
2233
  const statements = path.node.body.body;
@@ -2268,7 +2313,7 @@ var toolCallTrackingPlugin = (calls = /* @__PURE__ */ new Map()) => function({})
2268
2313
  skip.clear();
2269
2314
  },
2270
2315
  CallExpression(path) {
2271
- var _a3;
2316
+ var _a;
2272
2317
  if (skip.has(path.node) || path.findParent((p) => skip.has(p.node))) {
2273
2318
  return;
2274
2319
  }
@@ -2283,7 +2328,7 @@ var toolCallTrackingPlugin = (calls = /* @__PURE__ */ new Map()) => function({})
2283
2328
  (p) => p.isAssignmentExpression()
2284
2329
  );
2285
2330
  if (declaration) {
2286
- lval = (_a3 = declaration.get("declarations")[0]) == null ? void 0 : _a3.get("id");
2331
+ lval = (_a = declaration.get("declarations")[0]) == null ? void 0 : _a.get("id");
2287
2332
  }
2288
2333
  if (assignment) {
2289
2334
  const left = assignment.get("left");
@@ -2562,8 +2607,7 @@ function compile(code) {
2562
2607
  let output = Babel.transform(code, {
2563
2608
  parserOpts: {
2564
2609
  allowReturnOutsideFunction: true,
2565
- allowAwaitOutsideFunction: true,
2566
- startLine: -1
2610
+ allowAwaitOutsideFunction: true
2567
2611
  },
2568
2612
  presets: ["typescript"],
2569
2613
  plugins: [
@@ -2586,46 +2630,52 @@ function compile(code) {
2586
2630
  });
2587
2631
  const variables = /* @__PURE__ */ new Set();
2588
2632
  const toolCalls = /* @__PURE__ */ new Map();
2633
+ const codeWithMarkers = output.code;
2589
2634
  output = Babel.transform(output.code, {
2590
2635
  ...DEFAULT_TRANSFORM_OPTIONS,
2591
2636
  parserOpts: {
2592
- ...DEFAULT_TRANSFORM_OPTIONS.parserOpts,
2593
- startLine: -1
2637
+ ...DEFAULT_TRANSFORM_OPTIONS.parserOpts
2594
2638
  },
2595
2639
  plugins: [
2596
2640
  lineTrackingBabelPlugin,
2597
2641
  replaceCommentBabelPlugin,
2598
2642
  variableTrackingPlugin(variables),
2599
2643
  toolCallTrackingPlugin(toolCalls)
2600
- ]
2644
+ ],
2645
+ retainLines: true
2601
2646
  });
2602
2647
  let outputCode = output.code;
2603
2648
  outputCode = AsyncIterator.postProcessing(outputCode);
2604
2649
  outputCode = JSXNewLines.postProcessing(outputCode);
2605
2650
  return {
2606
2651
  code: outputCode,
2652
+ codeWithMarkers,
2653
+ // Code from before second transform, still has literal markers
2607
2654
  map: output.map,
2608
2655
  variables,
2609
2656
  toolCalls
2610
2657
  };
2611
2658
  }
2612
2659
 
2613
- // src/vm.ts
2614
- var IS_NODE = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
2615
- var _a;
2616
- var IS_CI = typeof process !== "undefined" && !!((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.CI);
2617
- var _a2;
2618
- var VM_DRIVER = (typeof process !== "undefined" && ((_a2 = process == null ? void 0 : process.env) == null ? void 0 : _a2.VM_DRIVER)) ?? (IS_CI ? "node" : "isolated-vm");
2619
- var CAN_USE_ISOLATED_VM = IS_NODE && VM_DRIVER === "isolated-vm";
2620
- var MAX_VM_EXECUTION_TIME = 6e4;
2621
- var requireEsm = async (id) => {
2622
- if (typeof globalThis.window === "undefined" && typeof globalThis.require !== "undefined") {
2623
- return eval("require")(id);
2624
- } else {
2625
- return await import(id).then((m) => m.default ?? m);
2660
+ // src/quickjs-variant.ts
2661
+ var getVariant = async () => {
2662
+ const module = await import("@jitl/quickjs-singlefile-browser-release-sync");
2663
+ return module.default;
2664
+ };
2665
+ var BundledReleaseSyncVariant = {
2666
+ type: "sync",
2667
+ importFFI: async () => {
2668
+ const variant = await getVariant();
2669
+ return variant.importFFI();
2670
+ },
2671
+ importModuleLoader: async () => {
2672
+ const variant = await getVariant();
2673
+ return variant.importModuleLoader();
2626
2674
  }
2627
2675
  };
2628
- var getIsolatedVm = async () => await requireEsm("isolated-vm");
2676
+
2677
+ // src/vm.ts
2678
+ var MAX_VM_EXECUTION_TIME = 6e4;
2629
2679
  var NO_TRACKING = [
2630
2680
  Identifiers.CommentFnIdentifier,
2631
2681
  Identifiers.ToolCallTrackerFnIdentifier,
@@ -2648,7 +2698,7 @@ function getCompiledCode(code, traces = []) {
2648
2698
  }
2649
2699
  }
2650
2700
  async function runAsyncFunction(context, code, traces = [], signal = null, timeout = MAX_VM_EXECUTION_TIME) {
2651
- var _a3;
2701
+ var _a, _b, _c, _d, _e, _f, _g;
2652
2702
  const transformed = getCompiledCode(code, traces);
2653
2703
  const lines_executed = /* @__PURE__ */ new Map();
2654
2704
  const variables = {};
@@ -2662,76 +2712,715 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
2662
2712
  sourceRoot: transformed.map.sourceRoot
2663
2713
  });
2664
2714
  context ??= {};
2665
- for (const name of transformed.variables) {
2715
+ for (const name of Array.from(transformed.variables)) {
2666
2716
  delete context[name];
2667
2717
  }
2668
- context[Identifiers.CommentFnIdentifier] = (comment, line) => traces.push({ type: "comment", comment, line, started_at: Date.now() });
2669
- context[Identifiers.LineTrackingFnIdentifier] = (line) => {
2670
- lines_executed.set(line, (lines_executed.get(line) ?? 0) + 1);
2671
- };
2672
- context[Identifiers.JSXFnIdentifier] = (tool, props, ...children) => createJsxComponent({
2673
- type: tool,
2674
- props,
2675
- children
2676
- });
2677
- context[Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
2678
- if (NO_TRACKING.includes(name)) {
2679
- return;
2680
- }
2681
- variables[name] = () => {
2682
- try {
2683
- const value = getter();
2684
- if (typeof value === "function") {
2685
- return "[[non-primitive]]";
2718
+ let DRIVER = "quickjs";
2719
+ if (typeof process !== "undefined" && ((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.USE_QUICKJS) === "false") {
2720
+ DRIVER = "node";
2721
+ }
2722
+ if (DRIVER === "quickjs") {
2723
+ try {
2724
+ context[Identifiers.CommentFnIdentifier] = (comment, line) => {
2725
+ if (comment.includes("__LLMZ_USER_CODE_START__") || comment.includes("__LLMZ_USER_CODE_END__")) {
2726
+ return;
2727
+ }
2728
+ traces.push({ type: "comment", comment, line, started_at: Date.now() });
2729
+ };
2730
+ const codeWithMarkers = transformed.codeWithMarkers || transformed.code;
2731
+ const markerLines = codeWithMarkers.split("\n");
2732
+ const USER_CODE_START_MARKER2 = "/* __LLMZ_USER_CODE_START__ */";
2733
+ let userCodeStartLine = -1;
2734
+ for (let i = 0; i < markerLines.length; i++) {
2735
+ if ((_b = markerLines[i]) == null ? void 0 : _b.includes(USER_CODE_START_MARKER2)) {
2736
+ userCodeStartLine = i + 1;
2737
+ break;
2686
2738
  }
2687
- return value;
2688
- } catch {
2689
- return "[[non-primitive]]";
2690
2739
  }
2691
- };
2692
- };
2693
- let currentToolCall;
2694
- context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
2695
- var _a4;
2696
- const temp = Signals.maybeDeserializeError(outputOrError == null ? void 0 : outputOrError.message);
2697
- if (type === "end" && temp instanceof SnapshotSignal && (temp == null ? void 0 : temp.toolCall)) {
2698
- currentToolCall = {
2699
- ...temp.toolCall,
2700
- assignment: (_a4 = transformed.toolCalls.get(callId)) == null ? void 0 : _a4.assignment
2740
+ context[Identifiers.LineTrackingFnIdentifier] = (line) => {
2741
+ const originalLine = consumer.originalPositionFor({
2742
+ line,
2743
+ column: 0
2744
+ });
2745
+ const mappedLine = originalLine.line ?? line;
2746
+ const userCodeLine = Math.max(1, mappedLine - userCodeStartLine);
2747
+ lines_executed.set(userCodeLine, (lines_executed.get(userCodeLine) ?? 0) + 1);
2701
2748
  };
2749
+ context[Identifiers.JSXFnIdentifier] = (tool, props, ...children) => createJsxComponent({
2750
+ type: tool,
2751
+ props,
2752
+ children
2753
+ });
2754
+ context[Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
2755
+ if (NO_TRACKING.includes(name)) {
2756
+ return;
2757
+ }
2758
+ variables[name] = () => {
2759
+ try {
2760
+ const value = getter();
2761
+ if (typeof value === "function") {
2762
+ return "[[non-primitive]]";
2763
+ }
2764
+ return value;
2765
+ } catch {
2766
+ return "[[non-primitive]]";
2767
+ }
2768
+ };
2769
+ };
2770
+ let currentToolCall;
2771
+ context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
2772
+ var _a2;
2773
+ const temp = Signals.maybeDeserializeError(outputOrError == null ? void 0 : outputOrError.message);
2774
+ if (type === "end" && temp instanceof SnapshotSignal && (temp == null ? void 0 : temp.toolCall)) {
2775
+ currentToolCall = {
2776
+ ...temp.toolCall,
2777
+ assignment: (_a2 = transformed.toolCalls.get(callId)) == null ? void 0 : _a2.assignment
2778
+ };
2779
+ }
2780
+ };
2781
+ context[Identifiers.ConsoleObjIdentifier] = {
2782
+ log: (...args) => {
2783
+ const message = args.shift();
2784
+ traces.push({ type: "log", message, args, started_at: Date.now() });
2785
+ }
2786
+ };
2787
+ context[Identifiers.AsyncIterYieldFnIdentifier] = async function(value) {
2788
+ const startedAt = Date.now();
2789
+ try {
2790
+ if (typeof value.type !== "string" || value.type.trim().length === 0) {
2791
+ throw new Error("A yield statement must yield a valid tool");
2792
+ }
2793
+ const toolName = Object.keys(context).find((x) => x.toUpperCase() === value.type.toUpperCase());
2794
+ if (!toolName) {
2795
+ throw new Error(`Yield tool "${value.type}", but tool is not found`);
2796
+ }
2797
+ await context[toolName](value);
2798
+ } finally {
2799
+ traces.push({ type: "yield", value, started_at: startedAt, ended_at: Date.now() });
2800
+ }
2801
+ };
2802
+ const QuickJS = await newQuickJSWASMModuleFromVariant(BundledReleaseSyncVariant);
2803
+ const runtime = QuickJS.newRuntime();
2804
+ runtime.setDebugMode(true);
2805
+ runtime.setMemoryLimit(128 * 1024 * 1024);
2806
+ const startTime = Date.now();
2807
+ const timeoutHandler = shouldInterruptAfterDeadline(startTime + timeout);
2808
+ runtime.setInterruptHandler(() => {
2809
+ if (signal == null ? void 0 : signal.aborted) {
2810
+ return true;
2811
+ }
2812
+ return timeoutHandler(runtime);
2813
+ });
2814
+ const vm = runtime.newContext();
2815
+ const trackedProperties = /* @__PURE__ */ new Set();
2816
+ const referenceProperties = /* @__PURE__ */ new Set();
2817
+ const pendingPromises = [];
2818
+ const toVmValue = (value) => {
2819
+ var _a2;
2820
+ if (typeof value === "string") {
2821
+ return vm.newString(value);
2822
+ } else if (typeof value === "number") {
2823
+ return vm.newNumber(value);
2824
+ } else if (typeof value === "boolean") {
2825
+ return value ? vm.true : vm.false;
2826
+ } else if (value === null) {
2827
+ return vm.null;
2828
+ } else if (value === void 0) {
2829
+ return vm.undefined;
2830
+ } else if (Array.isArray(value)) {
2831
+ const items = value.map((item) => {
2832
+ if (typeof item === "string") {
2833
+ return JSON.stringify(item);
2834
+ } else if (typeof item === "number" || typeof item === "boolean") {
2835
+ return String(item);
2836
+ } else if (item === null) {
2837
+ return "null";
2838
+ } else if (item === void 0) {
2839
+ return "undefined";
2840
+ } else if (typeof item === "object") {
2841
+ return JSON.stringify(item);
2842
+ }
2843
+ return "undefined";
2844
+ });
2845
+ const arrayLiteral = `[${items.join(",")}]`;
2846
+ const result = vm.evalCode(arrayLiteral);
2847
+ if ("error" in result) {
2848
+ (_a2 = result.error) == null ? void 0 : _a2.dispose();
2849
+ return vm.undefined;
2850
+ }
2851
+ const arrHandle = result.value;
2852
+ return arrHandle;
2853
+ } else if (typeof value === "object") {
2854
+ const obj = vm.newObject();
2855
+ for (const [k, v] of Object.entries(value)) {
2856
+ if (typeof v !== "function") {
2857
+ const propHandle = toVmValue(v);
2858
+ vm.setProp(obj, k, propHandle);
2859
+ if (propHandle !== vm.true && propHandle !== vm.false && propHandle !== vm.null && propHandle !== vm.undefined) {
2860
+ propHandle.dispose();
2861
+ }
2862
+ }
2863
+ }
2864
+ return obj;
2865
+ }
2866
+ return vm.undefined;
2867
+ };
2868
+ const bridgeFunction = (fn, _fnName = "anonymous") => {
2869
+ return (...argHandles) => {
2870
+ const args = argHandles.map((h) => vm.dump(h));
2871
+ try {
2872
+ const result = fn(...args);
2873
+ if (result && typeof result.then === "function") {
2874
+ const promise = vm.newPromise();
2875
+ pendingPromises.push({
2876
+ hostPromise: result,
2877
+ deferredPromise: promise
2878
+ });
2879
+ void promise.settled.then(() => {
2880
+ if (runtime.alive) {
2881
+ runtime.executePendingJobs();
2882
+ }
2883
+ });
2884
+ return promise.handle;
2885
+ }
2886
+ return toVmValue(result);
2887
+ } catch (err) {
2888
+ const serialized = err instanceof Error ? err.message : String(err);
2889
+ throw new Error(serialized);
2890
+ }
2891
+ };
2892
+ };
2893
+ try {
2894
+ for (const [key, value] of Object.entries(context)) {
2895
+ const descriptor = Object.getOwnPropertyDescriptor(context, key);
2896
+ if (descriptor && (descriptor.get || descriptor.set)) {
2897
+ referenceProperties.add(key);
2898
+ trackedProperties.add(key);
2899
+ let getterCode = "undefined";
2900
+ if (descriptor.get) {
2901
+ const getterBridge = vm.newFunction(`get_${key}`, () => {
2902
+ try {
2903
+ const hostValue = context[key];
2904
+ return toVmValue(hostValue);
2905
+ } catch (err) {
2906
+ const serialized = err instanceof Error ? err.message : String(err);
2907
+ throw new Error(serialized);
2908
+ }
2909
+ });
2910
+ const getterName = `__getter_${key}__`;
2911
+ vm.setProp(vm.global, getterName, getterBridge);
2912
+ getterBridge.dispose();
2913
+ getterCode = getterName;
2914
+ }
2915
+ let setterCode = "undefined";
2916
+ if (descriptor.set) {
2917
+ const setterBridge = vm.newFunction(`set_${key}`, (valueHandle) => {
2918
+ try {
2919
+ const jsValue = vm.dump(valueHandle);
2920
+ context[key] = jsValue;
2921
+ return vm.undefined;
2922
+ } catch (err) {
2923
+ const serialized = err instanceof Error ? err.message : String(err);
2924
+ throw new Error(serialized);
2925
+ }
2926
+ });
2927
+ const setterName = `__setter_${key}__`;
2928
+ vm.setProp(vm.global, setterName, setterBridge);
2929
+ setterBridge.dispose();
2930
+ setterCode = setterName;
2931
+ }
2932
+ const definePropertyCode = `
2933
+ Object.defineProperty(globalThis, '${key}', {
2934
+ enumerable: true,
2935
+ configurable: ${descriptor.configurable !== false},
2936
+ get: ${getterCode},
2937
+ set: ${setterCode}
2938
+ });
2939
+ `;
2940
+ const result = vm.evalCode(definePropertyCode);
2941
+ if ("error" in result) {
2942
+ (_c = result.error) == null ? void 0 : _c.dispose();
2943
+ } else {
2944
+ result.value.dispose();
2945
+ }
2946
+ continue;
2947
+ }
2948
+ if (typeof value === "function") {
2949
+ const fnHandle = vm.newFunction(key, bridgeFunction(value, key));
2950
+ vm.setProp(vm.global, key, fnHandle);
2951
+ fnHandle.dispose();
2952
+ } else if (Array.isArray(value)) {
2953
+ trackedProperties.add(key);
2954
+ const arrayHandle = toVmValue(value);
2955
+ vm.setProp(vm.global, key, arrayHandle);
2956
+ const shouldDispose = arrayHandle !== vm.true && arrayHandle !== vm.false && arrayHandle !== vm.null && arrayHandle !== vm.undefined;
2957
+ if (shouldDispose) {
2958
+ arrayHandle.dispose();
2959
+ }
2960
+ } else if (typeof value === "object" && value !== null) {
2961
+ trackedProperties.add(key);
2962
+ const objHandle = vm.newObject();
2963
+ const props = /* @__PURE__ */ new Set([...Object.keys(value), ...Object.getOwnPropertyNames(value)]);
2964
+ const getterSetterProps = [];
2965
+ for (const prop of props) {
2966
+ const propDescriptor = Object.getOwnPropertyDescriptor(value, prop);
2967
+ if (propDescriptor && (propDescriptor.get || propDescriptor.set)) {
2968
+ referenceProperties.add(`${key}.${prop}`);
2969
+ getterSetterProps.push({ prop, descriptor: propDescriptor });
2970
+ } else if (typeof value[prop] === "function") {
2971
+ const propFnHandle = vm.newFunction(prop, bridgeFunction(value[prop], `${key}.${prop}`));
2972
+ vm.setProp(objHandle, prop, propFnHandle);
2973
+ propFnHandle.dispose();
2974
+ } else {
2975
+ const propHandle = toVmValue(value[prop]);
2976
+ vm.setProp(objHandle, prop, propHandle);
2977
+ const shouldDispose = propHandle !== vm.true && propHandle !== vm.false && propHandle !== vm.null && propHandle !== vm.undefined;
2978
+ if (shouldDispose) {
2979
+ propHandle.dispose();
2980
+ }
2981
+ }
2982
+ }
2983
+ vm.setProp(vm.global, key, objHandle);
2984
+ objHandle.dispose();
2985
+ for (const { prop, descriptor: descriptor2 } of getterSetterProps) {
2986
+ let getterCode = "undefined";
2987
+ if (descriptor2.get) {
2988
+ const getterBridge = vm.newFunction(`get_${prop}`, () => {
2989
+ try {
2990
+ const hostValue = context[key][prop];
2991
+ return toVmValue(hostValue);
2992
+ } catch (err) {
2993
+ const serialized = err instanceof Error ? err.message : String(err);
2994
+ throw new Error(serialized);
2995
+ }
2996
+ });
2997
+ const getterName = `__getter_${key}_${prop}__`;
2998
+ vm.setProp(vm.global, getterName, getterBridge);
2999
+ getterBridge.dispose();
3000
+ getterCode = getterName;
3001
+ }
3002
+ let setterCode = "undefined";
3003
+ if (descriptor2.set) {
3004
+ const setterBridge = vm.newFunction(`set_${prop}`, (valueHandle) => {
3005
+ try {
3006
+ const jsValue = vm.dump(valueHandle);
3007
+ context[key][prop] = jsValue;
3008
+ return vm.undefined;
3009
+ } catch (err) {
3010
+ const serialized = err instanceof Error ? err.message : String(err);
3011
+ throw new Error(serialized);
3012
+ }
3013
+ });
3014
+ const setterName = `__setter_${key}_${prop}__`;
3015
+ vm.setProp(vm.global, setterName, setterBridge);
3016
+ setterBridge.dispose();
3017
+ setterCode = setterName;
3018
+ }
3019
+ const definePropertyCode = `
3020
+ Object.defineProperty(${key}, '${prop}', {
3021
+ enumerable: true,
3022
+ configurable: ${descriptor2.configurable !== false},
3023
+ get: ${getterCode},
3024
+ set: ${setterCode}
3025
+ });
3026
+ `;
3027
+ const result = vm.evalCode(definePropertyCode);
3028
+ if ("error" in result) {
3029
+ (_d = result.error) == null ? void 0 : _d.dispose();
3030
+ } else {
3031
+ result.value.dispose();
3032
+ }
3033
+ }
3034
+ if (Object.isSealed(value)) {
3035
+ const sealResult = vm.evalCode(`Object.seal(globalThis['${key}']);`);
3036
+ if ("error" in sealResult) {
3037
+ (_e = sealResult.error) == null ? void 0 : _e.dispose();
3038
+ } else {
3039
+ sealResult.value.dispose();
3040
+ }
3041
+ }
3042
+ if (!Object.isExtensible(value)) {
3043
+ const preventResult = vm.evalCode(`Object.preventExtensions(globalThis['${key}']);`);
3044
+ if ("error" in preventResult) {
3045
+ (_f = preventResult.error) == null ? void 0 : _f.dispose();
3046
+ } else {
3047
+ preventResult.value.dispose();
3048
+ }
3049
+ }
3050
+ } else {
3051
+ trackedProperties.add(key);
3052
+ const valueHandle = toVmValue(value);
3053
+ vm.setProp(vm.global, key, valueHandle);
3054
+ const shouldDispose = valueHandle !== vm.true && valueHandle !== vm.false && valueHandle !== vm.null && valueHandle !== vm.undefined;
3055
+ if (shouldDispose) {
3056
+ valueHandle.dispose();
3057
+ }
3058
+ }
3059
+ }
3060
+ const varTrackFnHandle = vm.newFunction(
3061
+ Identifiers.VariableTrackingFnIdentifier,
3062
+ (nameHandle, getterHandle) => {
3063
+ var _a2;
3064
+ const name = vm.getString(nameHandle);
3065
+ if (NO_TRACKING.includes(name)) {
3066
+ return;
3067
+ }
3068
+ try {
3069
+ const valueResult = vm.callFunction(getterHandle, vm.undefined);
3070
+ if ("error" in valueResult) {
3071
+ variables[name] = "[[non-primitive]]";
3072
+ (_a2 = valueResult.error) == null ? void 0 : _a2.dispose();
3073
+ return;
3074
+ }
3075
+ const value = vm.dump(valueResult.value);
3076
+ valueResult.value.dispose();
3077
+ if (typeof value === "function" || typeof value === "string" && value.includes("=>")) {
3078
+ variables[name] = "[[non-primitive]]";
3079
+ } else {
3080
+ variables[name] = value;
3081
+ }
3082
+ } catch {
3083
+ variables[name] = "[[non-primitive]]";
3084
+ }
3085
+ }
3086
+ );
3087
+ vm.setProp(vm.global, Identifiers.VariableTrackingFnIdentifier, varTrackFnHandle);
3088
+ varTrackFnHandle.dispose();
3089
+ const scriptCode = `
3090
+ "use strict";
3091
+ globalThis.__llmz_result = undefined;
3092
+ globalThis.__llmz_result_set = false;
3093
+ globalThis.__llmz_error = null;
3094
+ globalThis.__llmz_error_stack = null;
3095
+ globalThis.__llmz_yields = [];
3096
+
3097
+ (async () => {
3098
+ try {
3099
+ async function* __fn__() {
3100
+ ${transformed.code}
2702
3101
  }
2703
- };
2704
- context[Identifiers.ConsoleObjIdentifier] = {
2705
- log: (...args) => {
2706
- const message = args.shift();
2707
- traces.push({ type: "log", message, args, started_at: Date.now() });
2708
- }
2709
- };
2710
- context[Identifiers.AsyncIterYieldFnIdentifier] = async function(value) {
2711
- const startedAt = Date.now();
2712
- try {
2713
- if (typeof value.type !== "string" || value.type.trim().length === 0) {
2714
- throw new Error("A yield statement must yield a valid tool");
2715
- }
2716
- const toolName = Object.keys(context).find((x) => x.toUpperCase() === value.type.toUpperCase());
2717
- if (!toolName) {
2718
- throw new Error(`Yield tool "${value.type}", but tool is not found`);
3102
+
3103
+ const fn = __fn__();
3104
+ let iteration = 0;
3105
+ const maxIterations = 10000; // Safety limit
3106
+
3107
+ while (iteration < maxIterations) {
3108
+ const { value, done } = await fn.next();
3109
+
3110
+ if (done) {
3111
+ globalThis.__llmz_result = value;
3112
+ globalThis.__llmz_result_set = true;
3113
+ break;
2719
3114
  }
2720
- await context[toolName](value);
2721
- } finally {
2722
- traces.push({ type: "yield", value, started_at: startedAt, ended_at: Date.now() });
3115
+
3116
+ // Store yielded value
3117
+ globalThis.__llmz_yields.push(value);
3118
+
3119
+ // Call yield handler
3120
+ await ${Identifiers.AsyncIterYieldFnIdentifier}(value);
3121
+
3122
+ iteration++;
2723
3123
  }
2724
- };
2725
- let DRIVER = CAN_USE_ISOLATED_VM ? "isolated-vm" : "node";
2726
- let isolatedVm;
2727
- if (DRIVER === "isolated-vm") {
2728
- try {
2729
- isolatedVm = await getIsolatedVm();
2730
- } catch {
3124
+
3125
+ if (iteration >= maxIterations) {
3126
+ throw new Error('Maximum iterations exceeded');
3127
+ }
3128
+ } catch (err) {
3129
+ // Store both the error message (which may contain serialized signal data)
3130
+ // and the stack trace from QuickJS
3131
+ // If err is a string (as thrown from promise rejection), use it directly
3132
+ // Otherwise extract the message property
3133
+ globalThis.__llmz_error = typeof err === 'string' ? err : String(err.message || err || '');
3134
+ // Force the stack to be converted to a string in QuickJS context
3135
+ globalThis.__llmz_error_stack = '' + (err.stack || '');
3136
+ }
3137
+ })();
3138
+ `.trim();
3139
+ const copyBackContextFromVM = () => {
3140
+ for (const key of trackedProperties) {
3141
+ if (referenceProperties.has(key)) {
3142
+ continue;
3143
+ }
3144
+ try {
3145
+ const valueResult = vm.evalCode(`globalThis['${key}']`);
3146
+ const vmValue = vm.dump(valueResult.unwrap());
3147
+ valueResult.unwrap().dispose();
3148
+ try {
3149
+ context[key] = vmValue;
3150
+ } catch {
3151
+ }
3152
+ } catch {
3153
+ }
3154
+ }
3155
+ };
3156
+ const execResult = vm.evalCode(scriptCode, "<quickjs>");
3157
+ if ("error" in execResult) {
3158
+ if (execResult.error) {
3159
+ const err = vm.dump(execResult.error);
3160
+ execResult.error.dispose();
3161
+ throw new Error((err == null ? void 0 : err.message) || "Execution failed");
3162
+ }
3163
+ throw new Error("Execution failed");
3164
+ }
3165
+ execResult.value.dispose();
3166
+ const maxIterations = 1e3;
3167
+ let iteration = 0;
3168
+ while (iteration < maxIterations) {
3169
+ let hasJobs = false;
3170
+ const maxJobs = 1e4;
3171
+ for (let i = 0; i < maxJobs; i++) {
3172
+ const pending = (_g = runtime.executePendingJobs) == null ? void 0 : _g.call(runtime, -1);
3173
+ const jobCount = pending === void 0 ? 0 : pending.unwrap();
3174
+ if (jobCount <= 0)
3175
+ break;
3176
+ hasJobs = true;
3177
+ }
3178
+ const currentPromises = [...pendingPromises];
3179
+ pendingPromises.length = 0;
3180
+ if (currentPromises.length > 0) {
3181
+ if (signal == null ? void 0 : signal.aborted) {
3182
+ const reason = signal.reason;
3183
+ const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3184
+ for (const { deferredPromise } of currentPromises) {
3185
+ const errValue = vm.newString(abortMessage);
3186
+ deferredPromise.reject(errValue);
3187
+ errValue.dispose();
3188
+ }
3189
+ runtime.executePendingJobs();
3190
+ break;
3191
+ }
3192
+ let abortListener = null;
3193
+ if (signal) {
3194
+ abortListener = () => {
3195
+ const reason = signal.reason;
3196
+ const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3197
+ for (const { deferredPromise } of currentPromises) {
3198
+ const errValue = vm.newString(abortMessage);
3199
+ deferredPromise.reject(errValue);
3200
+ errValue.dispose();
3201
+ }
3202
+ runtime.executePendingJobs();
3203
+ };
3204
+ signal.addEventListener("abort", abortListener);
3205
+ }
3206
+ try {
3207
+ await Promise.all(
3208
+ currentPromises.map(async ({ hostPromise, deferredPromise }) => {
3209
+ if (signal == null ? void 0 : signal.aborted) {
3210
+ return;
3211
+ }
3212
+ try {
3213
+ const value = await hostPromise;
3214
+ if (signal == null ? void 0 : signal.aborted) {
3215
+ return;
3216
+ }
3217
+ const vmValue = toVmValue(value);
3218
+ deferredPromise.resolve(vmValue);
3219
+ } catch (err) {
3220
+ if (signal == null ? void 0 : signal.aborted) {
3221
+ return;
3222
+ }
3223
+ const serialized = err instanceof Error ? err.message : String(err);
3224
+ const createErrorResult = vm.evalCode(`new Error(${JSON.stringify(serialized)})`);
3225
+ if ("error" in createErrorResult) {
3226
+ const errValue = vm.newString(serialized);
3227
+ deferredPromise.reject(errValue);
3228
+ errValue.dispose();
3229
+ } else {
3230
+ const errorHandle = createErrorResult.value;
3231
+ deferredPromise.reject(errorHandle);
3232
+ errorHandle.dispose();
3233
+ }
3234
+ }
3235
+ })
3236
+ );
3237
+ } finally {
3238
+ if (signal && abortListener) {
3239
+ signal.removeEventListener("abort", abortListener);
3240
+ }
3241
+ }
3242
+ runtime.executePendingJobs();
3243
+ if (signal == null ? void 0 : signal.aborted) {
3244
+ break;
3245
+ }
3246
+ }
3247
+ if (!hasJobs && pendingPromises.length === 0) {
3248
+ break;
3249
+ }
3250
+ iteration++;
3251
+ }
3252
+ if (iteration >= maxIterations) {
3253
+ throw new Error("Maximum event loop iterations exceeded");
3254
+ }
3255
+ const errorResult = vm.evalCode("globalThis.__llmz_error");
3256
+ const errorValue = vm.dump(errorResult.unwrap());
3257
+ errorResult.unwrap().dispose();
3258
+ if (signal == null ? void 0 : signal.aborted) {
3259
+ const reason = signal.reason;
3260
+ if (reason instanceof Error) {
3261
+ throw reason;
3262
+ }
3263
+ throw new Error(reason ? String(reason) : "Execution was aborted");
3264
+ }
3265
+ if (errorValue !== null && errorValue !== "") {
3266
+ try {
3267
+ copyBackContextFromVM();
3268
+ } catch {
3269
+ }
3270
+ const errorStackResult = vm.evalCode("globalThis.__llmz_error_stack");
3271
+ const errorStack = vm.dump(errorStackResult.unwrap()) || "";
3272
+ errorStackResult.unwrap().dispose();
3273
+ const deserializedError = Signals.maybeDeserializeError(errorValue);
3274
+ if (deserializedError instanceof VMSignal) {
3275
+ deserializedError.stack = errorStack;
3276
+ throw deserializedError;
3277
+ }
3278
+ const error = new Error(errorValue);
3279
+ error.stack = errorStack;
3280
+ throw error;
3281
+ }
3282
+ copyBackContextFromVM();
3283
+ const resultSetResult = vm.evalCode("globalThis.__llmz_result_set");
3284
+ const resultSet = vm.dump(resultSetResult.unwrap());
3285
+ resultSetResult.unwrap().dispose();
3286
+ let returnValue = void 0;
3287
+ if (resultSet) {
3288
+ const resultResult = vm.evalCode("globalThis.__llmz_result");
3289
+ returnValue = vm.dump(resultResult.unwrap());
3290
+ resultResult.unwrap().dispose();
3291
+ }
3292
+ returnValue = Signals.maybeDeserializeError(returnValue);
3293
+ return {
3294
+ success: true,
3295
+ variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3296
+ signal: returnValue instanceof VMSignal ? returnValue : void 0,
3297
+ lines_executed: Array.from(lines_executed),
3298
+ return_value: returnValue
3299
+ };
3300
+ } catch (err) {
3301
+ if (signal == null ? void 0 : signal.aborted) {
3302
+ const reason = signal.reason;
3303
+ const abortError = reason instanceof Error ? reason : new Error(reason ? String(reason) : "Execution was aborted");
3304
+ return handleErrorQuickJS(
3305
+ abortError,
3306
+ code,
3307
+ consumer,
3308
+ traces,
3309
+ variables,
3310
+ lines_executed,
3311
+ userCodeStartLine,
3312
+ currentToolCall
3313
+ );
3314
+ }
3315
+ await Promise.all(
3316
+ pendingPromises.map(async ({ hostPromise, deferredPromise }) => {
3317
+ try {
3318
+ const value = await hostPromise;
3319
+ const vmValue = toVmValue(value);
3320
+ deferredPromise.resolve(vmValue);
3321
+ } catch (err2) {
3322
+ const serialized = err2 instanceof Error ? err2.message : String(err2);
3323
+ const errValue = vm.newString(serialized);
3324
+ deferredPromise.reject(errValue);
3325
+ }
3326
+ })
3327
+ ).catch(() => {
3328
+ });
3329
+ return handleErrorQuickJS(
3330
+ err,
3331
+ code,
3332
+ consumer,
3333
+ traces,
3334
+ variables,
3335
+ lines_executed,
3336
+ userCodeStartLine,
3337
+ currentToolCall
3338
+ );
3339
+ } finally {
3340
+ try {
3341
+ vm.dispose();
3342
+ } catch {
3343
+ }
3344
+ try {
3345
+ runtime.dispose();
3346
+ } catch {
3347
+ }
3348
+ }
3349
+ } catch (quickjsError) {
3350
+ const debugInfo = {
3351
+ error: (quickjsError == null ? void 0 : quickjsError.message) || String(quickjsError),
3352
+ errorStack: quickjsError == null ? void 0 : quickjsError.stack,
3353
+ wasmSource: BundledReleaseSyncVariant._wasmSource,
3354
+ wasmLoadedSuccessfully: BundledReleaseSyncVariant._wasmLoadedSuccessfully,
3355
+ wasmSize: BundledReleaseSyncVariant._wasmSize,
3356
+ wasmLoadError: BundledReleaseSyncVariant._wasmLoadError,
3357
+ nodeVersion: typeof process !== "undefined" && process.version ? process.version : "undefined",
3358
+ platform: typeof process !== "undefined" && process.platform ? process.platform : "undefined"
3359
+ };
3360
+ console.warn("QuickJS failed to load, falling back to node driver.");
3361
+ console.warn("Error:", (quickjsError == null ? void 0 : quickjsError.message) || quickjsError);
3362
+ console.warn("Debug info:", JSON.stringify(debugInfo, null, 2));
2731
3363
  DRIVER = "node";
2732
3364
  }
2733
3365
  }
2734
3366
  if (DRIVER === "node") {
3367
+ context[Identifiers.CommentFnIdentifier] = (comment, line) => traces.push({ type: "comment", comment, line, started_at: Date.now() });
3368
+ context[Identifiers.LineTrackingFnIdentifier] = (line) => {
3369
+ lines_executed.set(line, (lines_executed.get(line) ?? 0) + 1);
3370
+ };
3371
+ context[Identifiers.JSXFnIdentifier] = (tool, props, ...children) => createJsxComponent({
3372
+ type: tool,
3373
+ props,
3374
+ children
3375
+ });
3376
+ context[Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
3377
+ if (NO_TRACKING.includes(name)) {
3378
+ return;
3379
+ }
3380
+ variables[name] = () => {
3381
+ try {
3382
+ const value = getter();
3383
+ if (typeof value === "function") {
3384
+ return "[[non-primitive]]";
3385
+ }
3386
+ return value;
3387
+ } catch {
3388
+ return "[[non-primitive]]";
3389
+ }
3390
+ };
3391
+ };
3392
+ let currentToolCall;
3393
+ context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
3394
+ var _a2;
3395
+ const temp = Signals.maybeDeserializeError(outputOrError == null ? void 0 : outputOrError.message);
3396
+ if (type === "end" && temp instanceof SnapshotSignal && (temp == null ? void 0 : temp.toolCall)) {
3397
+ currentToolCall = {
3398
+ ...temp.toolCall,
3399
+ assignment: (_a2 = transformed.toolCalls.get(callId)) == null ? void 0 : _a2.assignment
3400
+ };
3401
+ }
3402
+ };
3403
+ context[Identifiers.ConsoleObjIdentifier] = {
3404
+ log: (...args) => {
3405
+ const message = args.shift();
3406
+ traces.push({ type: "log", message, args, started_at: Date.now() });
3407
+ }
3408
+ };
3409
+ context[Identifiers.AsyncIterYieldFnIdentifier] = async function(value) {
3410
+ const startedAt = Date.now();
3411
+ try {
3412
+ if (typeof value.type !== "string" || value.type.trim().length === 0) {
3413
+ throw new Error("A yield statement must yield a valid tool");
3414
+ }
3415
+ const toolName = Object.keys(context).find((x) => x.toUpperCase() === value.type.toUpperCase());
3416
+ if (!toolName) {
3417
+ throw new Error(`Yield tool "${value.type}", but tool is not found`);
3418
+ }
3419
+ await context[toolName](value);
3420
+ } finally {
3421
+ traces.push({ type: "yield", value, started_at: startedAt, ended_at: Date.now() });
3422
+ }
3423
+ };
2735
3424
  const AsyncFunction = async function* () {
2736
3425
  }.constructor;
2737
3426
  return await (async () => {
@@ -2766,293 +3455,109 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
2766
3455
  lines_executed: Array.from(lines_executed),
2767
3456
  return_value: res
2768
3457
  };
2769
- }).catch((err) => handleError(err, code, consumer, traces, variables, lines_executed, currentToolCall, DRIVER)).catch((err) => handleCatch(err, traces, variables, lines_executed));
2770
- }
2771
- if (!isolatedVm) {
2772
- throw new Error("isolated-vm is not available");
2773
- }
2774
- const isolate = new isolatedVm.Isolate({ memoryLimit: 128 });
2775
- const isolatedContext = await isolate.createContext();
2776
- const jail = isolatedContext.global;
2777
- const trackedProperties = /* @__PURE__ */ new Set();
2778
- const referenceProperties = /* @__PURE__ */ new Set();
2779
- const abort = () => {
2780
- if (DRIVER === "isolated-vm") {
2781
- isolate.dispose();
2782
- isolatedContext.release();
2783
- }
2784
- };
2785
- if (signal) {
2786
- signal.addEventListener("abort", abort);
3458
+ }).catch((err) => handleErrorNode(err, code, consumer, traces, variables, lines_executed, currentToolCall)).catch((err) => handleCatch(err, traces, variables, lines_executed));
2787
3459
  }
2788
- await jail.set("global", jail.derefInto());
2789
- for (const key of Object.keys(context)) {
2790
- if (typeof context[key] === "function") {
2791
- await isolatedContext.evalClosure(
2792
- `global['${key}'] = (...args) => $0.applySyncPromise(null, args, {arguments: {copy: true}});`,
2793
- [async (...args) => new isolatedVm.ExternalCopy(await context[key](...args)).copyInto()],
2794
- {
2795
- arguments: { reference: true }
2796
- }
2797
- );
2798
- } else if (typeof context[key] === "object" && !((_a3 = Object.getOwnPropertyDescriptor(context, key)) == null ? void 0 : _a3.get)) {
2799
- try {
2800
- trackedProperties.add(key);
2801
- const initial = Array.isArray(context[key]) ? new Array(context[key].length) : {};
2802
- await jail.set(key, initial, { copy: true });
2803
- const props = /* @__PURE__ */ new Set([...Object.keys(context[key]), ...Object.getOwnPropertyNames(context[key])]);
2804
- for (const prop of props) {
2805
- try {
2806
- if (typeof context[key][prop] === "function") {
2807
- await isolatedContext.evalClosure(
2808
- `global['${key}']['${prop}'] = (...args) => $0.applySyncPromise(null, args, {arguments: {copy: true}});`,
2809
- [async (...args) => new isolatedVm.ExternalCopy(await context[key][prop](...args)).copyInto()],
2810
- {
2811
- arguments: { reference: true }
2812
- }
2813
- );
2814
- } else {
2815
- const descriptor = Object.getOwnPropertyDescriptor(context[key], prop);
2816
- if (descriptor && (descriptor.get || descriptor.set)) {
2817
- referenceProperties.add(`${key}.${prop}`);
2818
- await isolatedContext.evalClosure(
2819
- `Object.defineProperty(global['${key}'], '${prop}', {
2820
- get: () => $0.applySync(null, [], {arguments: {copy: true}}),
2821
- set: (value) => $1.applySync(null, [value], {arguments: {copy: true}})
2822
- });`,
2823
- [
2824
- () => context[key][prop],
2825
- (value) => {
2826
- context[key][prop] = value;
2827
- return value;
2828
- }
2829
- ],
2830
- { arguments: { reference: true } }
2831
- );
2832
- } else {
2833
- await isolatedContext.evalClosure(`global['${key}']['${prop}'] = $0;`, [context[key][prop]], {
2834
- arguments: { copy: true }
2835
- });
2836
- }
2837
- }
2838
- } catch (err) {
2839
- console.error(`Could not copy "${key}.${prop}" (typeof = ${typeof context[key][prop]}) to the sandbox`, err);
2840
- }
2841
- }
2842
- } catch (err) {
2843
- console.error(`Could not create object "${key}" (typeof = ${typeof context[key]}) in the sandbox`, err);
2844
- }
2845
- } else {
2846
- try {
2847
- const descriptor = Object.getOwnPropertyDescriptor(context, key);
2848
- if (descriptor && (descriptor.get || descriptor.set)) {
2849
- referenceProperties.add(key);
2850
- await isolatedContext.evalClosure(
2851
- `Object.defineProperty(global, '${key}', {
2852
- get: () => $0.applySync(null, [], {arguments: {copy: true}}),
2853
- set: (value) => $1.applySync(null, [value], {arguments: {copy: true}})
2854
- });`,
2855
- [
2856
- () => context[key],
2857
- (value) => {
2858
- context[key] = value;
2859
- return value;
2860
- }
2861
- ],
2862
- { arguments: { reference: true } }
2863
- );
2864
- } else {
2865
- await jail.set(key, context[key], { copy: true });
2866
- }
2867
- trackedProperties.add(key);
2868
- } catch (err) {
2869
- console.error(`Could not copy "${key}" to the sandbox (typeof = ${typeof context[key]})`, err);
2870
- }
2871
- }
2872
- }
2873
- for (const key of Object.keys(context)) {
2874
- if (Object.isSealed(context[key])) {
2875
- await isolatedContext.evalClosure(`Object.seal(global['${key}']);`, []);
2876
- }
2877
- if (!Object.isExtensible(context[key])) {
2878
- await isolatedContext.evalClosure(`Object.preventExtensions(global['${key}']);`, []);
2879
- }
2880
- }
2881
- const Console = await jail.get(Identifiers.ConsoleObjIdentifier, { reference: true });
2882
- await Console.set("log", (...args) => {
2883
- const message = args.shift();
2884
- traces.push({ type: "log", message, args, started_at: Date.now() });
2885
- });
2886
- await isolatedContext.evalClosure(
2887
- `${Identifiers.VariableTrackingFnIdentifier} = (name, getter) => {
2888
- const value = getter();
2889
- try {
2890
- $0.applySync(null, [name, getter()], { arguments: { copy: true } });
2891
- } catch {
2892
- $0.applySync(null, [name, '[[non-primitive]]'], { arguments: { copy: true } });
2893
- }
2894
- };`,
2895
- [
2896
- (name, value) => {
2897
- variables[name] = value;
2898
- }
2899
- ],
2900
- {
2901
- arguments: { reference: true }
2902
- }
2903
- );
2904
- const scriptCode = `
2905
- "use strict";
2906
- new Promise(async (resolve) => {
2907
-
2908
- async function* __fn__() {
2909
- ${transformed.code}
3460
+ throw new Error(`Unknown driver: ${DRIVER}`);
2910
3461
  }
2911
-
2912
- const fn = __fn__();
2913
- do {
2914
- const { value, done } = await fn.next();
2915
- if (done) {
2916
- const ret = await value;
2917
- return resolve(ret);
3462
+ var handleErrorQuickJS = (err, code, _consumer, traces, variables, lines_executed, userCodeStartLine, currentToolCall) => {
3463
+ var _a, _b, _c;
3464
+ err = Signals.maybeDeserializeError(err);
3465
+ const lines = code.split("\n");
3466
+ const stackTrace = err.stack || "";
3467
+ const LINE_OFFSET = 1;
3468
+ const regex = /<quickjs>:(\d+)/g;
3469
+ const QUICKJS_WRAPPER_OFFSET = 10;
3470
+ const matches = Array.from(stackTrace.matchAll(regex)).map((x) => {
3471
+ const quickjsLine = Number(x[1]);
3472
+ const transformedCodeLine = quickjsLine - QUICKJS_WRAPPER_OFFSET;
3473
+ const line = Math.max(1, transformedCodeLine - userCodeStartLine + 1);
3474
+ const actualLine = lines[line - LINE_OFFSET] ?? "";
3475
+ const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
3476
+ const minColumn = whiteSpacesCount;
3477
+ return {
3478
+ line,
3479
+ column: minColumn
3480
+ };
3481
+ });
3482
+ if (matches.length === 0 && lines_executed.size > 0) {
3483
+ const lastLine2 = Math.max(...Array.from(lines_executed.keys()));
3484
+ const actualLine = lines[lastLine2 - LINE_OFFSET] ?? "";
3485
+ const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
3486
+ matches.push({
3487
+ line: lastLine2,
3488
+ column: whiteSpacesCount
3489
+ });
2918
3490
  }
2919
- await ${Identifiers.AsyncIterYieldFnIdentifier}(value);
2920
- } while(true);
2921
-
2922
- })`.trim();
2923
- const script = await isolate.compileScript(scriptCode, { filename: "<isolated-vm>", columnOffset: 0, lineOffset: 0 });
2924
- const copyErrors = [];
2925
- let copied = false;
2926
- const copyBackContextFromJail = () => {
2927
- if (copied) {
2928
- return;
2929
- }
2930
- copied = true;
2931
- for (const key of trackedProperties) {
2932
- if (typeof context[key] === "object" && !referenceProperties.has(key)) {
2933
- try {
2934
- let properties = [];
2935
- try {
2936
- properties = isolatedContext.evalClosureSync(`return Object.getOwnPropertyNames(global['${key}'])`, [], {
2937
- result: { copy: true }
2938
- }) ?? [];
2939
- } catch (err) {
2940
- console.error(`Could not get properties of object "${key}" from the sandbox`, err);
2941
- }
2942
- const propsToDelete = Object.getOwnPropertyNames(context[key]).filter((x) => !properties.includes(x));
2943
- for (const prop of propsToDelete) {
2944
- delete context[key][prop];
2945
- }
2946
- for (const prop of properties) {
2947
- if (typeof context[key][prop] === "function" || referenceProperties.has(`${key}.${prop}`)) {
2948
- continue;
2949
- }
2950
- try {
2951
- const obj = isolatedContext.evalClosureSync(`return global['${key}']['${prop}']`, [], {
2952
- result: { copy: true }
2953
- });
2954
- try {
2955
- Object.assign(context[key], { [prop]: obj });
2956
- } catch (err) {
2957
- if (err instanceof AssignmentError) {
2958
- traces.push({
2959
- type: "code_execution_exception",
2960
- position: [0, 0],
2961
- message: err.message,
2962
- stackTrace: "",
2963
- started_at: Date.now(),
2964
- ended_at: Date.now()
2965
- });
2966
- copyErrors.push(err);
2967
- }
2968
- }
2969
- } catch (err) {
2970
- console.error(`Could not copy back "${key}.${prop}" from the sandbox`, err);
2971
- }
2972
- }
2973
- } catch (err) {
2974
- console.error(`Could not copy back object "${key}" from the sandbox`, err);
2975
- }
2976
- } else {
2977
- try {
2978
- if (referenceProperties.has(key)) {
2979
- continue;
2980
- }
2981
- const value = jail.getSync(key, { copy: true });
2982
- try {
2983
- Object.assign(context, { [key]: value });
2984
- } catch (err) {
2985
- if (err instanceof AssignmentError) {
2986
- traces.push({
2987
- type: "code_execution_exception",
2988
- position: [0, 0],
2989
- message: err.message,
2990
- stackTrace: "",
2991
- started_at: Date.now(),
2992
- ended_at: Date.now()
2993
- });
2994
- copyErrors.push(err);
2995
- }
2996
- }
2997
- } catch (err) {
2998
- console.error(`Could not copy back "${key}" from the sandbox`, err);
2999
- }
3000
- }
3491
+ const lastLine = ((_a = maxBy_default(matches, (x) => x.line ?? 0)) == null ? void 0 : _a.line) ?? 0;
3492
+ let debugUserCode = "";
3493
+ let truncatedCode = "";
3494
+ let truncated = false;
3495
+ const appendCode = (line) => {
3496
+ debugUserCode += line;
3497
+ if (!truncated) {
3498
+ truncatedCode += line;
3001
3499
  }
3002
3500
  };
3003
- const final = await script.run(isolatedContext, {
3004
- timeout,
3005
- copy: true,
3006
- promise: true
3007
- }).then((res) => {
3008
- copyBackContextFromJail();
3009
- if (copyErrors.length) {
3010
- throw new CodeExecutionError(copyErrors.map((x) => x.message).join(", "), code, "");
3011
- }
3012
- return res;
3013
- }).then(
3014
- (res) => {
3015
- res = Signals.maybeDeserializeError(res);
3016
- return {
3017
- success: true,
3018
- variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3019
- signal: res instanceof VMSignal ? res : void 0,
3020
- lines_executed: Array.from(lines_executed),
3021
- return_value: res
3022
- };
3023
- },
3024
- (err) => {
3025
- return handleError(err, code, consumer, traces, variables, lines_executed, currentToolCall, DRIVER);
3026
- }
3027
- ).catch((err) => {
3028
- if (signal == null ? void 0 : signal.aborted) {
3029
- return handleCatch(new Error("Execution was aborted"), traces, variables, lines_executed);
3501
+ for (let i = 0; i < lines.length; i++) {
3502
+ const VM_OFFSET = 2;
3503
+ const DISPLAY_OFFSET = 0;
3504
+ const line = lines[i];
3505
+ const correctedStackLineIndex = i + LINE_OFFSET + VM_OFFSET;
3506
+ const match = matches.find((x) => x.line + VM_OFFSET === correctedStackLineIndex);
3507
+ const paddedLineNumber = String(correctedStackLineIndex - VM_OFFSET - DISPLAY_OFFSET).padStart(3, "0");
3508
+ if (match) {
3509
+ appendCode(`> ${paddedLineNumber} | ${line}
3510
+ `);
3511
+ appendCode(` ${" ".repeat(paddedLineNumber.length + match.column)}^^^^^^^^^^
3512
+ `);
3513
+ if (match.line >= lastLine) {
3514
+ truncated = true;
3515
+ }
3030
3516
  } else {
3031
- copyBackContextFromJail();
3517
+ appendCode(` ${paddedLineNumber} | ${line}
3518
+ `);
3032
3519
  }
3033
- return handleCatch(err, traces, variables, lines_executed);
3034
- });
3035
- signal == null ? void 0 : signal.removeEventListener("abort", abort);
3036
- try {
3037
- isolate.dispose();
3038
- } catch {
3039
3520
  }
3040
- try {
3041
- isolatedContext.release();
3042
- } catch {
3521
+ debugUserCode = cleanStackTrace(debugUserCode).trim();
3522
+ truncatedCode = cleanStackTrace(truncatedCode).trim();
3523
+ if (err instanceof VMSignal) {
3524
+ const signalError = err;
3525
+ signalError.stack = debugUserCode;
3526
+ signalError.truncatedCode = truncatedCode;
3527
+ signalError.variables = mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter);
3528
+ signalError.toolCall = currentToolCall;
3529
+ return {
3530
+ success: true,
3531
+ variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3532
+ signal: err,
3533
+ lines_executed: Array.from(lines_executed)
3534
+ };
3535
+ } else {
3536
+ traces.push({
3537
+ type: "code_execution_exception",
3538
+ position: [((_b = matches[0]) == null ? void 0 : _b.line) ?? 0, ((_c = matches[0]) == null ? void 0 : _c.column) ?? 0],
3539
+ message: err.message,
3540
+ stackTrace: debugUserCode,
3541
+ started_at: Date.now()
3542
+ });
3543
+ const codeError = new CodeExecutionError(err.message, code, debugUserCode);
3544
+ const deserializedError = Signals.maybeDeserializeError(codeError);
3545
+ return {
3546
+ success: false,
3547
+ variables: mapValues_default(variables, (getter) => isFunction_default(getter) ? getter() : getter),
3548
+ error: deserializedError,
3549
+ traces,
3550
+ lines_executed: Array.from(lines_executed)
3551
+ };
3043
3552
  }
3044
- return final;
3045
- }
3046
- var handleError = (err, code, consumer, traces, variables, lines_executed, currentToolCall, driver = "isolated-vm") => {
3047
- var _a3, _b, _c;
3553
+ };
3554
+ var handleErrorNode = (err, code, consumer, traces, variables, _lines_executed, currentToolCall) => {
3555
+ var _a, _b, _c;
3048
3556
  err = Signals.maybeDeserializeError(err);
3049
3557
  const lines = code.split("\n");
3050
3558
  const stackTrace = err.stack || "";
3051
- const LINE_OFFSET = driver === "isolated-vm" ? 3 : 1;
3052
- let regex = /\(<isolated-vm>:(\d+):(\d+)/g;
3053
- if (driver === "node") {
3054
- regex = /<anonymous>:(\d+):(\d+)/g;
3055
- }
3559
+ const LINE_OFFSET = 1;
3560
+ const regex = /<anonymous>:(\d+):(\d+)/g;
3056
3561
  const matches = [...stackTrace.matchAll(regex)].map((x) => {
3057
3562
  const originalLine = consumer.originalPositionFor({
3058
3563
  line: Number(x[1]),
@@ -3067,7 +3572,7 @@ var handleError = (err, code, consumer, traces, variables, lines_executed, curre
3067
3572
  column: Math.min(minColumn, Number(x[2]))
3068
3573
  };
3069
3574
  });
3070
- const lastLine = ((_a3 = maxBy_default(matches, (x) => x.line ?? 0)) == null ? void 0 : _a3.line) ?? 0;
3575
+ const lastLine = ((_a = maxBy_default(matches, (x) => x.line ?? 0)) == null ? void 0 : _a.line) ?? 0;
3071
3576
  let debugUserCode = "";
3072
3577
  let truncatedCode = "";
3073
3578
  let truncated = false;
@@ -3078,8 +3583,8 @@ var handleError = (err, code, consumer, traces, variables, lines_executed, curre
3078
3583
  }
3079
3584
  };
3080
3585
  for (let i = 0; i < lines.length; i++) {
3081
- const VM_OFFSET = driver === "isolated-vm" ? 2 : 2;
3082
- const DISPLAY_OFFSET = driver === "isolated-vm" ? 2 : 0;
3586
+ const VM_OFFSET = 2;
3587
+ const DISPLAY_OFFSET = 0;
3083
3588
  const line = lines[i];
3084
3589
  const correctedStackLineIndex = i + LINE_OFFSET + VM_OFFSET;
3085
3590
  const match = matches.find((x) => x.line + VM_OFFSET === correctedStackLineIndex);
@@ -3129,6 +3634,5 @@ var handleCatch = (err, traces, variables, lines_executed) => {
3129
3634
  };
3130
3635
 
3131
3636
  export {
3132
- CAN_USE_ISOLATED_VM,
3133
3637
  runAsyncFunction
3134
3638
  };