llmz 0.0.29 → 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.
@@ -4,7 +4,6 @@
4
4
 
5
5
 
6
6
 
7
-
8
7
  var _chunkT63Y6GTWcjs = require('./chunk-T63Y6GTW.cjs');
9
8
 
10
9
 
@@ -1936,6 +1935,7 @@ var require_source_map = _chunkUQOBUJIQcjs.__commonJS.call(void 0, {
1936
1935
 
1937
1936
  // src/vm.ts
1938
1937
  var import_source_map_js = _chunkUQOBUJIQcjs.__toESM.call(void 0, require_source_map(), 1);
1938
+ var _quickjsemscriptencore = require('quickjs-emscripten-core');
1939
1939
 
1940
1940
  // src/compiler/compiler.ts
1941
1941
  var _plugintransformreactjsx = require('@babel/plugin-transform-react-jsx'); var _plugintransformreactjsx2 = _interopRequireDefault(_plugintransformreactjsx);
@@ -1944,17 +1944,22 @@ var _standalone = require('@babel/standalone'); var Babel = _interopRequireWildc
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
  };
@@ -2186,7 +2191,7 @@ var replaceCommentBabelPlugin = function({
2186
2191
  return;
2187
2192
  }
2188
2193
  comments.sort((a, b) => a.start > b.start ? -1 : 1).forEach((comment) => {
2189
- var _a3;
2194
+ var _a;
2190
2195
  if (processed.has(comment.loc)) {
2191
2196
  return;
2192
2197
  }
@@ -2194,7 +2199,7 @@ var replaceCommentBabelPlugin = function({
2194
2199
  const commentCall = t.expressionStatement(
2195
2200
  t.callExpression(t.identifier(CommentFnIdentifier), [
2196
2201
  t.stringLiteral(comment.value.trim()),
2197
- t.numericLiteral(_nullishCoalesce(((_a3 = comment.loc) == null ? void 0 : _a3.start.line), () => ( 0)))
2202
+ t.numericLiteral(_nullishCoalesce(((_a = comment.loc) == null ? void 0 : _a.start.line), () => ( 0)))
2198
2203
  ])
2199
2204
  );
2200
2205
  const isInsideObjectProperty = t.isObjectProperty(node) || path2.findParent((path3) => t.isObjectProperty(path3.node));
@@ -2221,8 +2226,8 @@ var instrumentLastLinePlugin = function({
2221
2226
  return {
2222
2227
  visitor: {
2223
2228
  FunctionDeclaration(path) {
2224
- var _a3, _b;
2225
- 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__") {
2226
2231
  return;
2227
2232
  }
2228
2233
  const statements = path.node.body.body;
@@ -2308,7 +2313,7 @@ var toolCallTrackingPlugin = (calls = /* @__PURE__ */ new Map()) => function({})
2308
2313
  skip.clear();
2309
2314
  },
2310
2315
  CallExpression(path) {
2311
- var _a3;
2316
+ var _a;
2312
2317
  if (skip.has(path.node) || path.findParent((p) => skip.has(p.node))) {
2313
2318
  return;
2314
2319
  }
@@ -2323,7 +2328,7 @@ var toolCallTrackingPlugin = (calls = /* @__PURE__ */ new Map()) => function({})
2323
2328
  (p) => p.isAssignmentExpression()
2324
2329
  );
2325
2330
  if (declaration) {
2326
- 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");
2327
2332
  }
2328
2333
  if (assignment) {
2329
2334
  const left = assignment.get("left");
@@ -2602,8 +2607,7 @@ function compile(code) {
2602
2607
  let output = Babel.transform(code, {
2603
2608
  parserOpts: {
2604
2609
  allowReturnOutsideFunction: true,
2605
- allowAwaitOutsideFunction: true,
2606
- startLine: -1
2610
+ allowAwaitOutsideFunction: true
2607
2611
  },
2608
2612
  presets: ["typescript"],
2609
2613
  plugins: [
@@ -2626,46 +2630,52 @@ function compile(code) {
2626
2630
  });
2627
2631
  const variables = /* @__PURE__ */ new Set();
2628
2632
  const toolCalls = /* @__PURE__ */ new Map();
2633
+ const codeWithMarkers = output.code;
2629
2634
  output = Babel.transform(output.code, {
2630
2635
  ...DEFAULT_TRANSFORM_OPTIONS,
2631
2636
  parserOpts: {
2632
- ...DEFAULT_TRANSFORM_OPTIONS.parserOpts,
2633
- startLine: -1
2637
+ ...DEFAULT_TRANSFORM_OPTIONS.parserOpts
2634
2638
  },
2635
2639
  plugins: [
2636
2640
  lineTrackingBabelPlugin,
2637
2641
  replaceCommentBabelPlugin,
2638
2642
  variableTrackingPlugin(variables),
2639
2643
  toolCallTrackingPlugin(toolCalls)
2640
- ]
2644
+ ],
2645
+ retainLines: true
2641
2646
  });
2642
2647
  let outputCode = output.code;
2643
2648
  outputCode = AsyncIterator.postProcessing(outputCode);
2644
2649
  outputCode = JSXNewLines.postProcessing(outputCode);
2645
2650
  return {
2646
2651
  code: outputCode,
2652
+ codeWithMarkers,
2653
+ // Code from before second transform, still has literal markers
2647
2654
  map: output.map,
2648
2655
  variables,
2649
2656
  toolCalls
2650
2657
  };
2651
2658
  }
2652
2659
 
2653
- // src/vm.ts
2654
- var IS_NODE = typeof process !== "undefined" && process.versions != null && process.versions.node != null;
2655
- var _a;
2656
- var IS_CI = typeof process !== "undefined" && !!((_a = process == null ? void 0 : process.env) == null ? void 0 : _a.CI);
2657
- var _a2;
2658
- var VM_DRIVER = _nullishCoalesce((typeof process !== "undefined" && ((_a2 = process == null ? void 0 : process.env) == null ? void 0 : _a2.VM_DRIVER)), () => ( (IS_CI ? "node" : "isolated-vm")));
2659
- var CAN_USE_ISOLATED_VM = IS_NODE && VM_DRIVER === "isolated-vm";
2660
- var MAX_VM_EXECUTION_TIME = 6e4;
2661
- var requireEsm = async (id) => {
2662
- if (typeof globalThis.window === "undefined" && typeof globalThis.require !== "undefined") {
2663
- return eval("require")(id);
2664
- } else {
2665
- return await Promise.resolve().then(() => _interopRequireWildcard(require(id))).then((m) => _nullishCoalesce(m.default, () => ( m)));
2660
+ // src/quickjs-variant.ts
2661
+ var getVariant = async () => {
2662
+ const module = await Promise.resolve().then(() => _interopRequireWildcard(require("@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();
2666
2674
  }
2667
2675
  };
2668
- var getIsolatedVm = async () => await requireEsm("isolated-vm");
2676
+
2677
+ // src/vm.ts
2678
+ var MAX_VM_EXECUTION_TIME = 6e4;
2669
2679
  var NO_TRACKING = [
2670
2680
  Identifiers.CommentFnIdentifier,
2671
2681
  Identifiers.ToolCallTrackerFnIdentifier,
@@ -2688,7 +2698,7 @@ function getCompiledCode(code, traces = []) {
2688
2698
  }
2689
2699
  }
2690
2700
  async function runAsyncFunction(context, code, traces = [], signal = null, timeout = MAX_VM_EXECUTION_TIME) {
2691
- var _a3;
2701
+ var _a, _b, _c, _d, _e, _f, _g;
2692
2702
  const transformed = getCompiledCode(code, traces);
2693
2703
  const lines_executed = /* @__PURE__ */ new Map();
2694
2704
  const variables = {};
@@ -2702,76 +2712,715 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
2702
2712
  sourceRoot: transformed.map.sourceRoot
2703
2713
  });
2704
2714
  context ??= {};
2705
- for (const name of transformed.variables) {
2715
+ for (const name of Array.from(transformed.variables)) {
2706
2716
  delete context[name];
2707
2717
  }
2708
- context[Identifiers.CommentFnIdentifier] = (comment, line) => traces.push({ type: "comment", comment, line, started_at: Date.now() });
2709
- context[Identifiers.LineTrackingFnIdentifier] = (line) => {
2710
- lines_executed.set(line, (_nullishCoalesce(lines_executed.get(line), () => ( 0))) + 1);
2711
- };
2712
- context[Identifiers.JSXFnIdentifier] = (tool, props, ...children) => _chunkKMZDFWYZcjs.createJsxComponent.call(void 0, {
2713
- type: tool,
2714
- props,
2715
- children
2716
- });
2717
- context[Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
2718
- if (NO_TRACKING.includes(name)) {
2719
- return;
2720
- }
2721
- variables[name] = () => {
2722
- try {
2723
- const value = getter();
2724
- if (typeof value === "function") {
2725
- return "[[non-primitive]]";
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;
2726
2738
  }
2727
- return value;
2728
- } catch (e2) {
2729
- return "[[non-primitive]]";
2730
2739
  }
2731
- };
2732
- };
2733
- let currentToolCall;
2734
- context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
2735
- var _a4;
2736
- const temp = _chunkT63Y6GTWcjs.Signals.maybeDeserializeError(outputOrError == null ? void 0 : outputOrError.message);
2737
- if (type === "end" && temp instanceof _chunkT63Y6GTWcjs.SnapshotSignal && (temp == null ? void 0 : temp.toolCall)) {
2738
- currentToolCall = {
2739
- ...temp.toolCall,
2740
- 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 = _nullishCoalesce(originalLine.line, () => ( line));
2746
+ const userCodeLine = Math.max(1, mappedLine - userCodeStartLine);
2747
+ lines_executed.set(userCodeLine, (_nullishCoalesce(lines_executed.get(userCodeLine), () => ( 0))) + 1);
2741
2748
  };
2749
+ context[Identifiers.JSXFnIdentifier] = (tool, props, ...children) => _chunkKMZDFWYZcjs.createJsxComponent.call(void 0, {
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 (e2) {
2766
+ return "[[non-primitive]]";
2767
+ }
2768
+ };
2769
+ };
2770
+ let currentToolCall;
2771
+ context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
2772
+ var _a2;
2773
+ const temp = _chunkT63Y6GTWcjs.Signals.maybeDeserializeError(outputOrError == null ? void 0 : outputOrError.message);
2774
+ if (type === "end" && temp instanceof _chunkT63Y6GTWcjs.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 _quickjsemscriptencore.newQuickJSWASMModuleFromVariant.call(void 0, BundledReleaseSyncVariant);
2803
+ const runtime = QuickJS.newRuntime();
2804
+ runtime.setDebugMode(true);
2805
+ runtime.setMemoryLimit(128 * 1024 * 1024);
2806
+ const startTime = Date.now();
2807
+ const timeoutHandler = _quickjsemscriptencore.shouldInterruptAfterDeadline.call(void 0, 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 (e3) {
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}
2742
3101
  }
2743
- };
2744
- context[Identifiers.ConsoleObjIdentifier] = {
2745
- log: (...args) => {
2746
- const message = args.shift();
2747
- traces.push({ type: "log", message, args, started_at: Date.now() });
2748
- }
2749
- };
2750
- context[Identifiers.AsyncIterYieldFnIdentifier] = async function(value) {
2751
- const startedAt = Date.now();
2752
- try {
2753
- if (typeof value.type !== "string" || value.type.trim().length === 0) {
2754
- throw new Error("A yield statement must yield a valid tool");
2755
- }
2756
- const toolName = Object.keys(context).find((x) => x.toUpperCase() === value.type.toUpperCase());
2757
- if (!toolName) {
2758
- throw new Error(`Yield tool "${value.type}", but tool is not found`);
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;
2759
3114
  }
2760
- await context[toolName](value);
2761
- } finally {
2762
- 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++;
2763
3123
  }
2764
- };
2765
- let DRIVER = CAN_USE_ISOLATED_VM ? "isolated-vm" : "node";
2766
- let isolatedVm;
2767
- if (DRIVER === "isolated-vm") {
2768
- try {
2769
- isolatedVm = await getIsolatedVm();
2770
- } catch (e3) {
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 (e4) {
3151
+ }
3152
+ } catch (e5) {
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 (e6) {
3269
+ }
3270
+ const errorStackResult = vm.evalCode("globalThis.__llmz_error_stack");
3271
+ const errorStack = vm.dump(errorStackResult.unwrap()) || "";
3272
+ errorStackResult.unwrap().dispose();
3273
+ const deserializedError = _chunkT63Y6GTWcjs.Signals.maybeDeserializeError(errorValue);
3274
+ if (deserializedError instanceof _chunkT63Y6GTWcjs.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 = _chunkT63Y6GTWcjs.Signals.maybeDeserializeError(returnValue);
3293
+ return {
3294
+ success: true,
3295
+ variables: _chunkUQOBUJIQcjs.mapValues_default.call(void 0, variables, (getter) => _chunkUQOBUJIQcjs.isFunction_default.call(void 0, getter) ? getter() : getter),
3296
+ signal: returnValue instanceof _chunkT63Y6GTWcjs.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 (e7) {
3343
+ }
3344
+ try {
3345
+ runtime.dispose();
3346
+ } catch (e8) {
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));
2771
3363
  DRIVER = "node";
2772
3364
  }
2773
3365
  }
2774
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, (_nullishCoalesce(lines_executed.get(line), () => ( 0))) + 1);
3370
+ };
3371
+ context[Identifiers.JSXFnIdentifier] = (tool, props, ...children) => _chunkKMZDFWYZcjs.createJsxComponent.call(void 0, {
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 (e9) {
3388
+ return "[[non-primitive]]";
3389
+ }
3390
+ };
3391
+ };
3392
+ let currentToolCall;
3393
+ context[Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
3394
+ var _a2;
3395
+ const temp = _chunkT63Y6GTWcjs.Signals.maybeDeserializeError(outputOrError == null ? void 0 : outputOrError.message);
3396
+ if (type === "end" && temp instanceof _chunkT63Y6GTWcjs.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
+ };
2775
3424
  const AsyncFunction = async function* () {
2776
3425
  }.constructor;
2777
3426
  return await (async () => {
@@ -2806,293 +3455,109 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
2806
3455
  lines_executed: Array.from(lines_executed),
2807
3456
  return_value: res
2808
3457
  };
2809
- }).catch((err) => handleError(err, code, consumer, traces, variables, lines_executed, currentToolCall, DRIVER)).catch((err) => handleCatch(err, traces, variables, lines_executed));
2810
- }
2811
- if (!isolatedVm) {
2812
- throw new Error("isolated-vm is not available");
2813
- }
2814
- const isolate = new isolatedVm.Isolate({ memoryLimit: 128 });
2815
- const isolatedContext = await isolate.createContext();
2816
- const jail = isolatedContext.global;
2817
- const trackedProperties = /* @__PURE__ */ new Set();
2818
- const referenceProperties = /* @__PURE__ */ new Set();
2819
- const abort = () => {
2820
- if (DRIVER === "isolated-vm") {
2821
- isolate.dispose();
2822
- isolatedContext.release();
2823
- }
2824
- };
2825
- if (signal) {
2826
- signal.addEventListener("abort", abort);
3458
+ }).catch((err) => handleErrorNode(err, code, consumer, traces, variables, lines_executed, currentToolCall)).catch((err) => handleCatch(err, traces, variables, lines_executed));
2827
3459
  }
2828
- await jail.set("global", jail.derefInto());
2829
- for (const key of Object.keys(context)) {
2830
- if (typeof context[key] === "function") {
2831
- await isolatedContext.evalClosure(
2832
- `global['${key}'] = (...args) => $0.applySyncPromise(null, args, {arguments: {copy: true}});`,
2833
- [async (...args) => new isolatedVm.ExternalCopy(await context[key](...args)).copyInto()],
2834
- {
2835
- arguments: { reference: true }
2836
- }
2837
- );
2838
- } else if (typeof context[key] === "object" && !((_a3 = Object.getOwnPropertyDescriptor(context, key)) == null ? void 0 : _a3.get)) {
2839
- try {
2840
- trackedProperties.add(key);
2841
- const initial = Array.isArray(context[key]) ? new Array(context[key].length) : {};
2842
- await jail.set(key, initial, { copy: true });
2843
- const props = /* @__PURE__ */ new Set([...Object.keys(context[key]), ...Object.getOwnPropertyNames(context[key])]);
2844
- for (const prop of props) {
2845
- try {
2846
- if (typeof context[key][prop] === "function") {
2847
- await isolatedContext.evalClosure(
2848
- `global['${key}']['${prop}'] = (...args) => $0.applySyncPromise(null, args, {arguments: {copy: true}});`,
2849
- [async (...args) => new isolatedVm.ExternalCopy(await context[key][prop](...args)).copyInto()],
2850
- {
2851
- arguments: { reference: true }
2852
- }
2853
- );
2854
- } else {
2855
- const descriptor = Object.getOwnPropertyDescriptor(context[key], prop);
2856
- if (descriptor && (descriptor.get || descriptor.set)) {
2857
- referenceProperties.add(`${key}.${prop}`);
2858
- await isolatedContext.evalClosure(
2859
- `Object.defineProperty(global['${key}'], '${prop}', {
2860
- get: () => $0.applySync(null, [], {arguments: {copy: true}}),
2861
- set: (value) => $1.applySync(null, [value], {arguments: {copy: true}})
2862
- });`,
2863
- [
2864
- () => context[key][prop],
2865
- (value) => {
2866
- context[key][prop] = value;
2867
- return value;
2868
- }
2869
- ],
2870
- { arguments: { reference: true } }
2871
- );
2872
- } else {
2873
- await isolatedContext.evalClosure(`global['${key}']['${prop}'] = $0;`, [context[key][prop]], {
2874
- arguments: { copy: true }
2875
- });
2876
- }
2877
- }
2878
- } catch (err) {
2879
- console.error(`Could not copy "${key}.${prop}" (typeof = ${typeof context[key][prop]}) to the sandbox`, err);
2880
- }
2881
- }
2882
- } catch (err) {
2883
- console.error(`Could not create object "${key}" (typeof = ${typeof context[key]}) in the sandbox`, err);
2884
- }
2885
- } else {
2886
- try {
2887
- const descriptor = Object.getOwnPropertyDescriptor(context, key);
2888
- if (descriptor && (descriptor.get || descriptor.set)) {
2889
- referenceProperties.add(key);
2890
- await isolatedContext.evalClosure(
2891
- `Object.defineProperty(global, '${key}', {
2892
- get: () => $0.applySync(null, [], {arguments: {copy: true}}),
2893
- set: (value) => $1.applySync(null, [value], {arguments: {copy: true}})
2894
- });`,
2895
- [
2896
- () => context[key],
2897
- (value) => {
2898
- context[key] = value;
2899
- return value;
2900
- }
2901
- ],
2902
- { arguments: { reference: true } }
2903
- );
2904
- } else {
2905
- await jail.set(key, context[key], { copy: true });
2906
- }
2907
- trackedProperties.add(key);
2908
- } catch (err) {
2909
- console.error(`Could not copy "${key}" to the sandbox (typeof = ${typeof context[key]})`, err);
2910
- }
2911
- }
2912
- }
2913
- for (const key of Object.keys(context)) {
2914
- if (Object.isSealed(context[key])) {
2915
- await isolatedContext.evalClosure(`Object.seal(global['${key}']);`, []);
2916
- }
2917
- if (!Object.isExtensible(context[key])) {
2918
- await isolatedContext.evalClosure(`Object.preventExtensions(global['${key}']);`, []);
2919
- }
2920
- }
2921
- const Console = await jail.get(Identifiers.ConsoleObjIdentifier, { reference: true });
2922
- await Console.set("log", (...args) => {
2923
- const message = args.shift();
2924
- traces.push({ type: "log", message, args, started_at: Date.now() });
2925
- });
2926
- await isolatedContext.evalClosure(
2927
- `${Identifiers.VariableTrackingFnIdentifier} = (name, getter) => {
2928
- const value = getter();
2929
- try {
2930
- $0.applySync(null, [name, getter()], { arguments: { copy: true } });
2931
- } catch {
2932
- $0.applySync(null, [name, '[[non-primitive]]'], { arguments: { copy: true } });
2933
- }
2934
- };`,
2935
- [
2936
- (name, value) => {
2937
- variables[name] = value;
2938
- }
2939
- ],
2940
- {
2941
- arguments: { reference: true }
2942
- }
2943
- );
2944
- const scriptCode = `
2945
- "use strict";
2946
- new Promise(async (resolve) => {
2947
-
2948
- async function* __fn__() {
2949
- ${transformed.code}
3460
+ throw new Error(`Unknown driver: ${DRIVER}`);
2950
3461
  }
2951
-
2952
- const fn = __fn__();
2953
- do {
2954
- const { value, done } = await fn.next();
2955
- if (done) {
2956
- const ret = await value;
2957
- return resolve(ret);
3462
+ var handleErrorQuickJS = (err, code, _consumer, traces, variables, lines_executed, userCodeStartLine, currentToolCall) => {
3463
+ var _a, _b, _c;
3464
+ err = _chunkT63Y6GTWcjs.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 = _nullishCoalesce(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 = _nullishCoalesce(lines[lastLine2 - LINE_OFFSET], () => ( ""));
3485
+ const whiteSpacesCount = actualLine.length - actualLine.trimStart().length;
3486
+ matches.push({
3487
+ line: lastLine2,
3488
+ column: whiteSpacesCount
3489
+ });
2958
3490
  }
2959
- await ${Identifiers.AsyncIterYieldFnIdentifier}(value);
2960
- } while(true);
2961
-
2962
- })`.trim();
2963
- const script = await isolate.compileScript(scriptCode, { filename: "<isolated-vm>", columnOffset: 0, lineOffset: 0 });
2964
- const copyErrors = [];
2965
- let copied = false;
2966
- const copyBackContextFromJail = () => {
2967
- if (copied) {
2968
- return;
2969
- }
2970
- copied = true;
2971
- for (const key of trackedProperties) {
2972
- if (typeof context[key] === "object" && !referenceProperties.has(key)) {
2973
- try {
2974
- let properties = [];
2975
- try {
2976
- properties = _nullishCoalesce(isolatedContext.evalClosureSync(`return Object.getOwnPropertyNames(global['${key}'])`, [], {
2977
- result: { copy: true }
2978
- }), () => ( []));
2979
- } catch (err) {
2980
- console.error(`Could not get properties of object "${key}" from the sandbox`, err);
2981
- }
2982
- const propsToDelete = Object.getOwnPropertyNames(context[key]).filter((x) => !properties.includes(x));
2983
- for (const prop of propsToDelete) {
2984
- delete context[key][prop];
2985
- }
2986
- for (const prop of properties) {
2987
- if (typeof context[key][prop] === "function" || referenceProperties.has(`${key}.${prop}`)) {
2988
- continue;
2989
- }
2990
- try {
2991
- const obj = isolatedContext.evalClosureSync(`return global['${key}']['${prop}']`, [], {
2992
- result: { copy: true }
2993
- });
2994
- try {
2995
- Object.assign(context[key], { [prop]: obj });
2996
- } catch (err) {
2997
- if (err instanceof _chunkT63Y6GTWcjs.AssignmentError) {
2998
- traces.push({
2999
- type: "code_execution_exception",
3000
- position: [0, 0],
3001
- message: err.message,
3002
- stackTrace: "",
3003
- started_at: Date.now(),
3004
- ended_at: Date.now()
3005
- });
3006
- copyErrors.push(err);
3007
- }
3008
- }
3009
- } catch (err) {
3010
- console.error(`Could not copy back "${key}.${prop}" from the sandbox`, err);
3011
- }
3012
- }
3013
- } catch (err) {
3014
- console.error(`Could not copy back object "${key}" from the sandbox`, err);
3015
- }
3016
- } else {
3017
- try {
3018
- if (referenceProperties.has(key)) {
3019
- continue;
3020
- }
3021
- const value = jail.getSync(key, { copy: true });
3022
- try {
3023
- Object.assign(context, { [key]: value });
3024
- } catch (err) {
3025
- if (err instanceof _chunkT63Y6GTWcjs.AssignmentError) {
3026
- traces.push({
3027
- type: "code_execution_exception",
3028
- position: [0, 0],
3029
- message: err.message,
3030
- stackTrace: "",
3031
- started_at: Date.now(),
3032
- ended_at: Date.now()
3033
- });
3034
- copyErrors.push(err);
3035
- }
3036
- }
3037
- } catch (err) {
3038
- console.error(`Could not copy back "${key}" from the sandbox`, err);
3039
- }
3040
- }
3491
+ const lastLine = _nullishCoalesce(((_a = _chunkUQOBUJIQcjs.maxBy_default.call(void 0, matches, (x) => _nullishCoalesce(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;
3041
3499
  }
3042
3500
  };
3043
- const final = await script.run(isolatedContext, {
3044
- timeout,
3045
- copy: true,
3046
- promise: true
3047
- }).then((res) => {
3048
- copyBackContextFromJail();
3049
- if (copyErrors.length) {
3050
- throw new (0, _chunkT63Y6GTWcjs.CodeExecutionError)(copyErrors.map((x) => x.message).join(", "), code, "");
3051
- }
3052
- return res;
3053
- }).then(
3054
- (res) => {
3055
- res = _chunkT63Y6GTWcjs.Signals.maybeDeserializeError(res);
3056
- return {
3057
- success: true,
3058
- variables: _chunkUQOBUJIQcjs.mapValues_default.call(void 0, variables, (getter) => _chunkUQOBUJIQcjs.isFunction_default.call(void 0, getter) ? getter() : getter),
3059
- signal: res instanceof _chunkT63Y6GTWcjs.VMSignal ? res : void 0,
3060
- lines_executed: Array.from(lines_executed),
3061
- return_value: res
3062
- };
3063
- },
3064
- (err) => {
3065
- return handleError(err, code, consumer, traces, variables, lines_executed, currentToolCall, DRIVER);
3066
- }
3067
- ).catch((err) => {
3068
- if (signal == null ? void 0 : signal.aborted) {
3069
- return handleCatch(new Error("Execution was aborted"), traces, variables, lines_executed);
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
+ }
3070
3516
  } else {
3071
- copyBackContextFromJail();
3517
+ appendCode(` ${paddedLineNumber} | ${line}
3518
+ `);
3072
3519
  }
3073
- return handleCatch(err, traces, variables, lines_executed);
3074
- });
3075
- signal == null ? void 0 : signal.removeEventListener("abort", abort);
3076
- try {
3077
- isolate.dispose();
3078
- } catch (e4) {
3079
3520
  }
3080
- try {
3081
- isolatedContext.release();
3082
- } catch (e5) {
3521
+ debugUserCode = _chunkKIN7Y247cjs.cleanStackTrace.call(void 0, debugUserCode).trim();
3522
+ truncatedCode = _chunkKIN7Y247cjs.cleanStackTrace.call(void 0, truncatedCode).trim();
3523
+ if (err instanceof _chunkT63Y6GTWcjs.VMSignal) {
3524
+ const signalError = err;
3525
+ signalError.stack = debugUserCode;
3526
+ signalError.truncatedCode = truncatedCode;
3527
+ signalError.variables = _chunkUQOBUJIQcjs.mapValues_default.call(void 0, variables, (getter) => _chunkUQOBUJIQcjs.isFunction_default.call(void 0, getter) ? getter() : getter);
3528
+ signalError.toolCall = currentToolCall;
3529
+ return {
3530
+ success: true,
3531
+ variables: _chunkUQOBUJIQcjs.mapValues_default.call(void 0, variables, (getter) => _chunkUQOBUJIQcjs.isFunction_default.call(void 0, 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: [_nullishCoalesce(((_b = matches[0]) == null ? void 0 : _b.line), () => ( 0)), _nullishCoalesce(((_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 (0, _chunkT63Y6GTWcjs.CodeExecutionError)(err.message, code, debugUserCode);
3544
+ const deserializedError = _chunkT63Y6GTWcjs.Signals.maybeDeserializeError(codeError);
3545
+ return {
3546
+ success: false,
3547
+ variables: _chunkUQOBUJIQcjs.mapValues_default.call(void 0, variables, (getter) => _chunkUQOBUJIQcjs.isFunction_default.call(void 0, getter) ? getter() : getter),
3548
+ error: deserializedError,
3549
+ traces,
3550
+ lines_executed: Array.from(lines_executed)
3551
+ };
3083
3552
  }
3084
- return final;
3085
- }
3086
- var handleError = (err, code, consumer, traces, variables, lines_executed, currentToolCall, driver = "isolated-vm") => {
3087
- var _a3, _b, _c;
3553
+ };
3554
+ var handleErrorNode = (err, code, consumer, traces, variables, _lines_executed, currentToolCall) => {
3555
+ var _a, _b, _c;
3088
3556
  err = _chunkT63Y6GTWcjs.Signals.maybeDeserializeError(err);
3089
3557
  const lines = code.split("\n");
3090
3558
  const stackTrace = err.stack || "";
3091
- const LINE_OFFSET = driver === "isolated-vm" ? 3 : 1;
3092
- let regex = /\(<isolated-vm>:(\d+):(\d+)/g;
3093
- if (driver === "node") {
3094
- regex = /<anonymous>:(\d+):(\d+)/g;
3095
- }
3559
+ const LINE_OFFSET = 1;
3560
+ const regex = /<anonymous>:(\d+):(\d+)/g;
3096
3561
  const matches = [...stackTrace.matchAll(regex)].map((x) => {
3097
3562
  const originalLine = consumer.originalPositionFor({
3098
3563
  line: Number(x[1]),
@@ -3107,7 +3572,7 @@ var handleError = (err, code, consumer, traces, variables, lines_executed, curre
3107
3572
  column: Math.min(minColumn, Number(x[2]))
3108
3573
  };
3109
3574
  });
3110
- const lastLine = _nullishCoalesce(((_a3 = _chunkUQOBUJIQcjs.maxBy_default.call(void 0, matches, (x) => _nullishCoalesce(x.line, () => ( 0)))) == null ? void 0 : _a3.line), () => ( 0));
3575
+ const lastLine = _nullishCoalesce(((_a = _chunkUQOBUJIQcjs.maxBy_default.call(void 0, matches, (x) => _nullishCoalesce(x.line, () => ( 0)))) == null ? void 0 : _a.line), () => ( 0));
3111
3576
  let debugUserCode = "";
3112
3577
  let truncatedCode = "";
3113
3578
  let truncated = false;
@@ -3118,8 +3583,8 @@ var handleError = (err, code, consumer, traces, variables, lines_executed, curre
3118
3583
  }
3119
3584
  };
3120
3585
  for (let i = 0; i < lines.length; i++) {
3121
- const VM_OFFSET = driver === "isolated-vm" ? 2 : 2;
3122
- const DISPLAY_OFFSET = driver === "isolated-vm" ? 2 : 0;
3586
+ const VM_OFFSET = 2;
3587
+ const DISPLAY_OFFSET = 0;
3123
3588
  const line = lines[i];
3124
3589
  const correctedStackLineIndex = i + LINE_OFFSET + VM_OFFSET;
3125
3590
  const match = matches.find((x) => x.line + VM_OFFSET === correctedStackLineIndex);
@@ -3170,5 +3635,4 @@ var handleCatch = (err, traces, variables, lines_executed) => {
3170
3635
 
3171
3636
 
3172
3637
 
3173
-
3174
- exports.CAN_USE_ISOLATED_VM = CAN_USE_ISOLATED_VM; exports.runAsyncFunction = runAsyncFunction;
3638
+ exports.runAsyncFunction = runAsyncFunction;