llmz 0.9.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/DOCS.md +232 -1794
  2. package/ERRORS.md +101 -0
  3. package/README.md +96 -582
  4. package/dist/chat/chat.d.ts +63 -0
  5. package/dist/chat/component.d.ts +31 -0
  6. package/dist/chat/component.default.d.ts +58 -0
  7. package/dist/chat/response.d.ts +15 -0
  8. package/dist/compiler/compiler.d.ts +2 -7
  9. package/dist/compiler/plugins/dynamic-code.d.ts +7 -0
  10. package/dist/compiler/plugins/replace-comment.d.ts +2 -3
  11. package/dist/compiler/plugins/return-async.d.ts +5 -4
  12. package/dist/compiler/plugins/termination.d.ts +8 -0
  13. package/dist/compiler/plugins/tool-resolution.d.ts +4 -0
  14. package/dist/compiler/plugins/variable-extraction.d.ts +2 -8
  15. package/dist/component-CMFoCHyu.cjs +649 -0
  16. package/dist/component-DncqP4fB.js +614 -0
  17. package/dist/context.d.ts +71 -378
  18. package/dist/custom-client-C-WXvLD9.js +1655 -0
  19. package/dist/custom-client-Cgt9_0r1.cjs +1732 -0
  20. package/dist/custom-client.d.ts +12 -2
  21. package/dist/errors/catalog.d.ts +294 -0
  22. package/dist/errors/hooks.d.ts +2 -0
  23. package/dist/errors-C6ppQUZX.cjs +893 -0
  24. package/dist/errors-Crk5P8jo.js +636 -0
  25. package/dist/errors.d.ts +24 -36
  26. package/dist/execute-CiYvPs5Q.js +2061 -0
  27. package/dist/execute-DTTfacsi.cjs +2062 -0
  28. package/dist/{exit-DUM96DN1.cjs → exit-BOtKWPuT.cjs} +38 -28
  29. package/dist/{exit-CDdxDBRT.js → exit-DMPwCSba.js} +37 -27
  30. package/dist/exit.d.ts +19 -16
  31. package/dist/index.cjs +177 -1237
  32. package/dist/index.d.ts +25 -28
  33. package/dist/index.js +137 -1213
  34. package/dist/index.workerd.js +8974 -11145
  35. package/dist/inspect.d.ts +18 -4
  36. package/dist/inspection.d.ts +40 -0
  37. package/dist/native-0bq5ATZM.cjs +212 -0
  38. package/dist/native-n_718Z-T.js +177 -0
  39. package/dist/objects.d.ts +2 -57
  40. package/dist/prompts/native.d.ts +2 -0
  41. package/dist/prompts/prompt.d.ts +10 -101
  42. package/dist/quickjs-variant-21IO97PF.cjs +1080 -0
  43. package/dist/quickjs-variant-CtuGagsb.js +985 -0
  44. package/dist/result.d.ts +30 -861
  45. package/dist/runtime/execute.d.ts +3 -2
  46. package/dist/runtime/execution-activity.d.ts +11 -0
  47. package/dist/runtime/execution-diagnostics.d.ts +11 -0
  48. package/dist/runtime/execution-report.d.ts +51 -0
  49. package/dist/runtime/fixtures/chat.d.ts +8 -0
  50. package/dist/runtime/fixtures/long-search.d.ts +1 -1
  51. package/dist/runtime/fixtures/native-client.d.ts +33 -0
  52. package/dist/runtime/fixtures/protocol-languages.d.ts +1 -1
  53. package/dist/runtime/forced-inspection.d.ts +13 -0
  54. package/dist/runtime/forced-inspection.test.d.ts +1 -0
  55. package/dist/runtime/generate.d.ts +23 -20
  56. package/dist/runtime/generate.test.d.ts +1 -0
  57. package/dist/runtime/hook-provenance.test.d.ts +1 -0
  58. package/dist/runtime/inspection-hook.test.d.ts +1 -0
  59. package/dist/runtime/inspection-values.d.ts +14 -0
  60. package/dist/runtime/inspection-values.test.d.ts +1 -0
  61. package/dist/runtime/interruption-control-flow.test.d.ts +1 -0
  62. package/dist/runtime/interruption-settings.test.d.ts +1 -0
  63. package/dist/runtime/javascript-api.d.ts +62 -0
  64. package/dist/runtime/javascript-api.test.d.ts +1 -0
  65. package/dist/runtime/native-review.test.d.ts +1 -0
  66. package/dist/runtime/native-tools.d.ts +18 -0
  67. package/dist/runtime/native-tools.test.d.ts +1 -0
  68. package/dist/runtime/object-memory.test.d.ts +1 -0
  69. package/dist/runtime/single-tool.test.d.ts +1 -0
  70. package/dist/runtime/think-signal.test.d.ts +1 -0
  71. package/dist/runtime/token-budget.d.ts +22 -0
  72. package/dist/runtime/token-budget.test.d.ts +1 -0
  73. package/dist/runtime/tool-wrapper.d.ts +6 -5
  74. package/dist/runtime/traces.test.d.ts +1 -0
  75. package/dist/runtime/truncation.test.d.ts +1 -0
  76. package/dist/runtime/types.d.ts +47 -31
  77. package/dist/runtime/variable-recovery.test.d.ts +1 -0
  78. package/dist/runtime/vm-context.d.ts +6 -1
  79. package/dist/runtime/worker-completion.test.d.ts +1 -0
  80. package/dist/runtime-names.d.ts +4 -0
  81. package/dist/schema-CXlnbb3n.cjs +68 -0
  82. package/dist/schema-GE4ISPCR.js +45 -0
  83. package/dist/schema.d.ts +10 -0
  84. package/dist/schema.test.d.ts +1 -0
  85. package/dist/session/compactor.d.ts +51 -0
  86. package/dist/session/compactor.test.d.ts +1 -0
  87. package/dist/session/history.d.ts +36 -0
  88. package/dist/session/history.test.d.ts +1 -0
  89. package/dist/session/json.d.ts +3 -0
  90. package/dist/session/json.test.d.ts +1 -0
  91. package/dist/session/memory-codec.d.ts +9 -0
  92. package/dist/session/memory-codec.test.d.ts +1 -0
  93. package/dist/session/memory-render.d.ts +15 -0
  94. package/dist/session/memory-render.test.d.ts +1 -0
  95. package/dist/session/memory.d.ts +112 -0
  96. package/dist/session/memory.test.d.ts +1 -0
  97. package/dist/session/messages.d.ts +19 -0
  98. package/dist/session/messages.test.d.ts +1 -0
  99. package/dist/session/serialization.d.ts +36 -0
  100. package/dist/session/serialization.test.d.ts +1 -0
  101. package/dist/session/session-memory.test.d.ts +1 -0
  102. package/dist/session/session.d.ts +121 -0
  103. package/dist/session/session.test.d.ts +1 -0
  104. package/dist/session/speaker.test.d.ts +1 -0
  105. package/dist/{transcript.d.ts → session/transcript.d.ts} +4 -8
  106. package/dist/session/transcript.test.d.ts +1 -0
  107. package/dist/{tool-Bv8N4IPj.js → tool-DstssiAs.js} +144 -92
  108. package/dist/{tool-Dy6AJpJH.cjs → tool-_wK9hQOb.cjs} +146 -94
  109. package/dist/tool.d.ts +25 -17
  110. package/dist/truncate-BEKbdo3t.js +79 -0
  111. package/dist/truncate-uomAMGPs.cjs +102 -0
  112. package/dist/truncate.d.ts +24 -0
  113. package/dist/truncate.test.d.ts +1 -0
  114. package/dist/types.d.ts +33 -9
  115. package/dist/{typings-3lsqCbkn.cjs → typings-BA_XxAcY.cjs} +38 -193
  116. package/dist/{typings-CrBa7Tyy.js → typings-BEVDvtuk.js} +38 -175
  117. package/dist/typings-formatter.d.ts +1 -1
  118. package/dist/typings.d.ts +3 -0
  119. package/dist/{uniq-BYQ7GWwb.js → uniq-DfUeSNaX.js} +2 -2
  120. package/dist/{uniq-G872RWmE.cjs → uniq-DiXgysNV.cjs} +6 -18
  121. package/dist/{_baseIteratee-P_firB7b.js → utils-BOFzb8Ok.js} +1134 -16
  122. package/dist/{_baseIteratee-CF4qP2a8.cjs → utils-CTlsXvdj.cjs} +1281 -84
  123. package/dist/vm/drivers/node.d.ts +1 -1
  124. package/dist/vm/drivers/quickjs.d.ts +1 -1
  125. package/dist/vm/errors.d.ts +4 -4
  126. package/dist/vm/index.d.ts +3 -4
  127. package/dist/vm/instrument.d.ts +14 -6
  128. package/dist/vm/member-proxy.d.ts +4 -0
  129. package/dist/vm/member-proxy.test.d.ts +1 -0
  130. package/dist/vm/memory.test.d.ts +1 -0
  131. package/dist/vm/return-semantics.test.d.ts +1 -0
  132. package/dist/vm/types.d.ts +20 -3
  133. package/dist/{vm-BLsHw1da.js → vm-C7SfutHn.js} +1187 -180
  134. package/dist/{vm-D6s1zF6M.cjs → vm-gmekHc0i.cjs} +1221 -207
  135. package/package.json +13 -6
  136. package/dist/_baseForOwn-BfWDTL8L.cjs +0 -53
  137. package/dist/_baseForOwn-CFhWe_W6.js +0 -48
  138. package/dist/_getPrototype-CG7Dxrrz.js +0 -6
  139. package/dist/_getPrototype-DQDlNVVM.cjs +0 -10
  140. package/dist/_overArg-C5Hy7oCi.cjs +0 -196
  141. package/dist/_overArg-CRYbj1NH.js +0 -155
  142. package/dist/chat.d.ts +0 -401
  143. package/dist/common-BlRFtdf2.js +0 -807
  144. package/dist/common-BnvrDnIT.cjs +0 -860
  145. package/dist/compiler/plugins/track-tool-calls.d.ts +0 -33
  146. package/dist/compiler-C-OI9sim.cjs +0 -547
  147. package/dist/compiler-CW1VjQsn.js +0 -473
  148. package/dist/component-C6Agl2ns.cjs +0 -73
  149. package/dist/component-DGG7d_Mz.js +0 -44
  150. package/dist/component.d.ts +0 -88
  151. package/dist/component.default.d.ts +0 -278
  152. package/dist/custom-client-ChuZ63zp.js +0 -2658
  153. package/dist/custom-client-DAsGRnYc.cjs +0 -2729
  154. package/dist/dual-modes-DDkoCp3R.js +0 -3006
  155. package/dist/dual-modes-DPXiuvNe.cjs +0 -3090
  156. package/dist/errors-C962uJdS.cjs +0 -220
  157. package/dist/errors-Cg1G0Awu.js +0 -161
  158. package/dist/example-format.d.ts +0 -8
  159. package/dist/example.d.ts +0 -45
  160. package/dist/execute-BWcdv9so.js +0 -1059
  161. package/dist/execute-DM2-7y86.cjs +0 -1060
  162. package/dist/exit-parser.d.ts +0 -39
  163. package/dist/handlers.d.ts +0 -10
  164. package/dist/hoist.d.ts +0 -2
  165. package/dist/isEmpty-BhJRCqIF.js +0 -52
  166. package/dist/isEmpty-LY533Wmh.cjs +0 -57
  167. package/dist/isPlainObject-CSxXVKCk.cjs +0 -56
  168. package/dist/isPlainObject-D39AzPO2.js +0 -51
  169. package/dist/jsx-CIgdGGVs.js +0 -52
  170. package/dist/jsx-owqxrquU.cjs +0 -75
  171. package/dist/jsx.d.ts +0 -11
  172. package/dist/message-stream/index.d.ts +0 -9
  173. package/dist/message-stream/instructions.d.ts +0 -30
  174. package/dist/message-stream/normalizer.d.ts +0 -21
  175. package/dist/message-stream/parser.d.ts +0 -89
  176. package/dist/message-stream/registry.d.ts +0 -14
  177. package/dist/message-stream/replayable.d.ts +0 -27
  178. package/dist/message-stream/response-parser.d.ts +0 -24
  179. package/dist/message-stream/sanitize.d.ts +0 -10
  180. package/dist/message-stream/stream.d.ts +0 -54
  181. package/dist/message-stream/types.d.ts +0 -97
  182. package/dist/message-stream/validator.d.ts +0 -23
  183. package/dist/prompts/chat-mode/protocol.d.ts +0 -2
  184. package/dist/prompts/chat-mode/system.d.ts +0 -2
  185. package/dist/prompts/chat-mode/system.md.d.ts +0 -2
  186. package/dist/prompts/chat-mode/user.d.ts +0 -2
  187. package/dist/prompts/chat-mode/user.md.d.ts +0 -2
  188. package/dist/prompts/code-examples.d.ts +0 -2
  189. package/dist/prompts/common.d.ts +0 -7
  190. package/dist/prompts/dual-modes.d.ts +0 -2
  191. package/dist/prompts/execution-history.d.ts +0 -6
  192. package/dist/prompts/execution-state.d.ts +0 -3
  193. package/dist/prompts/protocol-basics.d.ts +0 -5
  194. package/dist/prompts/protocol.d.ts +0 -31
  195. package/dist/prompts/worker-mode/protocol.d.ts +0 -2
  196. package/dist/prompts/worker-mode/system.d.ts +0 -2
  197. package/dist/prompts/worker-mode/system.md.d.ts +0 -2
  198. package/dist/prompts/worker-mode/user.d.ts +0 -2
  199. package/dist/prompts/worker-mode/user.md.d.ts +0 -2
  200. package/dist/quickjs-variant-BYhMBpwU.js +0 -45
  201. package/dist/quickjs-variant-CsIwTVFC.cjs +0 -56
  202. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  203. package/dist/runtime/fixtures/qwen-protocol-failures.d.ts +0 -29
  204. package/dist/runtime/interpret-result.d.ts +0 -22
  205. package/dist/snapshots.d.ts +0 -249
  206. package/dist/stack-traces-BIE_5Xwf.js +0 -21
  207. package/dist/stack-traces-ntw_qhoy.cjs +0 -26
  208. package/dist/truncator-CLkouTCO.cjs +0 -276
  209. package/dist/truncator-DZqEqnpD.js +0 -253
  210. package/dist/truncator.d.ts +0 -118
  211. package/dist/utils-3ESwP3yg.cjs +0 -1075
  212. package/dist/utils-UBeAFeEI.js +0 -950
  213. /package/dist/{citations.d.ts → chat/citations.d.ts} +0 -0
  214. /package/dist/{citations.test.d.ts → chat/citations.test.d.ts} +0 -0
  215. /package/dist/{component.default.test.d.ts → chat/component.default.test.d.ts} +0 -0
  216. /package/dist/{compiler/plugins/track-tool-calls.test.d.ts → chat/component.test.d.ts} +0 -0
  217. /package/dist/{example.test.d.ts → chat/response.test.d.ts} +0 -0
  218. /package/dist/{exit-parser.test.d.ts → compiler/plugins/dynamic-code.test.d.ts} +0 -0
  219. /package/dist/{handlers.test.d.ts → compiler/plugins/tool-resolution.test.d.ts} +0 -0
  220. /package/dist/{hoist.test.d.ts → errors/catalog.test.d.ts} +0 -0
  221. /package/dist/{message-stream/instructions.test.d.ts → exit.test.d.ts} +0 -0
  222. /package/dist/{message-stream/normalizer.test.d.ts → inspection.test.d.ts} +0 -0
  223. /package/dist/{message-stream/parser.test.d.ts → prompts/native.test.d.ts} +0 -0
  224. /package/dist/{message-stream/response-parser.test.d.ts → result.test.d.ts} +0 -0
  225. /package/dist/{message-stream/stream.test.d.ts → runtime/chat-completion.test.d.ts} +0 -0
  226. /package/dist/{message-stream/validator.test.d.ts → runtime/chat-delivery.test.d.ts} +0 -0
  227. /package/dist/{prompts/adherence.test.d.ts → runtime/chat-last-speaker.test.d.ts} +0 -0
  228. /package/dist/{prompts/catalogue-examples.test.d.ts → runtime/compatibility-regressions.test.d.ts} +0 -0
  229. /package/dist/{prompts/code-examples.test.d.ts → runtime/context-registration.test.d.ts} +0 -0
  230. /package/dist/{prompts/common.test.d.ts → runtime/empty-completion.test.d.ts} +0 -0
  231. /package/dist/{prompts/concrete-patterns.test.d.ts → runtime/error-recovery.test.d.ts} +0 -0
  232. /package/dist/{prompts/long-search.test.d.ts → runtime/errors.test.d.ts} +0 -0
  233. /package/dist/{prompts/protocol-simple.test.d.ts → runtime/execution-activity.test.d.ts} +0 -0
  234. /package/dist/{prompts/protocol.test.d.ts → runtime/execution-diagnostics.test.d.ts} +0 -0
  235. /package/dist/{prompts/sections.test.d.ts → runtime/execution-report.test.d.ts} +0 -0
  236. /package/dist/runtime/{interpret-result.test.d.ts → execution-safety.test.d.ts} +0 -0
  237. /package/dist/{transcript.test.d.ts → runtime/exit-control-flow.test.d.ts} +0 -0
  238. /package/dist/{truncator.test.d.ts → runtime/fixtures/long-search.test.d.ts} +0 -0
@@ -1,10 +1,56 @@
1
- const require_compiler = require("./compiler-C-OI9sim.cjs");
2
- const require__baseIteratee = require("./_baseIteratee-CF4qP2a8.cjs");
3
- const require__baseForOwn = require("./_baseForOwn-BfWDTL8L.cjs");
4
- const require_stack_traces = require("./stack-traces-ntw_qhoy.cjs");
5
- const require_errors = require("./errors-C962uJdS.cjs");
6
- const require_quickjs_variant = require("./quickjs-variant-CsIwTVFC.cjs");
1
+ const require_utils = require("./utils-CTlsXvdj.cjs");
2
+ const require_errors = require("./errors-C6ppQUZX.cjs");
3
+ const require_quickjs_variant = require("./quickjs-variant-21IO97PF.cjs");
4
+ let magic_string = require("magic-string");
5
+ magic_string = require_utils.__toESM(magic_string, 1);
6
+ let acorn = require("acorn");
7
7
  let quickjs_emscripten_core = require("quickjs-emscripten-core");
8
+ //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_createBaseFor.js
9
+ /**
10
+ * Creates a base function for methods like `_.forIn` and `_.forOwn`.
11
+ *
12
+ * @private
13
+ * @param {boolean} [fromRight] Specify iterating from right to left.
14
+ * @returns {Function} Returns the new base function.
15
+ */
16
+ function createBaseFor(fromRight) {
17
+ return function(object, iteratee, keysFunc) {
18
+ var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length;
19
+ while (length--) {
20
+ var key = props[fromRight ? length : ++index];
21
+ if (iteratee(iterable[key], key, iterable) === false) break;
22
+ }
23
+ return object;
24
+ };
25
+ }
26
+ //#endregion
27
+ //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseFor.js
28
+ /**
29
+ * The base implementation of `baseForOwn` which iterates over `object`
30
+ * properties returned by `keysFunc` and invokes `iteratee` for each property.
31
+ * Iteratee functions may exit iteration early by explicitly returning `false`.
32
+ *
33
+ * @private
34
+ * @param {Object} object The object to iterate over.
35
+ * @param {Function} iteratee The function invoked per iteration.
36
+ * @param {Function} keysFunc The function to get the keys of `object`.
37
+ * @returns {Object} Returns `object`.
38
+ */
39
+ var baseFor = createBaseFor();
40
+ //#endregion
41
+ //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseForOwn.js
42
+ /**
43
+ * The base implementation of `_.forOwn` without support for iteratee shorthands.
44
+ *
45
+ * @private
46
+ * @param {Object} object The object to iterate over.
47
+ * @param {Function} iteratee The function invoked per iteration.
48
+ * @returns {Object} Returns `object`.
49
+ */
50
+ function baseForOwn(object, iteratee) {
51
+ return object && baseFor(object, iteratee, require_utils.keys);
52
+ }
53
+ //#endregion
8
54
  //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/_baseGt.js
9
55
  /**
10
56
  * The base implementation of `_.gt` which doesn't coerce arguments.
@@ -50,9 +96,9 @@ function baseGt(value, other) {
50
96
  */
51
97
  function mapValues(object, iteratee) {
52
98
  var result = {};
53
- iteratee = require__baseIteratee.baseIteratee(iteratee, 3);
54
- require__baseForOwn.baseForOwn(object, function(value, key, object) {
55
- require__baseIteratee.baseAssignValue(result, key, iteratee(value, key, object));
99
+ iteratee = require_utils.baseIteratee(iteratee, 3);
100
+ baseForOwn(object, function(value, key, object) {
101
+ require_utils.baseAssignValue(result, key, iteratee(value, key, object));
56
102
  });
57
103
  return result;
58
104
  }
@@ -72,7 +118,7 @@ function baseExtremum(array, iteratee, comparator) {
72
118
  var index = -1, length = array.length;
73
119
  while (++index < length) {
74
120
  var value = array[index], current = iteratee(value);
75
- if (current != null && (computed === void 0 ? current === current && !require__baseIteratee.isSymbol(current) : comparator(current, computed))) var computed = current, result = value;
121
+ if (current != null && (computed === void 0 ? current === current && !require_utils.isSymbol(current) : comparator(current, computed))) var computed = current, result = value;
76
122
  }
77
123
  return result;
78
124
  }
@@ -102,11 +148,11 @@ function baseExtremum(array, iteratee, comparator) {
102
148
  * // => { 'n': 2 }
103
149
  */
104
150
  function maxBy(array, iteratee) {
105
- return array && array.length ? baseExtremum(array, require__baseIteratee.baseIteratee(iteratee, 2), baseGt) : void 0;
151
+ return array && array.length ? baseExtremum(array, require_utils.baseIteratee(iteratee, 2), baseGt) : void 0;
106
152
  }
107
153
  //#endregion
108
154
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/base64.js
109
- var require_base64 = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
155
+ var require_base64 = /* @__PURE__ */ require_utils.__commonJSMin(((exports) => {
110
156
  var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");
111
157
  /**
112
158
  * Encode an integer in the range of 0 to 63 to a single base 64 digit.
@@ -140,7 +186,7 @@ var require_base64 = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) =
140
186
  }));
141
187
  //#endregion
142
188
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/base64-vlq.js
143
- var require_base64_vlq = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
189
+ var require_base64_vlq = /* @__PURE__ */ require_utils.__commonJSMin(((exports) => {
144
190
  var base64 = require_base64();
145
191
  var VLQ_BASE_SHIFT = 5;
146
192
  var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
@@ -205,7 +251,7 @@ var require_base64_vlq = /* @__PURE__ */ require_compiler.__commonJSMin(((export
205
251
  }));
206
252
  //#endregion
207
253
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/util.js
208
- var require_util = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
254
+ var require_util = /* @__PURE__ */ require_utils.__commonJSMin(((exports) => {
209
255
  /**
210
256
  * This is a helper function for getting values from parameter/options
211
257
  * objects.
@@ -552,7 +598,7 @@ var require_util = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) =>
552
598
  }));
553
599
  //#endregion
554
600
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/array-set.js
555
- var require_array_set = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
601
+ var require_array_set = /* @__PURE__ */ require_utils.__commonJSMin(((exports) => {
556
602
  var util = require_util();
557
603
  var has = Object.prototype.hasOwnProperty;
558
604
  var hasNativeMap = typeof Map !== "undefined";
@@ -646,7 +692,7 @@ var require_array_set = /* @__PURE__ */ require_compiler.__commonJSMin(((exports
646
692
  }));
647
693
  //#endregion
648
694
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/mapping-list.js
649
- var require_mapping_list = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
695
+ var require_mapping_list = /* @__PURE__ */ require_utils.__commonJSMin(((exports) => {
650
696
  var util = require_util();
651
697
  /**
652
698
  * Determine whether mappingB is after mappingA with respect to generated
@@ -715,7 +761,7 @@ var require_mapping_list = /* @__PURE__ */ require_compiler.__commonJSMin(((expo
715
761
  }));
716
762
  //#endregion
717
763
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/source-map-generator.js
718
- var require_source_map_generator = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
764
+ var require_source_map_generator = /* @__PURE__ */ require_utils.__commonJSMin(((exports) => {
719
765
  var base64VLQ = require_base64_vlq();
720
766
  var util = require_util();
721
767
  var ArraySet = require_array_set().ArraySet;
@@ -999,7 +1045,7 @@ var require_source_map_generator = /* @__PURE__ */ require_compiler.__commonJSMi
999
1045
  }));
1000
1046
  //#endregion
1001
1047
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/binary-search.js
1002
- var require_binary_search = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
1048
+ var require_binary_search = /* @__PURE__ */ require_utils.__commonJSMin(((exports) => {
1003
1049
  exports.GREATEST_LOWER_BOUND = 1;
1004
1050
  exports.LEAST_UPPER_BOUND = 2;
1005
1051
  /**
@@ -1060,7 +1106,7 @@ var require_binary_search = /* @__PURE__ */ require_compiler.__commonJSMin(((exp
1060
1106
  }));
1061
1107
  //#endregion
1062
1108
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/quick-sort.js
1063
- var require_quick_sort = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
1109
+ var require_quick_sort = /* @__PURE__ */ require_utils.__commonJSMin(((exports) => {
1064
1110
  function SortTemplate(comparator) {
1065
1111
  /**
1066
1112
  * Swap the elements indexed by `x` and `y` in the array `ary`.
@@ -1142,7 +1188,7 @@ var require_quick_sort = /* @__PURE__ */ require_compiler.__commonJSMin(((export
1142
1188
  }));
1143
1189
  //#endregion
1144
1190
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/source-map-consumer.js
1145
- var require_source_map_consumer = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
1191
+ var require_source_map_consumer = /* @__PURE__ */ require_utils.__commonJSMin(((exports) => {
1146
1192
  var util = require_util();
1147
1193
  var binarySearch = require_binary_search();
1148
1194
  var ArraySet = require_array_set().ArraySet;
@@ -1918,7 +1964,7 @@ var require_source_map_consumer = /* @__PURE__ */ require_compiler.__commonJSMin
1918
1964
  }));
1919
1965
  //#endregion
1920
1966
  //#region ../../node_modules/.pnpm/source-map-js@1.2.1_patch_hash=0354139cbc5dbd66e1bc59167ff8e42d3a9a2169038a35f1b7b1b4b843e08a6c/node_modules/source-map-js/lib/source-node.js
1921
- var require_source_node = /* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
1967
+ var require_source_node = /* @__PURE__ */ require_utils.__commonJSMin(((exports) => {
1922
1968
  var SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
1923
1969
  var util = require_util();
1924
1970
  var REGEX_NEWLINE = /(\r?\n)/;
@@ -2203,13 +2249,599 @@ var require_source_node = /* @__PURE__ */ require_compiler.__commonJSMin(((expor
2203
2249
  exports.SourceNode = SourceNode;
2204
2250
  }));
2205
2251
  //#endregion
2206
- //#region src/vm/errors.ts
2207
- var import_source_map = (/* @__PURE__ */ require_compiler.__commonJSMin(((exports) => {
2252
+ //#region src/compiler/ast.ts
2253
+ var import_source_map = (/* @__PURE__ */ require_utils.__commonJSMin(((exports) => {
2208
2254
  exports.SourceMapGenerator = require_source_map_generator().SourceMapGenerator;
2209
2255
  exports.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer;
2210
2256
  exports.SourceNode = require_source_node().SourceNode;
2211
2257
  })))();
2212
- const handleErrorQuickJS = (err, code, _consumer, traces, variables, lines_executed, userCodeStartLine, currentToolCall) => {
2258
+ const TS_SMELL = /(^|[^:]):\s*(string|number|boolean|any|unknown|void)\b|\bas\s+(const\b|[A-Z])|\binterface\s+[A-Z]|^\s*type\s+[A-Z]|[a-zA-Z)\]]!\.|<(string|number|boolean)[,>]/m;
2259
+ function parseScript(code, opts) {
2260
+ try {
2261
+ return (0, acorn.parse)(code, {
2262
+ ecmaVersion: "latest",
2263
+ sourceType: "script",
2264
+ locations: true,
2265
+ allowReturnOutsideFunction: true,
2266
+ allowAwaitOutsideFunction: true,
2267
+ ...opts,
2268
+ onComment: opts === null || opts === void 0 ? void 0 : opts.comments
2269
+ });
2270
+ } catch (err) {
2271
+ if (err instanceof SyntaxError && TS_SMELL.test(code)) err.message += ". The code must be plain JavaScript: do not use TypeScript syntax (type annotations, \"as\" casts, generics, interfaces or type aliases).";
2272
+ throw err;
2273
+ }
2274
+ }
2275
+ /**
2276
+ * Depth-first pre-order walk. `ancestors` is ordered outermost → innermost and
2277
+ * excludes `node` itself; `parent` is `ancestors[ancestors.length - 1]`.
2278
+ */
2279
+ function walk(root, enter) {
2280
+ const ancestors = [];
2281
+ const visit = (node) => {
2282
+ enter(node, ancestors[ancestors.length - 1] ?? null, ancestors);
2283
+ ancestors.push(node);
2284
+ for (const key of Object.keys(node)) {
2285
+ if (key === "loc") continue;
2286
+ const value = node[key];
2287
+ if (Array.isArray(value)) {
2288
+ for (const child of value) if (isNode(child)) visit(child);
2289
+ } else if (isNode(value)) visit(value);
2290
+ }
2291
+ ancestors.pop();
2292
+ };
2293
+ visit(root);
2294
+ }
2295
+ const isNode = (value) => !!value && typeof value === "object" && typeof value.type === "string";
2296
+ const isStatementContainer = (node) => !!node && (node.type === "Program" || node.type === "BlockStatement" || node.type === "StaticBlock");
2297
+ /**
2298
+ * The statement that contains `node`: the outermost ancestor (or the node
2299
+ * itself) whose parent is a statement container.
2300
+ */
2301
+ function enclosingStatement(node, ancestors) {
2302
+ const chain = [...ancestors, node];
2303
+ for (let i = chain.length - 1; i > 0; i--) if (isStatementContainer(chain[i - 1])) return chain[i];
2304
+ return null;
2305
+ }
2306
+ /** The innermost node whose range contains [start, end] */
2307
+ function innermostContaining(ast, start, end) {
2308
+ let best = null;
2309
+ walk(ast, (node) => {
2310
+ if (node.start <= start && node.end >= end) {
2311
+ if (!best || node.start >= best.start && node.end <= best.end) best = node;
2312
+ }
2313
+ });
2314
+ return best;
2315
+ }
2316
+ //#endregion
2317
+ //#region src/compiler/plugins/async-wrapper.ts
2318
+ const Open = "async function __fn__() {";
2319
+ const Close = "}";
2320
+ const USER_CODE_START_MARKER = "/* __LLMZ_USER_CODE_START__ */";
2321
+ const USER_CODE_END_MARKER = "/* __LLMZ_USER_CODE_END__ */";
2322
+ /**
2323
+ * Wraps user code in an async function so top-level `await` and `return` parse,
2324
+ * and so plugins can target the `__fn__` declaration. The wrapper is removed
2325
+ * after transformation — drivers re-wrap the bare statements themselves.
2326
+ */
2327
+ const AsyncWrapper = {
2328
+ preProcessing: (code) => {
2329
+ return `"use strict";
2330
+ ${Open}
2331
+ ${USER_CODE_START_MARKER}
2332
+ ${code}
2333
+ ${USER_CODE_END_MARKER}
2334
+ ${Close}
2335
+ `.trim();
2336
+ },
2337
+ postProcessing: (code) => {
2338
+ code = code.slice(code.indexOf(Open) + 25);
2339
+ code = code.slice(0, code.lastIndexOf(Close));
2340
+ code = code.replace(USER_CODE_START_MARKER, "").replace(USER_CODE_END_MARKER, "");
2341
+ return code.trimEnd();
2342
+ }
2343
+ };
2344
+ //#endregion
2345
+ //#region src/compiler/plugins/dynamic-code.ts
2346
+ const DYNAMIC_GLOBALS = /* @__PURE__ */ new Set([
2347
+ "eval",
2348
+ "Function",
2349
+ "AsyncFunction",
2350
+ "GeneratorFunction",
2351
+ "AsyncGeneratorFunction"
2352
+ ]);
2353
+ const GLOBAL_OBJECTS = /* @__PURE__ */ new Set([
2354
+ "globalThis",
2355
+ "global",
2356
+ "window",
2357
+ "self"
2358
+ ]);
2359
+ const INVOCATION_METHODS = /* @__PURE__ */ new Set([
2360
+ "call",
2361
+ "apply",
2362
+ "bind"
2363
+ ]);
2364
+ function propertyName(node) {
2365
+ if (!node.computed && node.property.type === "Identifier") return node.property.name;
2366
+ if (node.property.type === "Literal" && typeof node.property.value === "string") return node.property.value;
2367
+ }
2368
+ function isConstructorAccess(node) {
2369
+ return node.type === "MemberExpression" && propertyName(node) === "constructor";
2370
+ }
2371
+ function isReference(node, parent) {
2372
+ if (!parent) return true;
2373
+ if (parent.type === "MemberExpression" && parent.property === node && !parent.computed) return false;
2374
+ if (parent.type === "Property" && parent.key === node && !parent.computed && !parent.shorthand) return false;
2375
+ return parent.type !== "VariableDeclarator" || parent.id !== node;
2376
+ }
2377
+ /**
2378
+ * Dynamically generated source bypasses the VM's control-flow instrumentation.
2379
+ * Reject identifiable entry points and constructor aliases. This is a language
2380
+ * restriction, not a security boundary against reflective JavaScript escapes.
2381
+ */
2382
+ function rejectDynamicCode(ast) {
2383
+ const constructorAliases = /* @__PURE__ */ new Set();
2384
+ const globalAliases = new Set(GLOBAL_OBJECTS);
2385
+ const aliasAssignments = [];
2386
+ const reject = () => {
2387
+ throw new Error("Dynamic code generation is not supported in run_javascript. Write JavaScript directly; do not use eval, Function, or async/generator function constructors.");
2388
+ };
2389
+ walk(ast, (node, parent) => {
2390
+ if (node.type === "Identifier" && DYNAMIC_GLOBALS.has(node.name) && isReference(node, parent)) reject();
2391
+ if (node.type === "MemberExpression" && node.object.type === "Identifier" && GLOBAL_OBJECTS.has(node.object.name) && DYNAMIC_GLOBALS.has(propertyName(node) ?? "")) reject();
2392
+ if (node.type === "VariableDeclarator" && node.init) {
2393
+ if (node.id.type === "Identifier") aliasAssignments.push({
2394
+ name: node.id.name,
2395
+ value: node.init
2396
+ });
2397
+ if (node.id.type === "ObjectPattern") for (const property of node.id.properties) {
2398
+ var _property$key, _property$key2, _property$key3, _property$value;
2399
+ if ((property.computed ? (_property$key = property.key) === null || _property$key === void 0 ? void 0 : _property$key.value : ((_property$key2 = property.key) === null || _property$key2 === void 0 ? void 0 : _property$key2.name) ?? ((_property$key3 = property.key) === null || _property$key3 === void 0 ? void 0 : _property$key3.value)) === "constructor" && ((_property$value = property.value) === null || _property$value === void 0 ? void 0 : _property$value.type) === "Identifier") constructorAliases.add(property.value.name);
2400
+ }
2401
+ }
2402
+ if (node.type === "AssignmentExpression" && node.left.type === "Identifier") aliasAssignments.push({
2403
+ name: node.left.name,
2404
+ value: node.right
2405
+ });
2406
+ });
2407
+ let changed = true;
2408
+ while (changed) {
2409
+ changed = false;
2410
+ for (const { name, value } of aliasAssignments) {
2411
+ const fromAlias = value.type === "Identifier" && constructorAliases.has(value.name);
2412
+ if (!constructorAliases.has(name) && (isConstructorAccess(value) || fromAlias)) {
2413
+ constructorAliases.add(name);
2414
+ changed = true;
2415
+ }
2416
+ if (value.type === "Identifier" && globalAliases.has(value.name) && !globalAliases.has(name)) {
2417
+ globalAliases.add(name);
2418
+ changed = true;
2419
+ }
2420
+ }
2421
+ }
2422
+ walk(ast, (node) => {
2423
+ var _node$init;
2424
+ if (node.type === "MemberExpression" && node.object.type === "Identifier" && globalAliases.has(node.object.name) && DYNAMIC_GLOBALS.has(propertyName(node) ?? "")) reject();
2425
+ if (node.type === "VariableDeclarator" && node.id.type === "ObjectPattern" && ((_node$init = node.init) === null || _node$init === void 0 ? void 0 : _node$init.type) === "Identifier" && globalAliases.has(node.init.name)) {
2426
+ if (node.id.properties.some((property) => {
2427
+ var _property$key4, _property$key5, _property$key6;
2428
+ const key = property.computed ? (_property$key4 = property.key) === null || _property$key4 === void 0 ? void 0 : _property$key4.value : ((_property$key5 = property.key) === null || _property$key5 === void 0 ? void 0 : _property$key5.name) ?? ((_property$key6 = property.key) === null || _property$key6 === void 0 ? void 0 : _property$key6.value);
2429
+ return DYNAMIC_GLOBALS.has(key);
2430
+ })) reject();
2431
+ }
2432
+ if (node.type !== "CallExpression" && node.type !== "NewExpression") return;
2433
+ let callee = node.callee;
2434
+ while (callee.type === "MemberExpression" && INVOCATION_METHODS.has(propertyName(callee) ?? "")) callee = callee.object;
2435
+ if (isConstructorAccess(callee) || callee.type === "Identifier" && constructorAliases.has(callee.name)) reject();
2436
+ });
2437
+ }
2438
+ //#endregion
2439
+ //#region src/compiler/plugins/line-tracking.ts
2440
+ const LineTrackingFnIdentifier = "__track__";
2441
+ const TRACKED_TYPES = /* @__PURE__ */ new Set([
2442
+ "FunctionDeclaration",
2443
+ "MethodDefinition",
2444
+ "ReturnStatement",
2445
+ "AwaitExpression",
2446
+ "ForOfStatement",
2447
+ "CallExpression",
2448
+ "UnaryExpression",
2449
+ "VariableDeclaration",
2450
+ "AssignmentExpression"
2451
+ ]);
2452
+ const SKIPPED_PARENT_TYPES = /* @__PURE__ */ new Set([
2453
+ "ArrowFunctionExpression",
2454
+ "Property",
2455
+ "AwaitExpression",
2456
+ "UnaryExpression",
2457
+ "ReturnStatement",
2458
+ "ForOfStatement",
2459
+ "ForStatement",
2460
+ "ForInStatement",
2461
+ "VariableDeclaration",
2462
+ "BinaryExpression",
2463
+ "LogicalExpression"
2464
+ ]);
2465
+ /**
2466
+ * Inserts a `__track__(<line>)` call before the statement containing each
2467
+ * tracked node — at most one per source line.
2468
+ */
2469
+ function applyLineTracking(ctx) {
2470
+ const trackedLines = /* @__PURE__ */ new Set();
2471
+ walk(ctx.ast, (node, parent, ancestors) => {
2472
+ if (!parent || !node.loc) return;
2473
+ if (!TRACKED_TYPES.has(node.type) && parent.type !== "BlockStatement") return;
2474
+ const line = node.loc.start.line;
2475
+ if (trackedLines.has(line) || SKIPPED_PARENT_TYPES.has(parent.type)) return;
2476
+ const statement = enclosingStatement(node, ancestors);
2477
+ if (!statement) return;
2478
+ trackedLines.add(line);
2479
+ ctx.ms.appendLeft(statement.start, `${LineTrackingFnIdentifier}(${line});`);
2480
+ });
2481
+ }
2482
+ //#endregion
2483
+ //#region src/compiler/plugins/replace-comment.ts
2484
+ const CommentFnIdentifier = "__comment__";
2485
+ const MARKER_TAGS = [USER_CODE_START_MARKER, USER_CODE_END_MARKER].map((m) => m.replace(/\/\*|\*\/|\s/g, ""));
2486
+ /** Blanks a range, keeping newlines so line numbers are preserved */
2487
+ const blank = (ctx, start, end) => {
2488
+ ctx.ms.update(start, end, ctx.code.slice(start, end).replace(/[^\n]/g, " "));
2489
+ };
2490
+ /**
2491
+ * Replaces comments at statement position with `__comment__("<text>", <line>)`
2492
+ * calls so the agent's inline "thinking" comments show up as traces at runtime.
2493
+ * Comments inside expressions and the user-code markers are blanked.
2494
+ */
2495
+ function applyCommentReplacement(ctx) {
2496
+ for (const comment of ctx.comments) {
2497
+ const text = comment.value.trim();
2498
+ if (MARKER_TAGS.some((tag) => text.includes(tag))) {
2499
+ blank(ctx, comment.start, comment.end);
2500
+ continue;
2501
+ }
2502
+ const container = innermostContaining(ctx.ast, comment.start, comment.end);
2503
+ if (isStatementContainer(container)) {
2504
+ const newlines = ctx.code.slice(comment.start, comment.end).replace(/[^\n]/g, "");
2505
+ ctx.ms.update(comment.start, comment.end, `;${CommentFnIdentifier}(${JSON.stringify(text)}, ${comment.loc.start.line});${newlines}`);
2506
+ } else blank(ctx, comment.start, comment.end);
2507
+ }
2508
+ }
2509
+ //#endregion
2510
+ //#region src/compiler/plugins/return-async.ts
2511
+ /**
2512
+ * Awaits the last expression without changing whether the program returns it.
2513
+ * The isolated VM cannot return a pending Promise:
2514
+ * - `return expr` → `return await (expr)`
2515
+ * - a trailing `call()` / `await call()` statement → `await (…)`
2516
+ *
2517
+ * Discarded values must stay discarded, especially terminal decision receipts.
2518
+ *
2519
+ * The prefix must be applied before, and the suffix after, all other edits so
2520
+ * they wrap around the tool-call instrumentation.
2521
+ */
2522
+ function planLastLineInstrumentation(ast) {
2523
+ const fn = ast.body.find((node) => {
2524
+ var _id;
2525
+ return node.type === "FunctionDeclaration" && ((_id = node.id) === null || _id === void 0 ? void 0 : _id.name) === "__fn__";
2526
+ });
2527
+ if (!fn) return null;
2528
+ const statements = fn.body.body;
2529
+ const last = statements[statements.length - 1];
2530
+ if (!last) return null;
2531
+ if (last.type === "ReturnStatement") {
2532
+ if (!last.argument) return null;
2533
+ return {
2534
+ prefixPos: last.argument.start,
2535
+ prefix: "await (",
2536
+ suffixPos: last.argument.end,
2537
+ suffix: ")"
2538
+ };
2539
+ }
2540
+ if (last.type === "ExpressionStatement" && (last.expression.type === "CallExpression" || last.expression.type === "AwaitExpression")) return {
2541
+ prefixPos: last.expression.start,
2542
+ prefix: "await (",
2543
+ suffixPos: last.expression.end,
2544
+ suffix: ")"
2545
+ };
2546
+ return null;
2547
+ }
2548
+ //#endregion
2549
+ //#region src/compiler/plugins/termination.ts
2550
+ const TerminationGuardIdentifier = "__llmz_guard";
2551
+ const TerminationCheckpointIdentifier = "__llmz_checkpoint";
2552
+ const FUNCTIONS = /* @__PURE__ */ new Set([
2553
+ "FunctionDeclaration",
2554
+ "FunctionExpression",
2555
+ "ArrowFunctionExpression"
2556
+ ]);
2557
+ const INTERNAL_CALLS = /* @__PURE__ */ new Set([
2558
+ "__var__",
2559
+ "__track__",
2560
+ "__comment__"
2561
+ ]);
2562
+ /**
2563
+ * A terminal host call unwinds ordinary JavaScript. User error handlers must not
2564
+ * consume that control flow, and async continuations must check before resuming.
2565
+ */
2566
+ function applyTerminationGuards(ctx) {
2567
+ const suffixes = [];
2568
+ const wrapper = ctx.ast.body.find((node) => {
2569
+ var _id;
2570
+ return node.type === "FunctionDeclaration" && ((_id = node.id) === null || _id === void 0 ? void 0 : _id.name) === "__fn__";
2571
+ });
2572
+ const guard = `${TerminationGuardIdentifier}();`;
2573
+ const wrap = (node, prefix) => {
2574
+ ctx.ms.appendLeft(node.start, prefix);
2575
+ suffixes.unshift(() => ctx.ms.appendRight(node.end, ")"));
2576
+ };
2577
+ const isCaptureGetter = (node, parent) => (parent === null || parent === void 0 ? void 0 : parent.type) === "CallExpression" && parent.callee.name === "__var__" && parent.arguments[1] === node;
2578
+ walk(ctx.ast, (node, parent, ancestors) => {
2579
+ if (isCaptureGetter(node, parent) || ancestors.some((ancestor, index) => isCaptureGetter(ancestor, ancestors[index - 1] ?? null))) return;
2580
+ if (node.type === "CallExpression" && node.callee.type === "Identifier" && INTERNAL_CALLS.has(node.callee.name)) return;
2581
+ if (node.type === "CatchClause") {
2582
+ ctx.ms.appendLeft(node.body.start + 1, guard);
2583
+ return;
2584
+ }
2585
+ if (node.type === "TryStatement" && node.finalizer) ctx.ms.appendLeft(node.finalizer.start + 1, guard);
2586
+ if (FUNCTIONS.has(node.type)) {
2587
+ if (node === wrapper) return;
2588
+ if (node.body.type === "BlockStatement") ctx.ms.appendLeft(node.body.start + 1, guard);
2589
+ else wrap(node.body, `(${TerminationGuardIdentifier}(), `);
2590
+ }
2591
+ if (node.type === "AssignmentPattern") wrap(node.right, `(${TerminationGuardIdentifier}(), `);
2592
+ if ([
2593
+ "AwaitExpression",
2594
+ "CallExpression",
2595
+ "NewExpression",
2596
+ "TaggedTemplateExpression"
2597
+ ].includes(node.type)) {
2598
+ wrap(node, `(${TerminationGuardIdentifier}(), ${TerminationCheckpointIdentifier}(`);
2599
+ suffixes.unshift(() => ctx.ms.appendRight(node.end, ")"));
2600
+ }
2601
+ if (node.type === "AssignmentExpression" || node.type === "UpdateExpression" || node.type === "UnaryExpression" && node.operator === "delete") wrap(node, `(${TerminationGuardIdentifier}(), `);
2602
+ });
2603
+ return () => suffixes.forEach((apply) => apply());
2604
+ }
2605
+ //#endregion
2606
+ //#region src/compiler/plugins/tool-resolution.ts
2607
+ const MissingToolIdentifier = "__llmz_missing_tool";
2608
+ /** Diagnose missing free callables at the lookup, before evaluating their arguments. */
2609
+ function applyToolResolution({ ast, ms }) {
2610
+ const declared = /* @__PURE__ */ new Set();
2611
+ const collect = (pattern) => {
2612
+ walk(pattern, (node) => {
2613
+ if (node.type === "Identifier") declared.add(node.name);
2614
+ });
2615
+ };
2616
+ walk(ast, (node) => {
2617
+ if (node.type === "VariableDeclarator") collect(node.id);
2618
+ else if ([
2619
+ "FunctionDeclaration",
2620
+ "FunctionExpression",
2621
+ "ArrowFunctionExpression"
2622
+ ].includes(node.type)) {
2623
+ if (node.id) collect(node.id);
2624
+ for (const param of node.params) collect(param);
2625
+ } else if (node.type === "CatchClause" && node.param) collect(node.param);
2626
+ else if (node.type === "ClassDeclaration" && node.id) collect(node.id);
2627
+ });
2628
+ walk(ast, (node) => {
2629
+ if (node.type !== "CallExpression" || node.optional || node.callee.type !== "Identifier") return;
2630
+ const name = node.callee.name;
2631
+ if (declared.has(name) || name.startsWith("__")) return;
2632
+ ms.overwrite(node.callee.start, node.callee.end, `(typeof ${name} === "undefined" ? ${MissingToolIdentifier}(${JSON.stringify(name)}) : ${name})`);
2633
+ });
2634
+ }
2635
+ //#endregion
2636
+ //#region src/compiler/plugins/variable-extraction.ts
2637
+ const VariableTrackingFnIdentifier = "__var__";
2638
+ const FUNCTION_TYPES = /* @__PURE__ */ new Set([
2639
+ "FunctionDeclaration",
2640
+ "FunctionExpression",
2641
+ "ArrowFunctionExpression"
2642
+ ]);
2643
+ const RESERVED = require_quickjs_variant.RESERVED_RUNTIME_NAMES;
2644
+ function names(id) {
2645
+ if (!id) return [];
2646
+ if (id.type === "Identifier") return [id.name];
2647
+ if (id.type === "RestElement") return names(id.argument);
2648
+ if (id.type === "AssignmentPattern") return names(id.left);
2649
+ if (id.type === "ObjectPattern") return id.properties.flatMap((prop) => names(prop.type === "RestElement" ? prop.argument : prop.value));
2650
+ if (id.type === "ArrayPattern") return id.elements.flatMap(names);
2651
+ return [];
2652
+ }
2653
+ function rootName(node) {
2654
+ if (node.type === "Identifier") return node.name;
2655
+ if (node.type === "MemberExpression") return rootName(node.object);
2656
+ }
2657
+ /** Capture only session-level bindings, and record completed writes without changing expression values. */
2658
+ function applyVariableTracking(ctx, variables, deferSuffixes = false) {
2659
+ const suffixes = [];
2660
+ const wrapper = ctx.ast.body.find((node) => {
2661
+ var _node$id;
2662
+ return node.type === "FunctionDeclaration" && ((_node$id = node.id) === null || _node$id === void 0 ? void 0 : _node$id.name) === "__fn__";
2663
+ });
2664
+ const root = (wrapper === null || wrapper === void 0 ? void 0 : wrapper.body) ?? ctx.ast;
2665
+ const scopes = /* @__PURE__ */ new Map();
2666
+ const sessionDeclarations = /* @__PURE__ */ new Set();
2667
+ const varBindings = /* @__PURE__ */ new Set();
2668
+ const scope = (node) => {
2669
+ if (!scopes.has(node)) scopes.set(node, /* @__PURE__ */ new Set());
2670
+ return scopes.get(node);
2671
+ };
2672
+ const owner = (ancestors, isVar = false) => [...ancestors].reverse().find((node) => node === root || node.type === "Program" || node.type === "StaticBlock" || FUNCTION_TYPES.has(node.type) || !isVar && (node.type === "BlockStatement" || node.type === "SwitchStatement" || node.type === "CatchClause" || node.type === "ForStatement" || node.type === "ForOfStatement" || node.type === "ForInStatement")) ?? root;
2673
+ walk(ctx.ast, (node, parent, ancestors) => {
2674
+ let declared = [];
2675
+ if (node.type === "VariableDeclarator") {
2676
+ declared = names(node.id);
2677
+ const bindingScope = owner(ancestors, (parent === null || parent === void 0 ? void 0 : parent.kind) === "var");
2678
+ for (const name of declared) scope(bindingScope).add(name);
2679
+ if (bindingScope === root) {
2680
+ sessionDeclarations.add(node);
2681
+ for (const name of declared.filter((name) => !name.startsWith("__"))) {
2682
+ variables.add(name);
2683
+ if ((parent === null || parent === void 0 ? void 0 : parent.kind) === "var") varBindings.add(name);
2684
+ }
2685
+ }
2686
+ } else if (FUNCTION_TYPES.has(node.type)) {
2687
+ declared = node.params.flatMap(names);
2688
+ if (node.id) declared.push(node.id.name);
2689
+ for (const name of declared) scope(node).add(name);
2690
+ } else if (node.type === "CatchClause" && node.param) {
2691
+ declared = names(node.param);
2692
+ for (const name of declared) scope(node).add(name);
2693
+ }
2694
+ for (const name of declared) if (RESERVED.has(name)) throw new require_errors.ReservedIdentifierError(name, "variable", false, `${name} is reserved for runtime memory`);
2695
+ });
2696
+ const eligible = (name, ancestors) => {
2697
+ if (name.startsWith("__")) return false;
2698
+ for (const ancestor of [...ancestors].reverse()) {
2699
+ var _scopes$get;
2700
+ if (ancestor === root) return true;
2701
+ if ((_scopes$get = scopes.get(ancestor)) === null || _scopes$get === void 0 ? void 0 : _scopes$get.has(name)) return false;
2702
+ }
2703
+ return true;
2704
+ };
2705
+ const wrap = (node, bindingNames, kind = "assignment") => {
2706
+ if (!bindingNames.length) return;
2707
+ ctx.ms.appendLeft(node.start, bindingNames.map((name) => `${VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => eval(${JSON.stringify(name)}), (`).join(""));
2708
+ suffixes.unshift(() => ctx.ms.appendRight(node.end, bindingNames.map(() => `), ${JSON.stringify(kind)})`).join("")));
2709
+ };
2710
+ const varGetters = [...varBindings].map((name) => `${VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => eval(${JSON.stringify(name)}), undefined, "initialize");`).join("");
2711
+ const entry = root.body.find((node) => !node.directive);
2712
+ if (entry && varGetters) ctx.ms.appendLeft(entry.start, varGetters);
2713
+ walk(ctx.ast, (node, parent, ancestors) => {
2714
+ if (node.type === "VariableDeclaration" && parent === root && node.kind !== "var") {
2715
+ const declared = node.declarations.flatMap((declaration) => names(declaration.id)).filter((name) => variables.has(name));
2716
+ ctx.ms.appendLeft(node.start, declared.map((name) => `${VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => eval(${JSON.stringify(name)}), undefined, "initialize");`).join(""));
2717
+ }
2718
+ if (node.type === "VariableDeclarator" && sessionDeclarations.has(node)) {
2719
+ const declared = names(node.id).filter((name) => variables.has(name) && eligible(name, ancestors));
2720
+ if (node.init) wrap(node.init, declared);
2721
+ else if (parent && parent.kind !== "var") {
2722
+ const trackers = declared.map((name) => `${VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => eval(${JSON.stringify(name)}));`).join("");
2723
+ ctx.ms.appendRight(parent.end, `${ctx.code[parent.end - 1] === ";" ? "" : ";"}${trackers}`);
2724
+ }
2725
+ }
2726
+ if ((node.type === "ForOfStatement" || node.type === "ForInStatement") && node.left.type === "VariableDeclaration") {
2727
+ const declared = node.left.declarations.filter((declaration) => sessionDeclarations.has(declaration)).flatMap((declaration) => names(declaration.id)).filter((name) => eligible(name, ancestors));
2728
+ if (declared.length) {
2729
+ const trackers = declared.map((name) => `${VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => eval(${JSON.stringify(name)}));`).join("");
2730
+ ctx.ms.appendLeft(node.body.start, `{${trackers}`);
2731
+ suffixes.unshift(() => ctx.ms.appendRight(node.body.end, "}"));
2732
+ }
2733
+ }
2734
+ if (node.type === "AssignmentExpression" || node.type === "UpdateExpression" || node.type === "UnaryExpression" && node.operator === "delete") {
2735
+ const target = node.left ?? node.argument;
2736
+ const roots = target.type === "MemberExpression" ? [rootName(target)].filter(Boolean) : names(target);
2737
+ for (const name of roots) if (RESERVED.has(name)) throw new require_errors.AssignmentError(`${name} is read-only runtime memory`);
2738
+ const tracked = [...new Set(roots)].filter((name) => eligible(name, ancestors));
2739
+ const kind = target.type === "MemberExpression" ? "mutation" : "assignment";
2740
+ if ([
2741
+ "||=",
2742
+ "&&=",
2743
+ "??="
2744
+ ].includes(node.operator)) {
2745
+ if (target.type === "Identifier" && tracked.length) {
2746
+ const name = tracked[0];
2747
+ const operator = node.operator.slice(0, -1);
2748
+ const lineBreaks = ctx.code.slice(target.end, node.right.start).replace(/[^\n]/g, "");
2749
+ ctx.ms.appendLeft(node.start, "(");
2750
+ ctx.ms.overwrite(target.end, node.right.start, ` ${operator} ${lineBreaks}`);
2751
+ ctx.ms.appendLeft(node.right.start, `${VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => eval(${JSON.stringify(name)}), (${name} = (`);
2752
+ suffixes.unshift(() => ctx.ms.appendRight(node.end, `)), "assignment"))`));
2753
+ }
2754
+ return;
2755
+ }
2756
+ wrap(node, tracked, kind);
2757
+ }
2758
+ });
2759
+ const finish = () => suffixes.forEach((apply) => apply());
2760
+ if (!deferSuffixes) finish();
2761
+ return finish;
2762
+ }
2763
+ //#endregion
2764
+ //#region src/compiler/compiler.ts
2765
+ const Identifiers = {
2766
+ ConsoleObjIdentifier: "console",
2767
+ LineTrackingFnIdentifier,
2768
+ VariableTrackingFnIdentifier,
2769
+ CommentFnIdentifier
2770
+ };
2771
+ /**
2772
+ * Compiles the agent's generated JavaScript for VM execution:
2773
+ *
2774
+ * 1. wraps it in an async `__fn__` so top-level `await`/`return` parse
2775
+ * 2. instruments it in a single parse + text-edit pass:
2776
+ * line tracking, last-line awaiting, comment tracing and variable tracking
2777
+ * 3. unwraps it — the VM drivers re-wrap the bare statements themselves
2778
+ *
2779
+ * All edits preserve line numbers 1:1 with the wrapped source, so positions
2780
+ * reported at runtime map straight back to the user code.
2781
+ */
2782
+ function compile(code) {
2783
+ try {
2784
+ return compileProgram(code);
2785
+ } catch (cause) {
2786
+ if (require_errors.isLLMzError(cause)) throw cause;
2787
+ throw new require_errors.InvalidCodeError(cause instanceof Error ? cause.message : String(cause), code, { cause });
2788
+ }
2789
+ }
2790
+ function compileProgram(code) {
2791
+ const wrapped = AsyncWrapper.preProcessing(code);
2792
+ const comments = [];
2793
+ const ast = parseScript(wrapped, { comments });
2794
+ rejectDynamicCode(ast);
2795
+ const variables = /* @__PURE__ */ new Set();
2796
+ const lastLine = planLastLineInstrumentation(ast);
2797
+ const msMarkers = new magic_string.default(wrapped);
2798
+ if (lastLine) {
2799
+ msMarkers.appendLeft(lastLine.prefixPos, lastLine.prefix);
2800
+ msMarkers.appendRight(lastLine.suffixPos, lastLine.suffix);
2801
+ }
2802
+ const codeWithMarkers = msMarkers.toString();
2803
+ const ms = new magic_string.default(wrapped);
2804
+ const ctx = {
2805
+ code: wrapped,
2806
+ ms,
2807
+ ast,
2808
+ comments
2809
+ };
2810
+ applyToolResolution(ctx);
2811
+ applyLineTracking(ctx);
2812
+ if (lastLine) ms.appendLeft(lastLine.prefixPos, lastLine.prefix);
2813
+ const finishVariableTracking = applyVariableTracking(ctx, variables, true);
2814
+ applyCommentReplacement(ctx);
2815
+ finishVariableTracking();
2816
+ if (lastLine) ms.appendRight(lastLine.suffixPos, lastLine.suffix);
2817
+ const instrumented = ms.toString();
2818
+ const terminationSource = new magic_string.default(instrumented);
2819
+ applyTerminationGuards({
2820
+ code: instrumented,
2821
+ ms: terminationSource,
2822
+ ast: parseScript(instrumented),
2823
+ comments: []
2824
+ })();
2825
+ const firstMap = ms.generateMap({
2826
+ hires: true,
2827
+ source: "<anonymous>"
2828
+ });
2829
+ const secondMap = terminationSource.generateMap({
2830
+ hires: true,
2831
+ source: "<instrumented>"
2832
+ });
2833
+ const map = import_source_map.SourceMapGenerator.fromSourceMap(new import_source_map.SourceMapConsumer(JSON.parse(secondMap.toString())));
2834
+ map.applySourceMap(new import_source_map.SourceMapConsumer(JSON.parse(firstMap.toString())), "<instrumented>");
2835
+ return {
2836
+ code: AsyncWrapper.postProcessing(terminationSource.toString()),
2837
+ codeWithMarkers,
2838
+ map: map.toJSON(),
2839
+ variables
2840
+ };
2841
+ }
2842
+ //#endregion
2843
+ //#region src/vm/errors.ts
2844
+ const handleErrorQuickJS = (err, code, _consumer, traces, variables, lines_executed, userCodeStartLine, recordTrace) => {
2213
2845
  err = require_errors.Signals.maybeDeserializeError(err);
2214
2846
  const lines = code.split("\n");
2215
2847
  const stackTrace = err.stack || "";
@@ -2234,9 +2866,9 @@ const handleErrorQuickJS = (err, code, _consumer, traces, variables, lines_execu
2234
2866
  column: whiteSpacesCount
2235
2867
  });
2236
2868
  }
2237
- return formatError(err, lines, matches, traces, variables, lines_executed, currentToolCall, code);
2869
+ return formatError(err, lines, matches, traces, variables, lines_executed, code, recordTrace);
2238
2870
  };
2239
- const handleErrorNode = (err, code, consumer, traces, variables, _lines_executed, currentToolCall) => {
2871
+ const handleErrorNode = (err, code, consumer, recordTrace, variables, _lines_executed, lastExecutedLine) => {
2240
2872
  err = require_errors.Signals.maybeDeserializeError(err);
2241
2873
  const lines = code.split("\n");
2242
2874
  const stackTrace = err.stack || "";
@@ -2259,32 +2891,39 @@ const handleErrorNode = (err, code, consumer, traces, variables, _lines_executed
2259
2891
  column: Math.min(minColumn, Number(x[2]))
2260
2892
  };
2261
2893
  });
2894
+ if (!matches.length && lastExecutedLine !== void 0) {
2895
+ const sourceLine = lines[lastExecutedLine - LINE_OFFSET] ?? "";
2896
+ matches.push({
2897
+ line: lastExecutedLine,
2898
+ column: sourceLine.length - sourceLine.trimStart().length
2899
+ });
2900
+ }
2262
2901
  const { debugUserCode, truncatedCode } = buildDebugCode(lines, matches);
2263
- if (err instanceof require_errors.VMSignal) {
2902
+ if (require_errors.VMSignal.is(err)) {
2264
2903
  err.stack = debugUserCode;
2265
2904
  err.truncatedCode = truncatedCode;
2266
- err.variables = mapValues(variables, (getter) => require__baseIteratee.isFunction(getter) ? getter() : getter);
2267
- err.toolCall = currentToolCall;
2905
+ err.variables = mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter);
2268
2906
  throw err;
2269
2907
  } else {
2270
2908
  var _matches$, _matches$2;
2271
- traces.push({
2909
+ recordTrace({
2272
2910
  type: "code_execution_exception",
2273
2911
  position: [((_matches$ = matches[0]) === null || _matches$ === void 0 ? void 0 : _matches$.line) ?? 0, ((_matches$2 = matches[0]) === null || _matches$2 === void 0 ? void 0 : _matches$2.column) ?? 0],
2274
2912
  message: err.message,
2275
2913
  stackTrace: debugUserCode,
2276
2914
  started_at: Date.now()
2277
2915
  });
2278
- throw new require_errors.CodeExecutionError(err.message, code, debugUserCode);
2916
+ const originalErrorName = require_errors.CodeExecutionError.is(err) ? err.originalErrorName : err.name;
2917
+ throw new require_errors.CodeExecutionError(err.message, code, debugUserCode, originalErrorName, err);
2279
2918
  }
2280
2919
  };
2281
2920
  const handleCatch = (err, traces, variables, lines_executed) => {
2282
2921
  err = require_errors.Signals.maybeDeserializeError(err);
2283
2922
  return {
2284
- success: err instanceof require_errors.VMSignal ? true : false,
2285
- variables: mapValues(variables, (getter) => require__baseIteratee.isFunction(getter) ? getter() : getter),
2923
+ success: require_errors.VMSignal.is(err) ? true : false,
2924
+ variables: mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter),
2286
2925
  error: err,
2287
- signal: err instanceof require_errors.VMSignal ? err : void 0,
2926
+ signal: require_errors.VMSignal.is(err) ? err : void 0,
2288
2927
  traces,
2289
2928
  lines_executed: Array.from(lines_executed)
2290
2929
  };
@@ -2314,38 +2953,37 @@ function buildDebugCode(lines, matches) {
2314
2953
  } else appendCode(` ${paddedLineNumber} | ${line}\n`);
2315
2954
  }
2316
2955
  return {
2317
- debugUserCode: require_stack_traces.cleanStackTrace(debugUserCode).trim(),
2318
- truncatedCode: require_stack_traces.cleanStackTrace(truncatedCode).trim()
2956
+ debugUserCode: debugUserCode.trim(),
2957
+ truncatedCode: truncatedCode.trim()
2319
2958
  };
2320
2959
  }
2321
- function formatError(err, lines, matches, traces, variables, lines_executed, currentToolCall, code) {
2960
+ function formatError(err, lines, matches, traces, variables, lines_executed, code, recordTrace) {
2322
2961
  const { debugUserCode, truncatedCode } = buildDebugCode(lines, matches);
2323
- if (err instanceof require_errors.VMSignal) {
2324
- const signalError = err;
2325
- signalError.stack = debugUserCode;
2326
- signalError.truncatedCode = truncatedCode;
2327
- signalError.variables = mapValues(variables, (getter) => require__baseIteratee.isFunction(getter) ? getter() : getter);
2328
- signalError.toolCall = currentToolCall;
2962
+ if (require_errors.VMSignal.is(err)) {
2963
+ err.stack = debugUserCode;
2964
+ err.truncatedCode = truncatedCode;
2965
+ err.variables = mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter);
2329
2966
  return {
2330
2967
  success: true,
2331
- variables: mapValues(variables, (getter) => require__baseIteratee.isFunction(getter) ? getter() : getter),
2968
+ variables: mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter),
2332
2969
  signal: err,
2333
2970
  lines_executed: Array.from(lines_executed)
2334
2971
  };
2335
2972
  } else {
2336
2973
  var _matches$3, _matches$4;
2337
- traces.push({
2974
+ recordTrace({
2338
2975
  type: "code_execution_exception",
2339
2976
  position: [((_matches$3 = matches[0]) === null || _matches$3 === void 0 ? void 0 : _matches$3.line) ?? 0, ((_matches$4 = matches[0]) === null || _matches$4 === void 0 ? void 0 : _matches$4.column) ?? 0],
2340
2977
  message: err.message,
2341
2978
  stackTrace: debugUserCode,
2342
2979
  started_at: Date.now()
2343
2980
  });
2344
- const codeError = new require_errors.CodeExecutionError(err.message, code, debugUserCode);
2981
+ const originalErrorName = require_errors.CodeExecutionError.is(err) ? err.originalErrorName : err.name;
2982
+ const codeError = new require_errors.CodeExecutionError(err.message, code, debugUserCode, originalErrorName, err);
2345
2983
  const deserializedError = require_errors.Signals.maybeDeserializeError(codeError);
2346
2984
  return {
2347
2985
  success: false,
2348
- variables: mapValues(variables, (getter) => require__baseIteratee.isFunction(getter) ? getter() : getter),
2986
+ variables: mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter),
2349
2987
  error: deserializedError,
2350
2988
  traces,
2351
2989
  lines_executed: Array.from(lines_executed)
@@ -2353,62 +2991,88 @@ function formatError(err, lines, matches, traces, variables, lines_executed, cur
2353
2991
  }
2354
2992
  }
2355
2993
  //#endregion
2994
+ //#region src/vm/types.ts
2995
+ /** Host-only lifecycle hook; symbols are not copied into the generated program's globals. */
2996
+ const VM_PROGRAM_COMPLETE = Symbol("llmz.programComplete");
2997
+ const VM_TERMINATION = Symbol("llmz.termination");
2998
+ const VM_CALL_SITE = Symbol("llmz.callSite");
2999
+ const VM_ON_ERROR = Symbol("llmz.onError");
3000
+ //#endregion
2356
3001
  //#region src/vm/instrument.ts
2357
3002
  const USER_CODE_MARKER_TAG_START = "__LLMZ_USER_CODE_START__";
2358
3003
  const USER_CODE_MARKER_TAG_END = "__LLMZ_USER_CODE_END__";
2359
3004
  const NO_TRACKING = [
2360
- require_compiler.Identifiers.CommentFnIdentifier,
2361
- require_compiler.Identifiers.ToolCallTrackerFnIdentifier,
2362
- require_compiler.Identifiers.ToolTrackerRetIdentifier,
2363
- require_compiler.Identifiers.VariableTrackingFnIdentifier,
2364
- require_compiler.Identifiers.ConsoleObjIdentifier
3005
+ Identifiers.CommentFnIdentifier,
3006
+ Identifiers.VariableTrackingFnIdentifier,
3007
+ Identifiers.ConsoleObjIdentifier,
3008
+ TerminationCheckpointIdentifier,
3009
+ TerminationGuardIdentifier
2365
3010
  ];
2366
- function instrumentContext(context, transformed, traces, variables, lines_executed, consumer, userCodeStartLine) {
2367
- const state = { currentToolCall: void 0 };
2368
- context[require_compiler.Identifiers.CommentFnIdentifier] = (comment, line) => {
3011
+ function instrumentContext(context, transformed, recordTrace, variables, lines_executed, consumer, userCodeStartLine, memoryNames = []) {
3012
+ const state = {
3013
+ lastExecutedLine: void 0,
3014
+ memoryNames: /* @__PURE__ */ new Set([...memoryNames, ...transformed.variables]),
3015
+ variableWrites: [],
3016
+ captureErrors: []
3017
+ };
3018
+ context[MissingToolIdentifier] = (name) => {
3019
+ var _context$VM_ON_ERROR;
3020
+ const error = new require_errors.UnknownToolError(name, Object.keys(context).filter((key) => !key.startsWith("__") && typeof context[key] === "function"));
3021
+ (_context$VM_ON_ERROR = context[VM_ON_ERROR]) === null || _context$VM_ON_ERROR === void 0 || _context$VM_ON_ERROR.call(context, error);
3022
+ throw error;
3023
+ };
3024
+ context[TerminationGuardIdentifier] = () => {
3025
+ var _context$VM_TERMINATI;
3026
+ return (_context$VM_TERMINATI = context[VM_TERMINATION]) === null || _context$VM_TERMINATI === void 0 ? void 0 : _context$VM_TERMINATI.check();
3027
+ };
3028
+ context[TerminationCheckpointIdentifier] = (value) => {
3029
+ var _context$VM_TERMINATI2;
3030
+ if (value instanceof Promise) Promise.prototype.then.call(value, void 0, () => {});
3031
+ (_context$VM_TERMINATI2 = context[VM_TERMINATION]) === null || _context$VM_TERMINATI2 === void 0 || _context$VM_TERMINATI2.check();
3032
+ return value;
3033
+ };
3034
+ context[Identifiers.CommentFnIdentifier] = (comment, line) => {
2369
3035
  if (comment.includes(USER_CODE_MARKER_TAG_START) || comment.includes(USER_CODE_MARKER_TAG_END)) return;
2370
- traces.push({
3036
+ recordTrace({
2371
3037
  type: "comment",
2372
3038
  comment,
2373
3039
  line,
2374
3040
  started_at: Date.now()
2375
3041
  });
2376
3042
  };
2377
- context[require_compiler.Identifiers.LineTrackingFnIdentifier] = (line) => {
3043
+ context[Identifiers.LineTrackingFnIdentifier] = (line) => {
2378
3044
  const mappedLine = consumer.originalPositionFor({
2379
3045
  line,
2380
3046
  column: 0
2381
3047
  }).line ?? line;
2382
3048
  const userCodeLine = Math.max(1, mappedLine - userCodeStartLine);
3049
+ state.lastExecutedLine = userCodeLine;
2383
3050
  lines_executed.set(userCodeLine, (lines_executed.get(userCodeLine) ?? 0) + 1);
2384
3051
  };
2385
- context[require_compiler.Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
2386
- if (NO_TRACKING.includes(name)) return;
3052
+ context[Identifiers.VariableTrackingFnIdentifier] = (name, getter, result, kind = "assignment") => {
3053
+ if (NO_TRACKING.includes(name) || !state.memoryNames.has(name)) return result;
3054
+ if (kind !== "initialize" && kind !== "read") state.variableWrites.push({
3055
+ name,
3056
+ timestamp: Date.now(),
3057
+ kind
3058
+ });
2387
3059
  variables[name] = () => {
2388
3060
  try {
2389
- const value = getter();
2390
- if (typeof value === "function") return "[[non-primitive]]";
2391
- return value;
2392
- } catch {
2393
- return "[[non-primitive]]";
3061
+ return getter();
3062
+ } catch (err) {
3063
+ if (!state.captureErrors.some((entry) => entry.name === name)) state.captureErrors.push({
3064
+ name,
3065
+ reason: err instanceof Error ? err.message : String(err)
3066
+ });
3067
+ return;
2394
3068
  }
2395
3069
  };
3070
+ return result;
2396
3071
  };
2397
- context[require_compiler.Identifiers.ToolCallTrackerFnIdentifier] = (callId, type, outputOrError) => {
2398
- const temp = require_errors.Signals.maybeDeserializeError(outputOrError === null || outputOrError === void 0 ? void 0 : outputOrError.message);
2399
- if (type === "end" && temp instanceof require_errors.SnapshotSignal && (temp === null || temp === void 0 ? void 0 : temp.toolCall)) {
2400
- var _transformed$toolCall;
2401
- state.currentToolCall = {
2402
- ...temp.toolCall,
2403
- assignment: (_transformed$toolCall = transformed.toolCalls.get(callId)) === null || _transformed$toolCall === void 0 ? void 0 : _transformed$toolCall.assignment
2404
- };
2405
- }
2406
- };
2407
- context[require_compiler.Identifiers.ConsoleObjIdentifier] = { log: (...args) => {
2408
- const message = args.shift();
2409
- traces.push({
3072
+ context[Identifiers.ConsoleObjIdentifier] = { log: (...args) => {
3073
+ recordTrace({
2410
3074
  type: "log",
2411
- message,
3075
+ message: args.shift(),
2412
3076
  args,
2413
3077
  started_at: Date.now()
2414
3078
  });
@@ -2423,14 +3087,54 @@ function findUserCodeStartLine(transformed) {
2423
3087
  }
2424
3088
  return -1;
2425
3089
  }
3090
+ /** Drop unsupported captures explicitly instead of presenting lossy placeholders as data. */
3091
+ function finalizeMemoryCapture(result, state) {
3092
+ for (const [name, value] of Object.entries(result.variables)) try {
3093
+ result.variables[name] = require_quickjs_variant.cloneMemoryValue(value);
3094
+ } catch (err) {
3095
+ if (!state.captureErrors.some((entry) => entry.name === name)) state.captureErrors.push({
3096
+ name,
3097
+ reason: err instanceof Error ? err.message : String(err)
3098
+ });
3099
+ }
3100
+ for (const failure of state.captureErrors) {
3101
+ var _result$signal;
3102
+ delete result.variables[failure.name];
3103
+ if ((_result$signal = result.signal) === null || _result$signal === void 0 ? void 0 : _result$signal.variables) delete result.signal.variables[failure.name];
3104
+ }
3105
+ if (result.success && !result.signal) try {
3106
+ result.return_value = require_quickjs_variant.cloneMemoryValue(result.return_value);
3107
+ } catch (err) {
3108
+ if (!state.captureErrors.some((entry) => entry.name === "$return")) state.captureErrors.push({
3109
+ name: "$return",
3110
+ reason: err instanceof Error ? err.message : String(err)
3111
+ });
3112
+ result.return_value = void 0;
3113
+ }
3114
+ return {
3115
+ ...result,
3116
+ variableWrites: state.variableWrites,
3117
+ captureErrors: state.captureErrors
3118
+ };
3119
+ }
2426
3120
  //#endregion
2427
3121
  //#region src/vm/drivers/node.ts
2428
3122
  var NodeDriver = class {
2429
3123
  async execute(ctx) {
2430
- const { transformed, consumer, context, traces, code, lines_executed, variables } = ctx;
2431
- const state = instrumentContext(context, transformed, traces, variables, lines_executed, consumer, 0);
3124
+ const { transformed, consumer, context, traces, recordTrace, code, lines_executed, variables } = ctx;
3125
+ const state = instrumentContext(context, transformed, recordTrace, variables, lines_executed, consumer, findUserCodeStartLine(transformed), ctx.memoryNames);
3126
+ context[VM_CALL_SITE] = () => {
3127
+ var _Error$stack;
3128
+ const frame = (_Error$stack = (/* @__PURE__ */ new Error()).stack) === null || _Error$stack === void 0 ? void 0 : _Error$stack.match(/<anonymous>:(\d+):(\d+)/);
3129
+ if (!frame) return;
3130
+ const position = consumer.originalPositionFor({
3131
+ line: Number(frame[1]) - 1,
3132
+ column: Number(frame[2])
3133
+ });
3134
+ return position.line ? Math.max(1, position.line - 3) : void 0;
3135
+ };
2432
3136
  const AsyncFunction = async function() {}.constructor;
2433
- return await (async () => {
3137
+ return finalizeMemoryCapture(await (async () => {
2434
3138
  const descriptors = Object.getOwnPropertyDescriptors(context);
2435
3139
  const topLevelProperties = Object.keys(descriptors).filter((x) => !NO_TRACKING.includes(x) && descriptors[x] && typeof descriptors[x].value !== "function" && typeof descriptors[x].value !== "object");
2436
3140
  const __report = (name, value) => {
@@ -2438,21 +3142,59 @@ var NodeDriver = class {
2438
3142
  };
2439
3143
  context.__report = __report;
2440
3144
  const reportAll = topLevelProperties.map((x) => `__report("${x}", ${x})`).join(";");
2441
- const wrapper = `"use strict"; try { ${`let __${require_compiler.Identifiers.LineTrackingFnIdentifier} = ${require_compiler.Identifiers.LineTrackingFnIdentifier}; ${require_compiler.Identifiers.LineTrackingFnIdentifier} = function(line) { ${reportAll}; __${require_compiler.Identifiers.LineTrackingFnIdentifier}(line);}`};${transformed.code} } finally { ${reportAll} };`;
2442
- return await AsyncFunction(...Object.keys(context), wrapper)(...Object.values(context));
3145
+ const assigner = `let __${Identifiers.LineTrackingFnIdentifier} = ${Identifiers.LineTrackingFnIdentifier}; ${Identifiers.LineTrackingFnIdentifier} = function(line) { ${reportAll}; __${Identifiers.LineTrackingFnIdentifier}(line);}`;
3146
+ const trackInputs = ctx.memoryNames.map((name) => `${Identifiers.VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => eval(${JSON.stringify(name)}), undefined, "read");`).join("");
3147
+ const bindings = Object.keys(context);
3148
+ const protectedBindings = bindings.filter((name) => require_quickjs_variant.RESERVED_RUNTIME_NAMES.has(name)).map((name) => `const ${name} = __llmz_binding_${bindings.indexOf(name)};`).join("");
3149
+ const parameters = bindings.map((name, index) => require_quickjs_variant.RESERVED_RUNTIME_NAMES.has(name) ? `__llmz_binding_${index}` : name);
3150
+ const wrapper = `"use strict"; ${protectedBindings} try { ${assigner};${trackInputs}${transformed.code} } finally { ${reportAll} };`;
3151
+ const fn = AsyncFunction(...parameters, wrapper);
3152
+ try {
3153
+ return await fn(...Object.values(context));
3154
+ } finally {
3155
+ var _context$VM_PROGRAM_C;
3156
+ (_context$VM_PROGRAM_C = context[VM_PROGRAM_COMPLETE]) === null || _context$VM_PROGRAM_C === void 0 || _context$VM_PROGRAM_C.call(context);
3157
+ }
2443
3158
  })().then((res) => {
3159
+ var _context$VM_TERMINATI, _context$VM_TERMINATI2, _context$VM_TERMINATI3;
3160
+ const signal = (_context$VM_TERMINATI = context[VM_TERMINATION]) === null || _context$VM_TERMINATI === void 0 || (_context$VM_TERMINATI2 = _context$VM_TERMINATI.getSignal) === null || _context$VM_TERMINATI2 === void 0 ? void 0 : _context$VM_TERMINATI2.call(_context$VM_TERMINATI);
3161
+ if (signal) throw signal;
3162
+ if ((_context$VM_TERMINATI3 = context[VM_TERMINATION]) === null || _context$VM_TERMINATI3 === void 0 ? void 0 : _context$VM_TERMINATI3.isTerminated()) res = void 0;
2444
3163
  res = require_errors.Signals.maybeDeserializeError(res);
2445
3164
  return {
2446
3165
  success: true,
2447
- variables: mapValues(variables, (getter) => require__baseIteratee.isFunction(getter) ? getter() : getter),
2448
- signal: res instanceof require_errors.VMSignal ? res : void 0,
3166
+ variables: mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter),
3167
+ signal: require_errors.VMSignal.is(res) ? res : void 0,
2449
3168
  lines_executed: Array.from(lines_executed),
2450
3169
  return_value: res
2451
3170
  };
2452
- }).catch((err) => handleErrorNode(err, code, consumer, traces, variables, lines_executed, state.currentToolCall)).catch((err) => handleCatch(err, traces, variables, lines_executed));
3171
+ }).catch((err) => {
3172
+ var _context$VM_TERMINATI4, _context$VM_TERMINATI5, _context$VM_TERMINATI6;
3173
+ const signal = (_context$VM_TERMINATI4 = context[VM_TERMINATION]) === null || _context$VM_TERMINATI4 === void 0 || (_context$VM_TERMINATI5 = _context$VM_TERMINATI4.getSignal) === null || _context$VM_TERMINATI5 === void 0 ? void 0 : _context$VM_TERMINATI5.call(_context$VM_TERMINATI4);
3174
+ if (signal) return handleErrorNode(signal, code, consumer, recordTrace, variables, lines_executed, state.lastExecutedLine);
3175
+ if ((_context$VM_TERMINATI6 = context[VM_TERMINATION]) === null || _context$VM_TERMINATI6 === void 0 ? void 0 : _context$VM_TERMINATI6.isTerminated()) return {
3176
+ success: true,
3177
+ variables: mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter),
3178
+ lines_executed: Array.from(lines_executed)
3179
+ };
3180
+ return handleErrorNode(err, code, consumer, recordTrace, variables, lines_executed, state.lastExecutedLine);
3181
+ }).catch((err) => handleCatch(err, traces, variables, lines_executed)), state);
2453
3182
  }
2454
3183
  };
2455
3184
  //#endregion
3185
+ //#region src/vm/member-proxy.ts
3186
+ /** Host-only metadata lets QuickJS install the same missing-member behavior in its own realm. */
3187
+ const MISSING_MEMBER = Symbol("llmz.missingMember");
3188
+ /** Only registered own members are callable; inherited Object methods are not API members. */
3189
+ function withMissingMember(target, missing) {
3190
+ Object.defineProperty(target, MISSING_MEMBER, { value: missing });
3191
+ Object.freeze(target);
3192
+ return new Proxy(target, { get(object, key, receiver) {
3193
+ if (typeof key === "string" && !Object.hasOwn(object, key)) return missing(key);
3194
+ return Reflect.get(object, key, receiver);
3195
+ } });
3196
+ }
3197
+ //#endregion
2456
3198
  //#region src/vm/drivers/quickjs.ts
2457
3199
  let _quickJSModule;
2458
3200
  let _loadedVariant;
@@ -2466,9 +3208,27 @@ const loadQuickJSModule = () => {
2466
3208
  };
2467
3209
  var QuickJSDriver = class {
2468
3210
  async execute(ctx) {
2469
- const { transformed, consumer, context, traces, signal, timeout, code, lines_executed, variables } = ctx;
3211
+ const { transformed, consumer, context, traces, recordTrace, signal, timeout, code, lines_executed, variables } = ctx;
2470
3212
  const userCodeStartLine = findUserCodeStartLine(transformed);
2471
- const state = instrumentContext(context, transformed, traces, variables, lines_executed, consumer, userCodeStartLine);
3213
+ const state = instrumentContext(context, transformed, recordTrace, variables, lines_executed, consumer, userCodeStartLine, ctx.memoryNames);
3214
+ const isTerminated = () => {
3215
+ var _context$VM_TERMINATI;
3216
+ return ((_context$VM_TERMINATI = context[VM_TERMINATION]) === null || _context$VM_TERMINATI === void 0 ? void 0 : _context$VM_TERMINATI.isTerminated()) ?? false;
3217
+ };
3218
+ const shouldStopJobs = () => {
3219
+ var _context$VM_TERMINATI2, _context$VM_TERMINATI3;
3220
+ return isTerminated() && !((_context$VM_TERMINATI2 = context[VM_TERMINATION]) === null || _context$VM_TERMINATI2 === void 0 || (_context$VM_TERMINATI3 = _context$VM_TERMINATI2.getSignal) === null || _context$VM_TERMINATI3 === void 0 ? void 0 : _context$VM_TERMINATI3.call(_context$VM_TERMINATI2));
3221
+ };
3222
+ const terminalResult = () => {
3223
+ var _context$VM_TERMINATI4, _context$VM_TERMINATI5;
3224
+ const interruption = (_context$VM_TERMINATI4 = context[VM_TERMINATION]) === null || _context$VM_TERMINATI4 === void 0 || (_context$VM_TERMINATI5 = _context$VM_TERMINATI4.getSignal) === null || _context$VM_TERMINATI5 === void 0 ? void 0 : _context$VM_TERMINATI5.call(_context$VM_TERMINATI4);
3225
+ if (interruption) return finalizeMemoryCapture(handleErrorQuickJS(interruption, code, consumer, traces, variables, lines_executed, userCodeStartLine, recordTrace), state);
3226
+ return finalizeMemoryCapture({
3227
+ success: true,
3228
+ variables: mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter),
3229
+ lines_executed: Array.from(lines_executed)
3230
+ }, state);
3231
+ };
2472
3232
  const runtime = (await loadQuickJSModule()).newRuntime();
2473
3233
  runtime.setMemoryLimit(134217728);
2474
3234
  const timeoutHandler = (0, quickjs_emscripten_core.shouldInterruptAfterDeadline)(Date.now() + timeout);
@@ -2480,42 +3240,65 @@ var QuickJSDriver = class {
2480
3240
  const trackedProperties = /* @__PURE__ */ new Set();
2481
3241
  const referenceProperties = /* @__PURE__ */ new Set();
2482
3242
  const pendingPromises = [];
2483
- const toVmValue = (value) => {
3243
+ const variableGetters = /* @__PURE__ */ new Map();
3244
+ let captureValue;
3245
+ const objectConstructor = vm.getProp(vm.global, "Object");
3246
+ const freezeFunction = vm.getProp(objectConstructor, "freeze");
3247
+ objectConstructor.dispose();
3248
+ const preserveHostFreeze = (hostValue, handle, preserveFrozen) => {
3249
+ if (!preserveFrozen || !Object.isFrozen(hostValue)) return handle;
3250
+ const frozen = vm.callFunction(freezeFunction, vm.undefined, handle);
3251
+ if ("error" in frozen) {
3252
+ const error = vm.dump(frozen.error);
3253
+ frozen.error.dispose();
3254
+ handle.dispose();
3255
+ throw new Error(error.message);
3256
+ }
3257
+ frozen.value.dispose();
3258
+ return handle;
3259
+ };
3260
+ const toVmValue = (value, preserveFrozen = false) => {
2484
3261
  if (typeof value === "string") return vm.newString(value);
2485
3262
  else if (typeof value === "number") return vm.newNumber(value);
2486
3263
  else if (typeof value === "boolean") return value ? vm.true : vm.false;
2487
3264
  else if (value === null) return vm.null;
2488
3265
  else if (value === void 0) return vm.undefined;
2489
3266
  else if (Array.isArray(value)) {
2490
- const items = value.map((item) => {
2491
- if (typeof item === "string") return JSON.stringify(item);
2492
- else if (typeof item === "number" || typeof item === "boolean") return String(item);
2493
- else if (item === null) return "null";
2494
- else if (item === void 0) return "undefined";
2495
- else if (typeof item === "object") return JSON.stringify(item);
2496
- return "undefined";
3267
+ const array = vm.newArray();
3268
+ value.forEach((item, index) => {
3269
+ const handle = toVmValue(item, preserveFrozen);
3270
+ vm.setProp(array, index, handle);
3271
+ disposeIfNeeded(handle);
2497
3272
  });
2498
- const result = vm.evalCode(`[${items.join(",")}]`);
2499
- if ("error" in result) {
2500
- var _result$error;
2501
- (_result$error = result.error) === null || _result$error === void 0 || _result$error.dispose();
2502
- return vm.undefined;
2503
- }
2504
- return result.value;
3273
+ return preserveHostFreeze(value, array, preserveFrozen);
2505
3274
  } else if (typeof value === "object") {
2506
3275
  const obj = vm.newObject();
2507
3276
  for (const [k, v] of Object.entries(value)) if (typeof v !== "function") {
2508
- const propHandle = toVmValue(v);
3277
+ const propHandle = toVmValue(v, preserveFrozen);
2509
3278
  vm.setProp(obj, k, propHandle);
2510
3279
  disposeIfNeeded(propHandle);
2511
3280
  }
2512
- return obj;
3281
+ return preserveHostFreeze(value, obj, preserveFrozen);
2513
3282
  }
2514
3283
  return vm.undefined;
2515
3284
  };
2516
3285
  const disposeIfNeeded = (handle) => {
2517
3286
  if (handle !== vm.true && handle !== vm.false && handle !== vm.null && handle !== vm.undefined) handle.dispose();
2518
3287
  };
3288
+ context[VM_CALL_SITE] = () => {
3289
+ const stack = vm.evalCode("new Error().stack");
3290
+ if ("error" in stack) {
3291
+ var _stack$error;
3292
+ (_stack$error = stack.error) === null || _stack$error === void 0 || _stack$error.dispose();
3293
+ return;
3294
+ }
3295
+ try {
3296
+ const frame = vm.getString(stack.value).match(/<quickjs>:(\d+)/);
3297
+ return frame ? Math.max(1, Number(frame[1]) - 9 - userCodeStartLine + 1) : void 0;
3298
+ } finally {
3299
+ stack.value.dispose();
3300
+ }
3301
+ };
2519
3302
  const bridgeFunction = (fn, _fnName = "anonymous") => {
2520
3303
  return (...argHandles) => {
2521
3304
  const args = argHandles.map((h) => vm.dump(h));
@@ -2523,36 +3306,94 @@ var QuickJSDriver = class {
2523
3306
  const result = fn(...args);
2524
3307
  if (result && typeof result.then === "function") {
2525
3308
  const promise = vm.newPromise();
3309
+ const hostPromise = Promise.resolve(result).then((value) => require_quickjs_variant.cloneMemoryValue(value));
3310
+ hostPromise.catch(() => {});
2526
3311
  pendingPromises.push({
2527
- hostPromise: result,
3312
+ hostPromise,
2528
3313
  deferredPromise: promise
2529
3314
  });
2530
3315
  promise.settled.then(() => {
2531
- if (runtime.alive) runtime.executePendingJobs();
3316
+ if (runtime.alive && !shouldStopJobs()) runtime.executePendingJobs();
2532
3317
  });
2533
3318
  return promise.handle;
2534
3319
  }
2535
- return toVmValue(result);
3320
+ return toVmValue(require_quickjs_variant.cloneMemoryValue(result));
2536
3321
  } catch (err) {
2537
- const serialized = err instanceof Error ? err.message : String(err);
2538
- throw new Error(serialized);
3322
+ return { error: guestError(vm, err) };
2539
3323
  }
2540
3324
  };
2541
3325
  };
2542
3326
  try {
2543
- bridgeContextToVM(context, vm, trackedProperties, referenceProperties, toVmValue, disposeIfNeeded, bridgeFunction);
2544
- setupVariableTrackingBridge(vm, variables);
3327
+ captureValue = setupMemoryCapture(vm);
3328
+ bridgeContextToVM(context, vm, trackedProperties, referenceProperties, toVmValue, disposeIfNeeded, bridgeFunction, captureValue);
3329
+ setupVariableTrackingBridge(vm, variables, variableGetters, state, captureValue);
3330
+ vm.evalCode(`(() => {
3331
+ const then = Promise.prototype.then;
3332
+ const check = globalThis.${TerminationGuardIdentifier};
3333
+ globalThis.${TerminationCheckpointIdentifier} = (value) => {
3334
+ if (value instanceof Promise) {
3335
+ then.call(value, undefined, () => {});
3336
+ }
3337
+ check();
3338
+ return value;
3339
+ };
3340
+ })()`).unwrap().dispose();
3341
+ const complete = vm.newFunction("__llmz_program_complete", () => {
3342
+ var _context$VM_PROGRAM_C;
3343
+ (_context$VM_PROGRAM_C = context[VM_PROGRAM_COMPLETE]) === null || _context$VM_PROGRAM_C === void 0 || _context$VM_PROGRAM_C.call(context);
3344
+ return vm.undefined;
3345
+ });
3346
+ vm.setProp(vm.global, "__llmz_program_complete", complete);
3347
+ complete.dispose();
3348
+ for (const name of ctx.memoryNames) {
3349
+ const tracked = vm.evalCode(`${Identifiers.VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => globalThis[${JSON.stringify(name)}], undefined, "read");`);
3350
+ if ("error" in tracked) {
3351
+ var _tracked$error;
3352
+ (_tracked$error = tracked.error) === null || _tracked$error === void 0 || _tracked$error.dispose();
3353
+ } else tracked.value.dispose();
3354
+ }
3355
+ const protect = vm.evalCode(`(() => {
3356
+ function freeze(value) {
3357
+ if (value && (typeof value === 'object' || typeof value === 'function') && !Object.isFrozen(value)) {
3358
+ Object.values(value).forEach(freeze);
3359
+ Object.freeze(value);
3360
+ }
3361
+ return value;
3362
+ }
3363
+ for (const name of ${JSON.stringify([
3364
+ ...require_quickjs_variant.RUNTIME_BINDING_NAMES,
3365
+ ...require_quickjs_variant.TERMINATION_BINDING_NAMES,
3366
+ "__llmz_program_complete"
3367
+ ])}) {
3368
+ if (Object.prototype.hasOwnProperty.call(globalThis, name)) {
3369
+ Object.defineProperty(globalThis, name, {
3370
+ value: freeze(globalThis[name]),
3371
+ writable: false,
3372
+ configurable: false,
3373
+ });
3374
+ }
3375
+ }
3376
+ })()`);
3377
+ if ("error" in protect) {
3378
+ const error = vm.dump(protect.error);
3379
+ protect.error.dispose();
3380
+ throw new Error(error.message);
3381
+ }
3382
+ protect.value.dispose();
2545
3383
  const scriptCode = buildScriptCode(transformed.code);
2546
3384
  const copyBackContextFromVM = () => {
2547
3385
  for (const key of trackedProperties) {
2548
3386
  if (referenceProperties.has(key)) continue;
2549
3387
  try {
2550
- const valueResult = vm.evalCode(`globalThis['${key}']`);
2551
- const vmValue = vm.dump(valueResult.unwrap());
2552
- valueResult.unwrap().dispose();
3388
+ const handle = vm.evalCode(`globalThis['${key}']`).unwrap();
2553
3389
  try {
2554
- context[key] = vmValue;
2555
- } catch {}
3390
+ const vmValue = ctx.memoryNames.includes(key) ? captureValue(handle) : vm.dump(handle);
3391
+ try {
3392
+ context[key] = vmValue;
3393
+ } catch {}
3394
+ } finally {
3395
+ handle.dispose();
3396
+ }
2556
3397
  } catch {}
2557
3398
  }
2558
3399
  };
@@ -2566,7 +3407,11 @@ var QuickJSDriver = class {
2566
3407
  throw new Error("Execution failed");
2567
3408
  }
2568
3409
  execResult.value.dispose();
2569
- await this._pumpEventLoop(runtime, vm, pendingPromises, signal, toVmValue, disposeIfNeeded);
3410
+ await this._pumpEventLoop(runtime, vm, pendingPromises, signal, toVmValue, disposeIfNeeded, shouldStopJobs);
3411
+ if (isTerminated()) {
3412
+ copyBackContextFromVM();
3413
+ return terminalResult();
3414
+ }
2570
3415
  const errorResult = vm.evalCode("globalThis.__llmz_error");
2571
3416
  const errorValue = vm.dump(errorResult.unwrap());
2572
3417
  errorResult.unwrap().dispose();
@@ -2583,11 +3428,14 @@ var QuickJSDriver = class {
2583
3428
  const errorStack = vm.dump(errorStackResult.unwrap()) || "";
2584
3429
  errorStackResult.unwrap().dispose();
2585
3430
  const deserializedError = require_errors.Signals.maybeDeserializeError(errorValue);
2586
- if (deserializedError instanceof require_errors.VMSignal) {
3431
+ if (require_errors.VMSignal.is(deserializedError)) {
2587
3432
  deserializedError.stack = errorStack;
2588
3433
  throw deserializedError;
2589
3434
  }
2590
3435
  const error = new Error(errorValue);
3436
+ const errorNameResult = vm.evalCode("globalThis.__llmz_error_name");
3437
+ error.name = vm.dump(errorNameResult.unwrap()) || "Error";
3438
+ errorNameResult.unwrap().dispose();
2591
3439
  error.stack = errorStack;
2592
3440
  throw error;
2593
3441
  }
@@ -2597,23 +3445,35 @@ var QuickJSDriver = class {
2597
3445
  resultSetResult.unwrap().dispose();
2598
3446
  let returnValue = void 0;
2599
3447
  if (resultSet) {
2600
- const resultResult = vm.evalCode("globalThis.__llmz_result");
2601
- returnValue = vm.dump(resultResult.unwrap());
2602
- resultResult.unwrap().dispose();
3448
+ const resultHandle = vm.evalCode("globalThis.__llmz_result").unwrap();
3449
+ try {
3450
+ returnValue = captureValue(resultHandle);
3451
+ } catch (err) {
3452
+ state.captureErrors.push({
3453
+ name: "$return",
3454
+ reason: err instanceof Error ? err.message : String(err)
3455
+ });
3456
+ } finally {
3457
+ resultHandle.dispose();
3458
+ }
2603
3459
  }
2604
3460
  returnValue = require_errors.Signals.maybeDeserializeError(returnValue);
2605
- return {
3461
+ return finalizeMemoryCapture({
2606
3462
  success: true,
2607
- variables: mapValues(variables, (getter) => require__baseIteratee.isFunction(getter) ? getter() : getter),
2608
- signal: returnValue instanceof require_errors.VMSignal ? returnValue : void 0,
3463
+ variables: mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter),
3464
+ signal: require_errors.VMSignal.is(returnValue) ? returnValue : void 0,
2609
3465
  lines_executed: Array.from(lines_executed),
2610
- return_value: returnValue
2611
- };
3466
+ return_value: returnValue,
3467
+ variableWrites: state.variableWrites,
3468
+ captureErrors: state.captureErrors
3469
+ }, state);
2612
3470
  } catch (err) {
3471
+ runtime.setInterruptHandler((0, quickjs_emscripten_core.shouldInterruptAfterDeadline)(Date.now() + 1e3));
3472
+ if (isTerminated()) return terminalResult();
2613
3473
  if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
2614
3474
  const reason = signal.reason;
2615
3475
  const abortError = reason instanceof Error ? reason : new Error(reason ? String(reason) : "Execution was aborted");
2616
- return handleErrorQuickJS(abortError, code, consumer, traces, variables, lines_executed, userCodeStartLine, ctx.currentToolCall ?? state.currentToolCall);
3476
+ return finalizeMemoryCapture(handleErrorQuickJS(abortError, code, consumer, traces, variables, lines_executed, userCodeStartLine, recordTrace), state);
2617
3477
  }
2618
3478
  await Promise.all(pendingPromises.map(async ({ hostPromise, deferredPromise }) => {
2619
3479
  try {
@@ -2628,8 +3488,13 @@ var QuickJSDriver = class {
2628
3488
  errValue.dispose();
2629
3489
  }
2630
3490
  })).catch(() => {});
2631
- return handleErrorQuickJS(err, code, consumer, traces, variables, lines_executed, userCodeStartLine, ctx.currentToolCall ?? state.currentToolCall);
3491
+ return finalizeMemoryCapture(handleErrorQuickJS(err, code, consumer, traces, variables, lines_executed, userCodeStartLine, recordTrace), state);
2632
3492
  } finally {
3493
+ var _context$VM_PROGRAM_C2;
3494
+ (_context$VM_PROGRAM_C2 = context[VM_PROGRAM_COMPLETE]) === null || _context$VM_PROGRAM_C2 === void 0 || _context$VM_PROGRAM_C2.call(context);
3495
+ for (const { deferredPromise } of pendingPromises) deferredPromise.dispose();
3496
+ for (const getter of variableGetters.values()) getter.dispose();
3497
+ freezeFunction.dispose();
2633
3498
  try {
2634
3499
  vm.dispose();
2635
3500
  } catch {}
@@ -2638,16 +3503,17 @@ var QuickJSDriver = class {
2638
3503
  } catch {}
2639
3504
  }
2640
3505
  }
2641
- async _pumpEventLoop(runtime, vm, pendingPromises, signal, toVmValue, disposeIfNeeded) {
3506
+ async _pumpEventLoop(runtime, vm, pendingPromises, signal, toVmValue, disposeIfNeeded, shouldStopJobs) {
2642
3507
  const maxIterations = 1e3;
2643
3508
  let iteration = 0;
2644
3509
  while (iteration < maxIterations) {
3510
+ if (shouldStopJobs()) break;
2645
3511
  let hasJobs = false;
2646
3512
  const maxJobs = 1e4;
2647
3513
  for (let i = 0; i < maxJobs; i++) {
2648
3514
  var _runtime$executePendi;
2649
3515
  const pending = (_runtime$executePendi = runtime.executePendingJobs) === null || _runtime$executePendi === void 0 ? void 0 : _runtime$executePendi.call(runtime, -1);
2650
- if ((pending === void 0 ? 0 : pending.unwrap()) <= 0) break;
3516
+ if ((pending === void 0 ? 0 : pending.unwrap()) <= 0 || shouldStopJobs()) break;
2651
3517
  hasJobs = true;
2652
3518
  }
2653
3519
  const currentPromises = [...pendingPromises];
@@ -2655,7 +3521,7 @@ var QuickJSDriver = class {
2655
3521
  if (currentPromises.length > 0) {
2656
3522
  if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
2657
3523
  const reason = signal.reason;
2658
- const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3524
+ const abortMessage = describeAbortReason(reason);
2659
3525
  for (const { deferredPromise } of currentPromises) {
2660
3526
  const errValue = vm.newString(abortMessage);
2661
3527
  deferredPromise.reject(errValue);
@@ -2668,7 +3534,7 @@ var QuickJSDriver = class {
2668
3534
  if (signal) {
2669
3535
  abortListener = () => {
2670
3536
  const reason = signal.reason;
2671
- const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3537
+ const abortMessage = describeAbortReason(reason);
2672
3538
  for (const { deferredPromise } of currentPromises) {
2673
3539
  const errValue = vm.newString(abortMessage);
2674
3540
  deferredPromise.reject(errValue);
@@ -2680,17 +3546,18 @@ var QuickJSDriver = class {
2680
3546
  }
2681
3547
  try {
2682
3548
  await Promise.all(currentPromises.map(async ({ hostPromise, deferredPromise }) => {
2683
- if (signal === null || signal === void 0 ? void 0 : signal.aborted) return;
3549
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || shouldStopJobs()) return;
2684
3550
  try {
2685
3551
  const value = await hostPromise;
2686
- if (signal === null || signal === void 0 ? void 0 : signal.aborted) return;
3552
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || shouldStopJobs()) return;
2687
3553
  const vmValue = toVmValue(value);
2688
3554
  deferredPromise.resolve(vmValue);
2689
3555
  disposeIfNeeded(vmValue);
2690
3556
  } catch (err) {
2691
- if (signal === null || signal === void 0 ? void 0 : signal.aborted) return;
2692
- const serialized = err instanceof Error ? err.message : String(err);
2693
- const createErrorResult = vm.evalCode(`new Error(${JSON.stringify(serialized)})`);
3557
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || shouldStopJobs()) return;
3558
+ const message = err instanceof Error ? err.message : String(err);
3559
+ const serialized = err instanceof Error ? require_errors.Signals.serializeError(err) : message;
3560
+ const createErrorResult = vm.evalCode(`Object.assign(new Error(${JSON.stringify(message)}), { __llmz_error: ${JSON.stringify(serialized)} })`);
2694
3561
  if ("error" in createErrorResult) {
2695
3562
  const errValue = vm.newString(serialized);
2696
3563
  deferredPromise.reject(errValue);
@@ -2704,9 +3571,10 @@ var QuickJSDriver = class {
2704
3571
  }));
2705
3572
  } finally {
2706
3573
  if (signal && abortListener) signal.removeEventListener("abort", abortListener);
3574
+ if (shouldStopJobs()) currentPromises.forEach(({ deferredPromise }) => deferredPromise.dispose());
2707
3575
  }
2708
- runtime.executePendingJobs();
2709
- if (signal === null || signal === void 0 ? void 0 : signal.aborted) break;
3576
+ if (!shouldStopJobs()) runtime.executePendingJobs();
3577
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || shouldStopJobs()) break;
2710
3578
  }
2711
3579
  if (!hasJobs && pendingPromises.length === 0) break;
2712
3580
  iteration++;
@@ -2714,13 +3582,13 @@ var QuickJSDriver = class {
2714
3582
  if (iteration >= maxIterations) throw new Error("Maximum event loop iterations exceeded");
2715
3583
  }
2716
3584
  };
2717
- function bridgeContextToVM(context, vm, trackedProperties, referenceProperties, toVmValue, disposeIfNeeded, bridgeFunction) {
3585
+ function bridgeContextToVM(context, vm, trackedProperties, referenceProperties, toVmValue, disposeIfNeeded, bridgeFunction, captureValue) {
2718
3586
  for (const [key, value] of Object.entries(context)) {
2719
3587
  const descriptor = Object.getOwnPropertyDescriptor(context, key);
2720
3588
  if (descriptor && (descriptor.get || descriptor.set)) {
2721
3589
  referenceProperties.add(key);
2722
3590
  trackedProperties.add(key);
2723
- bridgeGetterSetter(vm, key, void 0, descriptor, context, toVmValue);
3591
+ bridgeGetterSetter(vm, key, void 0, descriptor, context, toVmValue, captureValue);
2724
3592
  continue;
2725
3593
  }
2726
3594
  if (typeof value === "function") {
@@ -2757,18 +3625,25 @@ function bridgeContextToVM(context, vm, trackedProperties, referenceProperties,
2757
3625
  }
2758
3626
  vm.setProp(vm.global, key, objHandle);
2759
3627
  objHandle.dispose();
2760
- for (const { prop, descriptor } of getterSetterProps) bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue);
3628
+ for (const { prop, descriptor } of getterSetterProps) bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue, captureValue);
3629
+ const missing = value[MISSING_MEMBER];
3630
+ if (missing) {
3631
+ trackedProperties.delete(key);
3632
+ installMemberProxy(vm, key, bridgeFunction(missing));
3633
+ }
2761
3634
  if (Object.isSealed(value)) {
2762
- var _sealResult$error;
2763
3635
  const sealResult = vm.evalCode(`Object.seal(globalThis['${key}']);`);
2764
- if ("error" in sealResult) (_sealResult$error = sealResult.error) === null || _sealResult$error === void 0 || _sealResult$error.dispose();
2765
- else sealResult.value.dispose();
3636
+ if ("error" in sealResult) {
3637
+ var _sealResult$error;
3638
+ (_sealResult$error = sealResult.error) === null || _sealResult$error === void 0 || _sealResult$error.dispose();
3639
+ } else sealResult.value.dispose();
2766
3640
  }
2767
3641
  if (!Object.isExtensible(value)) {
2768
- var _preventResult$error;
2769
3642
  const preventResult = vm.evalCode(`Object.preventExtensions(globalThis['${key}']);`);
2770
- if ("error" in preventResult) (_preventResult$error = preventResult.error) === null || _preventResult$error === void 0 || _preventResult$error.dispose();
2771
- else preventResult.value.dispose();
3643
+ if ("error" in preventResult) {
3644
+ var _preventResult$error;
3645
+ (_preventResult$error = preventResult.error) === null || _preventResult$error === void 0 || _preventResult$error.dispose();
3646
+ } else preventResult.value.dispose();
2772
3647
  }
2773
3648
  } else {
2774
3649
  trackedProperties.add(key);
@@ -2778,8 +3653,43 @@ function bridgeContextToVM(context, vm, trackedProperties, referenceProperties,
2778
3653
  }
2779
3654
  }
2780
3655
  }
2781
- function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue) {
2782
- var _result$error2;
3656
+ function installMemberProxy(vm, key, missing) {
3657
+ const factory = vm.evalCode("(function(target, missing) { return new Proxy(target, { get(object, key, receiver) { if (typeof key === \"string\" && !Object.prototype.hasOwnProperty.call(object, key)) { return missing(key); } return Reflect.get(object, key, receiver); } }); })");
3658
+ if ("error" in factory) {
3659
+ var _factory$error;
3660
+ (_factory$error = factory.error) === null || _factory$error === void 0 || _factory$error.dispose();
3661
+ throw new Error("Could not create the API member proxy.");
3662
+ }
3663
+ const missingHandle = vm.newFunction("missingMember", missing);
3664
+ const target = vm.getProp(vm.global, key);
3665
+ try {
3666
+ const result = vm.callFunction(factory.value, vm.undefined, target, missingHandle);
3667
+ if ("error" in result) {
3668
+ var _result$error;
3669
+ (_result$error = result.error) === null || _result$error === void 0 || _result$error.dispose();
3670
+ throw new Error("Could not install the API member proxy.");
3671
+ }
3672
+ vm.setProp(vm.global, key, result.value);
3673
+ result.value.dispose();
3674
+ } finally {
3675
+ target.dispose();
3676
+ factory.value.dispose();
3677
+ missingHandle.dispose();
3678
+ }
3679
+ }
3680
+ /** Preserve readable guest messages and host error types without serializing Error as a string. */
3681
+ function guestError(vm, cause) {
3682
+ const error = cause instanceof Error ? cause : new Error(String(cause));
3683
+ const handle = vm.newError({
3684
+ name: error.name,
3685
+ message: error.message
3686
+ });
3687
+ const details = vm.newString(require_errors.Signals.serializeError(error));
3688
+ vm.setProp(handle, "__llmz_error", details);
3689
+ details.dispose();
3690
+ return handle;
3691
+ }
3692
+ function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue, captureValue) {
2783
3693
  const target = prop ? `${key}` : "globalThis";
2784
3694
  const propName = prop ?? key;
2785
3695
  const prefix = prop ? `${key}_${prop}` : key;
@@ -2787,9 +3697,9 @@ function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue) {
2787
3697
  if (descriptor.get) {
2788
3698
  const getterBridge = vm.newFunction(`get_${propName}`, () => {
2789
3699
  try {
2790
- return toVmValue(prop ? context[key][prop] : context[key]);
3700
+ return toVmValue(prop ? context[key][prop] : context[key], true);
2791
3701
  } catch (err) {
2792
- throw new Error(err instanceof Error ? err.message : String(err));
3702
+ return { error: guestError(vm, err) };
2793
3703
  }
2794
3704
  });
2795
3705
  const getterName = `__getter_${prefix}__`;
@@ -2801,12 +3711,12 @@ function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue) {
2801
3711
  if (descriptor.set) {
2802
3712
  const setterBridge = vm.newFunction(`set_${propName}`, (valueHandle) => {
2803
3713
  try {
2804
- const jsValue = vm.dump(valueHandle);
3714
+ const jsValue = captureValue(valueHandle);
2805
3715
  if (prop) context[key][prop] = jsValue;
2806
3716
  else context[key] = jsValue;
2807
3717
  return vm.undefined;
2808
3718
  } catch (err) {
2809
- throw new Error(err instanceof Error ? err.message : String(err));
3719
+ return { error: guestError(vm, err) };
2810
3720
  }
2811
3721
  });
2812
3722
  const setterName = `__setter_${prefix}__`;
@@ -2823,31 +3733,131 @@ function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue) {
2823
3733
  });
2824
3734
  `;
2825
3735
  const result = vm.evalCode(definePropertyCode);
2826
- if ("error" in result) (_result$error2 = result.error) === null || _result$error2 === void 0 || _result$error2.dispose();
2827
- else result.value.dispose();
3736
+ if ("error" in result) {
3737
+ var _result$error2;
3738
+ (_result$error2 = result.error) === null || _result$error2 === void 0 || _result$error2.dispose();
3739
+ } else result.value.dispose();
2828
3740
  }
2829
- function setupVariableTrackingBridge(vm, variables) {
2830
- const varTrackFnHandle = vm.newFunction(require_compiler.Identifiers.VariableTrackingFnIdentifier, (nameHandle, getterHandle) => {
2831
- const name = vm.getString(nameHandle);
2832
- if (NO_TRACKING.includes(name)) return;
3741
+ function setupMemoryCapture(vm) {
3742
+ const installed = vm.evalCode(`
3743
+ globalThis.__llmz_encode_memory = function encode(value, seen = new Set()) {
3744
+ if (value === undefined) {
3745
+ return ['undefined'];
3746
+ }
3747
+ if (Object.is(value, -0)) {
3748
+ return ['negative-zero'];
3749
+ }
3750
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') {
3751
+ return ['value', value];
3752
+ }
3753
+ if (typeof value === 'number' && Number.isFinite(value)) {
3754
+ return ['value', value];
3755
+ }
3756
+ if (!value || typeof value !== 'object') {
3757
+ throw new Error('Unsupported memory value: ' + typeof value);
3758
+ }
3759
+ if (seen.has(value)) {
3760
+ throw new Error('Cyclic values cannot be retained in memory');
3761
+ }
3762
+ const plainObject = Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null;
3763
+ if (!Array.isArray(value) && !plainObject) {
3764
+ throw new Error('Only plain objects and arrays can be retained in memory');
3765
+ }
3766
+ if (Object.getOwnPropertySymbols(value).length) {
3767
+ throw new Error('Symbol properties cannot be retained in memory');
3768
+ }
3769
+ seen.add(value);
3770
+ try {
3771
+ if (Array.isArray(value)) {
3772
+ if (Object.keys(value).length !== value.length) {
3773
+ throw new Error('Sparse arrays and custom array properties are unsupported');
3774
+ }
3775
+ const items = [];
3776
+ for (let index = 0; index < value.length; index++) {
3777
+ const descriptor = Object.getOwnPropertyDescriptor(value, index);
3778
+ if (!descriptor || descriptor.get || descriptor.set) {
3779
+ throw new Error('Array accessor properties cannot be retained in memory');
3780
+ }
3781
+ items.push(encode(descriptor.value, seen));
3782
+ }
3783
+ return ['array', items];
3784
+ }
3785
+ const entries = [];
3786
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
3787
+ if (descriptor.get || descriptor.set || !descriptor.enumerable) {
3788
+ throw new Error('Accessor and non-enumerable properties cannot be retained in memory');
3789
+ }
3790
+ entries.push([key, encode(descriptor.value, seen)]);
3791
+ }
3792
+ return ['object', entries];
3793
+ } finally {
3794
+ seen.delete(value);
3795
+ }
3796
+ };
3797
+ `);
3798
+ if ("error" in installed) {
3799
+ const error = vm.dump(installed.error);
3800
+ installed.error.dispose();
3801
+ throw new Error(error.message);
3802
+ }
3803
+ installed.value.dispose();
3804
+ return (handle) => {
3805
+ const encoder = vm.getProp(vm.global, "__llmz_encode_memory");
2833
3806
  try {
2834
- const valueResult = vm.callFunction(getterHandle, vm.undefined);
2835
- if ("error" in valueResult) {
2836
- var _valueResult$error;
2837
- variables[name] = "[[non-primitive]]";
2838
- (_valueResult$error = valueResult.error) === null || _valueResult$error === void 0 || _valueResult$error.dispose();
2839
- return;
3807
+ const encoded = vm.callFunction(encoder, vm.undefined, handle);
3808
+ if ("error" in encoded) {
3809
+ const error = vm.dump(encoded.error);
3810
+ encoded.error.dispose();
3811
+ throw new Error(error.message);
2840
3812
  }
2841
- const value = vm.dump(valueResult.value);
2842
- valueResult.value.dispose();
2843
- if (typeof value === "function" || typeof value === "string" && value.includes("=>")) variables[name] = "[[non-primitive]]";
2844
- else variables[name] = value;
2845
- } catch {
2846
- variables[name] = "[[non-primitive]]";
3813
+ try {
3814
+ return require_quickjs_variant.decodeMemoryValue(vm.dump(encoded.value));
3815
+ } finally {
3816
+ encoded.value.dispose();
3817
+ }
3818
+ } finally {
3819
+ encoder.dispose();
2847
3820
  }
3821
+ };
3822
+ }
3823
+ function setupVariableTrackingBridge(vm, variables, getters, state, capture) {
3824
+ const tracker = vm.newFunction(Identifiers.VariableTrackingFnIdentifier, (nameHandle, getterHandle, resultHandle, kindHandle) => {
3825
+ var _getters$get;
3826
+ const name = vm.getString(nameHandle);
3827
+ if (NO_TRACKING.includes(name) || !state.memoryNames.has(name)) return (resultHandle === null || resultHandle === void 0 ? void 0 : resultHandle.dup()) ?? vm.undefined;
3828
+ const kind = kindHandle ? vm.dump(kindHandle) : "assignment";
3829
+ if (kind !== "initialize" && kind !== "read") state.variableWrites.push({
3830
+ name,
3831
+ timestamp: Date.now(),
3832
+ kind: kind === "mutation" ? "mutation" : "assignment"
3833
+ });
3834
+ (_getters$get = getters.get(name)) === null || _getters$get === void 0 || _getters$get.dispose();
3835
+ getters.set(name, getterHandle.dup());
3836
+ variables[name] = () => {
3837
+ try {
3838
+ const result = vm.callFunction(getters.get(name), vm.undefined);
3839
+ if ("error" in result) {
3840
+ const error = vm.dump(result.error);
3841
+ result.error.dispose();
3842
+ throw new Error(error.message);
3843
+ }
3844
+ try {
3845
+ return capture(result.value);
3846
+ } finally {
3847
+ result.value.dispose();
3848
+ }
3849
+ } catch (err) {
3850
+ if (!state.captureErrors.some((entry) => entry.name === name)) state.captureErrors.push({
3851
+ name,
3852
+ reason: err instanceof Error ? err.message : String(err)
3853
+ });
3854
+ return;
3855
+ }
3856
+ };
3857
+ return (resultHandle === null || resultHandle === void 0 ? void 0 : resultHandle.dup()) ?? vm.undefined;
2848
3858
  });
2849
- vm.setProp(vm.global, require_compiler.Identifiers.VariableTrackingFnIdentifier, varTrackFnHandle);
2850
- varTrackFnHandle.dispose();
3859
+ vm.setProp(vm.global, Identifiers.VariableTrackingFnIdentifier, tracker);
3860
+ tracker.dispose();
2851
3861
  }
2852
3862
  function buildScriptCode(transformedCode) {
2853
3863
  return `
@@ -2866,12 +3876,19 @@ ${transformedCode}
2866
3876
  globalThis.__llmz_result = await __fn__();
2867
3877
  globalThis.__llmz_result_set = true;
2868
3878
  } catch (err) {
2869
- globalThis.__llmz_error = typeof err === 'string' ? err : String(err.message || err || '');
3879
+ globalThis.__llmz_error = typeof err === 'string' ? err : String(err.__llmz_error || err.message || err || '');
3880
+ globalThis.__llmz_error_name = typeof err?.name === 'string' ? err.name : 'Error';
2870
3881
  globalThis.__llmz_error_stack = '' + (err.stack || '');
3882
+ } finally {
3883
+ __llmz_program_complete();
2871
3884
  }
2872
3885
  })();
2873
3886
  `.trim();
2874
3887
  }
3888
+ function describeAbortReason(reason) {
3889
+ if (reason instanceof Error) return `${reason.name}: ${reason.message}`;
3890
+ return reason ? String(reason) : "Execution was aborted";
3891
+ }
2875
3892
  //#endregion
2876
3893
  //#region src/vm/index.ts
2877
3894
  const MAX_VM_EXECUTION_TIME = 6e4;
@@ -2883,27 +3900,20 @@ const isWorkerd = () => {
2883
3900
  var _navigator;
2884
3901
  return typeof navigator !== "undefined" && ((_navigator = navigator) === null || _navigator === void 0 ? void 0 : _navigator.userAgent) === "Cloudflare-Workers";
2885
3902
  };
2886
- /**
2887
- * Pre-warms the VM so the first execution doesn't pay the QuickJS WASM
2888
- * instantiation cost. Fire-and-forget: called as soon as the model starts
2889
- * writing a `■run` block, so the module loads while the code is still being
2890
- * generated. No-op when the QuickJS driver is disabled or already loaded.
2891
- */
2892
- const warmupVM = () => {
2893
- if (useQuickJS()) loadQuickJSModule().catch(() => {});
2894
- };
2895
- async function runAsyncFunction(context, code, traces = [], signal = null, timeout = MAX_VM_EXECUTION_TIME) {
3903
+ async function runAsyncFunction(context, code, traces = [], signal = null, timeout = MAX_VM_EXECUTION_TIME, memoryNames, recordTrace = (trace) => {
3904
+ traces.push(trace);
3905
+ }) {
2896
3906
  const transformed = (() => {
2897
3907
  try {
2898
- return require_compiler.compile(code);
3908
+ return compile(code);
2899
3909
  } catch (err) {
2900
- traces.push({
3910
+ recordTrace({
2901
3911
  type: "invalid_code_exception",
2902
3912
  message: (err === null || err === void 0 ? void 0 : err.message) ?? "Unknown error",
2903
3913
  code,
2904
3914
  started_at: Date.now()
2905
3915
  });
2906
- throw new require_errors.InvalidCodeError(err.message, code);
3916
+ throw require_errors.isLLMzError(err) ? err : new require_errors.InvalidCodeError(err.message, code, { cause: err });
2907
3917
  }
2908
3918
  })();
2909
3919
  const lines_executed = /* @__PURE__ */ new Map();
@@ -2917,22 +3927,21 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
2917
3927
  file: transformed.map.file
2918
3928
  });
2919
3929
  context ??= {};
3930
+ memoryNames ??= Object.keys(context).filter((name) => {
3931
+ if (name.startsWith("__") || require_quickjs_variant.RESERVED_RUNTIME_NAMES.has(name)) return false;
3932
+ try {
3933
+ require_quickjs_variant.cloneMemoryValue(context[name]);
3934
+ return true;
3935
+ } catch {
3936
+ return false;
3937
+ }
3938
+ });
3939
+ memoryNames = memoryNames.filter((name) => !transformed.variables.has(name) && !require_quickjs_variant.RESERVED_RUNTIME_NAMES.has(name) && !name.startsWith("__"));
2920
3940
  for (const name of Array.from(transformed.variables)) delete context[name];
2921
- let driver;
3941
+ let driver = new NodeDriver();
2922
3942
  if (useQuickJS()) try {
3943
+ await loadQuickJSModule();
2923
3944
  driver = new QuickJSDriver();
2924
- return await driver.execute({
2925
- transformed,
2926
- consumer,
2927
- context,
2928
- traces,
2929
- signal,
2930
- timeout,
2931
- code,
2932
- lines_executed,
2933
- variables,
2934
- currentToolCall: void 0
2935
- });
2936
3945
  } catch (quickjsError) {
2937
3946
  const variant = require_quickjs_variant.getQuickJSVariant();
2938
3947
  const debugInfo = {
@@ -2949,7 +3958,7 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
2949
3958
  console.error("QuickJS failed to load and the node driver is unavailable on Cloudflare Workers.");
2950
3959
  console.error("Debug info:", JSON.stringify(debugInfo, null, 2));
2951
3960
  if (quickjsError instanceof Error) {
2952
- quickjsError.debugInfo = debugInfo;
3961
+ Object.assign(quickjsError, { debugInfo });
2953
3962
  throw quickjsError;
2954
3963
  }
2955
3964
  throw new Error(`QuickJS failed to load on Cloudflare Workers: ${debugInfo.error}`);
@@ -2958,20 +3967,25 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
2958
3967
  console.warn("Error:", (quickjsError === null || quickjsError === void 0 ? void 0 : quickjsError.message) || quickjsError);
2959
3968
  console.warn("Debug info:", JSON.stringify(debugInfo, null, 2));
2960
3969
  }
2961
- driver = new NodeDriver();
2962
3970
  return await driver.execute({
2963
3971
  transformed,
3972
+ memoryNames,
2964
3973
  consumer,
2965
3974
  context,
2966
3975
  traces,
3976
+ recordTrace,
2967
3977
  signal,
2968
3978
  timeout,
2969
3979
  code,
2970
3980
  lines_executed,
2971
- variables,
2972
- currentToolCall: void 0
3981
+ variables
2973
3982
  });
2974
3983
  }
2975
3984
  //#endregion
3985
+ exports.VM_CALL_SITE = VM_CALL_SITE;
3986
+ exports.VM_ON_ERROR = VM_ON_ERROR;
3987
+ exports.VM_PROGRAM_COMPLETE = VM_PROGRAM_COMPLETE;
3988
+ exports.VM_TERMINATION = VM_TERMINATION;
3989
+ exports.compile = compile;
2976
3990
  exports.runAsyncFunction = runAsyncFunction;
2977
- exports.warmupVM = warmupVM;
3991
+ exports.withMissingMember = withMissingMember;