llmz 0.9.0 → 1.0.1

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 (231) hide show
  1. package/DOCS.md +230 -1796
  2. package/ERRORS.md +98 -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-BpMVZYOa.cjs +649 -0
  16. package/dist/component-C27qu6Zv.js +614 -0
  17. package/dist/context.d.ts +70 -377
  18. package/dist/custom-client-BDkgBR2w.js +1631 -0
  19. package/dist/custom-client-MytucGI-.cjs +1708 -0
  20. package/dist/custom-client.d.ts +12 -2
  21. package/dist/errors/catalog.d.ts +287 -0
  22. package/dist/errors/hooks.d.ts +2 -0
  23. package/dist/errors-H4JJFH3S.js +620 -0
  24. package/dist/errors-IhnTKUp7.cjs +871 -0
  25. package/dist/errors.d.ts +18 -36
  26. package/dist/execute-BYI_U5sR.js +1943 -0
  27. package/dist/execute-DLas4V2n.cjs +1944 -0
  28. package/dist/{exit-DUM96DN1.cjs → exit-BUgJ5qi5.cjs} +38 -28
  29. package/dist/{exit-CDdxDBRT.js → exit-CPNk3vbz.js} +37 -27
  30. package/dist/exit.d.ts +19 -16
  31. package/dist/index.cjs +176 -1237
  32. package/dist/index.d.ts +25 -28
  33. package/dist/index.js +137 -1213
  34. package/dist/index.workerd.js +8427 -10771
  35. package/dist/inspect.d.ts +18 -4
  36. package/dist/inspection.d.ts +38 -0
  37. package/dist/native-Bm6L9zOb.cjs +212 -0
  38. package/dist/native-DvTH9vFe.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-DJwYDSsb.cjs +1073 -0
  43. package/dist/quickjs-variant-DlPi9-Sx.js +984 -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 +48 -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/generate.d.ts +23 -20
  54. package/dist/runtime/inspection-values.d.ts +14 -0
  55. package/dist/runtime/inspection-values.test.d.ts +1 -0
  56. package/dist/runtime/interruption-control-flow.test.d.ts +1 -0
  57. package/dist/runtime/interruption-settings.test.d.ts +1 -0
  58. package/dist/runtime/javascript-api.d.ts +59 -0
  59. package/dist/runtime/javascript-api.test.d.ts +1 -0
  60. package/dist/runtime/native-review.test.d.ts +1 -0
  61. package/dist/runtime/native-tools.d.ts +18 -0
  62. package/dist/runtime/native-tools.test.d.ts +1 -0
  63. package/dist/runtime/object-memory.test.d.ts +1 -0
  64. package/dist/runtime/single-tool.test.d.ts +1 -0
  65. package/dist/runtime/token-budget.d.ts +22 -0
  66. package/dist/runtime/token-budget.test.d.ts +1 -0
  67. package/dist/runtime/tool-wrapper.d.ts +4 -5
  68. package/dist/runtime/traces.test.d.ts +1 -0
  69. package/dist/runtime/truncation.test.d.ts +1 -0
  70. package/dist/runtime/types.d.ts +39 -31
  71. package/dist/runtime/variable-recovery.test.d.ts +1 -0
  72. package/dist/runtime/vm-context.d.ts +6 -1
  73. package/dist/runtime/worker-completion.test.d.ts +1 -0
  74. package/dist/runtime-names.d.ts +4 -0
  75. package/dist/schema-Aer_W7Al.js +45 -0
  76. package/dist/schema-DBkjo0b7.cjs +68 -0
  77. package/dist/schema.d.ts +10 -0
  78. package/dist/schema.test.d.ts +1 -0
  79. package/dist/session/compactor.d.ts +51 -0
  80. package/dist/session/compactor.test.d.ts +1 -0
  81. package/dist/session/history.d.ts +36 -0
  82. package/dist/session/history.test.d.ts +1 -0
  83. package/dist/session/json.d.ts +3 -0
  84. package/dist/session/json.test.d.ts +1 -0
  85. package/dist/session/memory-codec.d.ts +9 -0
  86. package/dist/session/memory-codec.test.d.ts +1 -0
  87. package/dist/session/memory-render.d.ts +15 -0
  88. package/dist/session/memory-render.test.d.ts +1 -0
  89. package/dist/session/memory.d.ts +112 -0
  90. package/dist/session/memory.test.d.ts +1 -0
  91. package/dist/session/messages.d.ts +17 -0
  92. package/dist/session/messages.test.d.ts +1 -0
  93. package/dist/session/serialization.d.ts +34 -0
  94. package/dist/session/serialization.test.d.ts +1 -0
  95. package/dist/session/session-memory.test.d.ts +1 -0
  96. package/dist/session/session.d.ts +117 -0
  97. package/dist/session/session.test.d.ts +1 -0
  98. package/dist/{transcript.d.ts → session/transcript.d.ts} +4 -8
  99. package/dist/session/transcript.test.d.ts +1 -0
  100. package/dist/{tool-Bv8N4IPj.js → tool--gK91eez.js} +144 -92
  101. package/dist/{tool-Dy6AJpJH.cjs → tool-Da_F-N-5.cjs} +146 -94
  102. package/dist/tool.d.ts +25 -17
  103. package/dist/truncate-BSoH2-nY.js +79 -0
  104. package/dist/truncate-nV3Mxr6-.cjs +102 -0
  105. package/dist/truncate.d.ts +24 -0
  106. package/dist/truncate.test.d.ts +1 -0
  107. package/dist/types.d.ts +27 -9
  108. package/dist/{typings-3lsqCbkn.cjs → typings-C1ihexWE.cjs} +38 -193
  109. package/dist/{typings-CrBa7Tyy.js → typings-D9_aC8aq.js} +38 -175
  110. package/dist/typings-formatter.d.ts +1 -1
  111. package/dist/typings.d.ts +3 -0
  112. package/dist/{uniq-BYQ7GWwb.js → uniq-DfUeSNaX.js} +2 -2
  113. package/dist/{uniq-G872RWmE.cjs → uniq-DiXgysNV.cjs} +6 -18
  114. package/dist/{_baseIteratee-P_firB7b.js → utils-BOFzb8Ok.js} +1134 -16
  115. package/dist/{_baseIteratee-CF4qP2a8.cjs → utils-CTlsXvdj.cjs} +1281 -84
  116. package/dist/vm/drivers/node.d.ts +1 -1
  117. package/dist/vm/drivers/quickjs.d.ts +1 -1
  118. package/dist/vm/errors.d.ts +4 -4
  119. package/dist/vm/index.d.ts +3 -4
  120. package/dist/vm/instrument.d.ts +14 -6
  121. package/dist/vm/member-proxy.d.ts +4 -0
  122. package/dist/vm/member-proxy.test.d.ts +1 -0
  123. package/dist/vm/memory.test.d.ts +1 -0
  124. package/dist/vm/return-semantics.test.d.ts +1 -0
  125. package/dist/vm/types.d.ts +18 -3
  126. package/dist/{vm-BLsHw1da.js → vm-8jxt8PTK.js} +1162 -180
  127. package/dist/{vm-D6s1zF6M.cjs → vm-XuVPuW3Y.cjs} +1195 -207
  128. package/package.json +13 -6
  129. package/dist/_baseForOwn-BfWDTL8L.cjs +0 -53
  130. package/dist/_baseForOwn-CFhWe_W6.js +0 -48
  131. package/dist/_getPrototype-CG7Dxrrz.js +0 -6
  132. package/dist/_getPrototype-DQDlNVVM.cjs +0 -10
  133. package/dist/_overArg-C5Hy7oCi.cjs +0 -196
  134. package/dist/_overArg-CRYbj1NH.js +0 -155
  135. package/dist/chat.d.ts +0 -401
  136. package/dist/common-BlRFtdf2.js +0 -807
  137. package/dist/common-BnvrDnIT.cjs +0 -860
  138. package/dist/compiler/plugins/track-tool-calls.d.ts +0 -33
  139. package/dist/compiler-C-OI9sim.cjs +0 -547
  140. package/dist/compiler-CW1VjQsn.js +0 -473
  141. package/dist/component-C6Agl2ns.cjs +0 -73
  142. package/dist/component-DGG7d_Mz.js +0 -44
  143. package/dist/component.d.ts +0 -88
  144. package/dist/component.default.d.ts +0 -278
  145. package/dist/custom-client-ChuZ63zp.js +0 -2658
  146. package/dist/custom-client-DAsGRnYc.cjs +0 -2729
  147. package/dist/dual-modes-DDkoCp3R.js +0 -3006
  148. package/dist/dual-modes-DPXiuvNe.cjs +0 -3090
  149. package/dist/errors-C962uJdS.cjs +0 -220
  150. package/dist/errors-Cg1G0Awu.js +0 -161
  151. package/dist/example-format.d.ts +0 -8
  152. package/dist/example.d.ts +0 -45
  153. package/dist/execute-BWcdv9so.js +0 -1059
  154. package/dist/execute-DM2-7y86.cjs +0 -1060
  155. package/dist/exit-parser.d.ts +0 -39
  156. package/dist/handlers.d.ts +0 -10
  157. package/dist/hoist.d.ts +0 -2
  158. package/dist/isEmpty-BhJRCqIF.js +0 -52
  159. package/dist/isEmpty-LY533Wmh.cjs +0 -57
  160. package/dist/isPlainObject-CSxXVKCk.cjs +0 -56
  161. package/dist/isPlainObject-D39AzPO2.js +0 -51
  162. package/dist/jsx-CIgdGGVs.js +0 -52
  163. package/dist/jsx-owqxrquU.cjs +0 -75
  164. package/dist/jsx.d.ts +0 -11
  165. package/dist/message-stream/index.d.ts +0 -9
  166. package/dist/message-stream/instructions.d.ts +0 -30
  167. package/dist/message-stream/normalizer.d.ts +0 -21
  168. package/dist/message-stream/parser.d.ts +0 -89
  169. package/dist/message-stream/registry.d.ts +0 -14
  170. package/dist/message-stream/replayable.d.ts +0 -27
  171. package/dist/message-stream/response-parser.d.ts +0 -24
  172. package/dist/message-stream/sanitize.d.ts +0 -10
  173. package/dist/message-stream/stream.d.ts +0 -54
  174. package/dist/message-stream/types.d.ts +0 -97
  175. package/dist/message-stream/validator.d.ts +0 -23
  176. package/dist/prompts/chat-mode/protocol.d.ts +0 -2
  177. package/dist/prompts/chat-mode/system.d.ts +0 -2
  178. package/dist/prompts/chat-mode/system.md.d.ts +0 -2
  179. package/dist/prompts/chat-mode/user.d.ts +0 -2
  180. package/dist/prompts/chat-mode/user.md.d.ts +0 -2
  181. package/dist/prompts/code-examples.d.ts +0 -2
  182. package/dist/prompts/common.d.ts +0 -7
  183. package/dist/prompts/dual-modes.d.ts +0 -2
  184. package/dist/prompts/execution-history.d.ts +0 -6
  185. package/dist/prompts/execution-state.d.ts +0 -3
  186. package/dist/prompts/protocol-basics.d.ts +0 -5
  187. package/dist/prompts/protocol.d.ts +0 -31
  188. package/dist/prompts/worker-mode/protocol.d.ts +0 -2
  189. package/dist/prompts/worker-mode/system.d.ts +0 -2
  190. package/dist/prompts/worker-mode/system.md.d.ts +0 -2
  191. package/dist/prompts/worker-mode/user.d.ts +0 -2
  192. package/dist/prompts/worker-mode/user.md.d.ts +0 -2
  193. package/dist/quickjs-variant-BYhMBpwU.js +0 -45
  194. package/dist/quickjs-variant-CsIwTVFC.cjs +0 -56
  195. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  196. package/dist/runtime/fixtures/qwen-protocol-failures.d.ts +0 -29
  197. package/dist/runtime/interpret-result.d.ts +0 -22
  198. package/dist/snapshots.d.ts +0 -249
  199. package/dist/stack-traces-BIE_5Xwf.js +0 -21
  200. package/dist/stack-traces-ntw_qhoy.cjs +0 -26
  201. package/dist/truncator-CLkouTCO.cjs +0 -276
  202. package/dist/truncator-DZqEqnpD.js +0 -253
  203. package/dist/truncator.d.ts +0 -118
  204. package/dist/utils-3ESwP3yg.cjs +0 -1075
  205. package/dist/utils-UBeAFeEI.js +0 -950
  206. /package/dist/{citations.d.ts → chat/citations.d.ts} +0 -0
  207. /package/dist/{citations.test.d.ts → chat/citations.test.d.ts} +0 -0
  208. /package/dist/{component.default.test.d.ts → chat/component.default.test.d.ts} +0 -0
  209. /package/dist/{compiler/plugins/track-tool-calls.test.d.ts → chat/component.test.d.ts} +0 -0
  210. /package/dist/{example.test.d.ts → chat/response.test.d.ts} +0 -0
  211. /package/dist/{exit-parser.test.d.ts → compiler/plugins/dynamic-code.test.d.ts} +0 -0
  212. /package/dist/{handlers.test.d.ts → compiler/plugins/tool-resolution.test.d.ts} +0 -0
  213. /package/dist/{hoist.test.d.ts → errors/catalog.test.d.ts} +0 -0
  214. /package/dist/{message-stream/instructions.test.d.ts → exit.test.d.ts} +0 -0
  215. /package/dist/{message-stream/normalizer.test.d.ts → inspection.test.d.ts} +0 -0
  216. /package/dist/{message-stream/parser.test.d.ts → prompts/native.test.d.ts} +0 -0
  217. /package/dist/{message-stream/response-parser.test.d.ts → result.test.d.ts} +0 -0
  218. /package/dist/{message-stream/stream.test.d.ts → runtime/chat-delivery.test.d.ts} +0 -0
  219. /package/dist/{message-stream/validator.test.d.ts → runtime/compatibility-regressions.test.d.ts} +0 -0
  220. /package/dist/{prompts/adherence.test.d.ts → runtime/context-registration.test.d.ts} +0 -0
  221. /package/dist/{prompts/catalogue-examples.test.d.ts → runtime/error-recovery.test.d.ts} +0 -0
  222. /package/dist/{prompts/code-examples.test.d.ts → runtime/errors.test.d.ts} +0 -0
  223. /package/dist/{prompts/common.test.d.ts → runtime/execution-activity.test.d.ts} +0 -0
  224. /package/dist/{prompts/concrete-patterns.test.d.ts → runtime/execution-diagnostics.test.d.ts} +0 -0
  225. /package/dist/{prompts/long-search.test.d.ts → runtime/execution-report.test.d.ts} +0 -0
  226. /package/dist/{prompts/protocol-simple.test.d.ts → runtime/execution-safety.test.d.ts} +0 -0
  227. /package/dist/{prompts/protocol.test.d.ts → runtime/exit-control-flow.test.d.ts} +0 -0
  228. /package/dist/{prompts/sections.test.d.ts → runtime/fixtures/long-search.test.d.ts} +0 -0
  229. /package/dist/runtime/{interpret-result.test.d.ts → generate.test.d.ts} +0 -0
  230. /package/dist/{transcript.test.d.ts → runtime/hook-provenance.test.d.ts} +0 -0
  231. /package/dist/{truncator.test.d.ts → runtime/inspection-hook.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-IhnTKUp7.cjs");
3
+ const require_quickjs_variant = require("./quickjs-variant-DJwYDSsb.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,87 @@ 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_ON_ERROR = Symbol("llmz.onError");
2999
+ //#endregion
2356
3000
  //#region src/vm/instrument.ts
2357
3001
  const USER_CODE_MARKER_TAG_START = "__LLMZ_USER_CODE_START__";
2358
3002
  const USER_CODE_MARKER_TAG_END = "__LLMZ_USER_CODE_END__";
2359
3003
  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
3004
+ Identifiers.CommentFnIdentifier,
3005
+ Identifiers.VariableTrackingFnIdentifier,
3006
+ Identifiers.ConsoleObjIdentifier,
3007
+ TerminationCheckpointIdentifier,
3008
+ TerminationGuardIdentifier
2365
3009
  ];
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) => {
3010
+ function instrumentContext(context, transformed, recordTrace, variables, lines_executed, consumer, userCodeStartLine, memoryNames = []) {
3011
+ const state = {
3012
+ lastExecutedLine: void 0,
3013
+ memoryNames: /* @__PURE__ */ new Set([...memoryNames, ...transformed.variables]),
3014
+ variableWrites: [],
3015
+ captureErrors: []
3016
+ };
3017
+ context[MissingToolIdentifier] = (name) => {
3018
+ var _context$VM_ON_ERROR;
3019
+ const error = new require_errors.UnknownToolError(name, Object.keys(context).filter((key) => !key.startsWith("__") && typeof context[key] === "function"));
3020
+ (_context$VM_ON_ERROR = context[VM_ON_ERROR]) === null || _context$VM_ON_ERROR === void 0 || _context$VM_ON_ERROR.call(context, error);
3021
+ throw error;
3022
+ };
3023
+ context[TerminationGuardIdentifier] = () => {
3024
+ var _context$VM_TERMINATI;
3025
+ return (_context$VM_TERMINATI = context[VM_TERMINATION]) === null || _context$VM_TERMINATI === void 0 ? void 0 : _context$VM_TERMINATI.check();
3026
+ };
3027
+ context[TerminationCheckpointIdentifier] = (value) => {
3028
+ var _context$VM_TERMINATI2;
3029
+ if (value instanceof Promise) Promise.prototype.then.call(value, void 0, () => {});
3030
+ (_context$VM_TERMINATI2 = context[VM_TERMINATION]) === null || _context$VM_TERMINATI2 === void 0 || _context$VM_TERMINATI2.check();
3031
+ return value;
3032
+ };
3033
+ context[Identifiers.CommentFnIdentifier] = (comment, line) => {
2369
3034
  if (comment.includes(USER_CODE_MARKER_TAG_START) || comment.includes(USER_CODE_MARKER_TAG_END)) return;
2370
- traces.push({
3035
+ recordTrace({
2371
3036
  type: "comment",
2372
3037
  comment,
2373
3038
  line,
2374
3039
  started_at: Date.now()
2375
3040
  });
2376
3041
  };
2377
- context[require_compiler.Identifiers.LineTrackingFnIdentifier] = (line) => {
3042
+ context[Identifiers.LineTrackingFnIdentifier] = (line) => {
2378
3043
  const mappedLine = consumer.originalPositionFor({
2379
3044
  line,
2380
3045
  column: 0
2381
3046
  }).line ?? line;
2382
3047
  const userCodeLine = Math.max(1, mappedLine - userCodeStartLine);
3048
+ state.lastExecutedLine = userCodeLine;
2383
3049
  lines_executed.set(userCodeLine, (lines_executed.get(userCodeLine) ?? 0) + 1);
2384
3050
  };
2385
- context[require_compiler.Identifiers.VariableTrackingFnIdentifier] = (name, getter) => {
2386
- if (NO_TRACKING.includes(name)) return;
3051
+ context[Identifiers.VariableTrackingFnIdentifier] = (name, getter, result, kind = "assignment") => {
3052
+ if (NO_TRACKING.includes(name) || !state.memoryNames.has(name)) return result;
3053
+ if (kind !== "initialize" && kind !== "read") state.variableWrites.push({
3054
+ name,
3055
+ timestamp: Date.now(),
3056
+ kind
3057
+ });
2387
3058
  variables[name] = () => {
2388
3059
  try {
2389
- const value = getter();
2390
- if (typeof value === "function") return "[[non-primitive]]";
2391
- return value;
2392
- } catch {
2393
- return "[[non-primitive]]";
3060
+ return getter();
3061
+ } catch (err) {
3062
+ if (!state.captureErrors.some((entry) => entry.name === name)) state.captureErrors.push({
3063
+ name,
3064
+ reason: err instanceof Error ? err.message : String(err)
3065
+ });
3066
+ return;
2394
3067
  }
2395
3068
  };
3069
+ return result;
2396
3070
  };
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({
3071
+ context[Identifiers.ConsoleObjIdentifier] = { log: (...args) => {
3072
+ recordTrace({
2410
3073
  type: "log",
2411
- message,
3074
+ message: args.shift(),
2412
3075
  args,
2413
3076
  started_at: Date.now()
2414
3077
  });
@@ -2423,14 +3086,44 @@ function findUserCodeStartLine(transformed) {
2423
3086
  }
2424
3087
  return -1;
2425
3088
  }
3089
+ /** Drop unsupported captures explicitly instead of presenting lossy placeholders as data. */
3090
+ function finalizeMemoryCapture(result, state) {
3091
+ for (const [name, value] of Object.entries(result.variables)) try {
3092
+ result.variables[name] = require_quickjs_variant.cloneMemoryValue(value);
3093
+ } catch (err) {
3094
+ if (!state.captureErrors.some((entry) => entry.name === name)) state.captureErrors.push({
3095
+ name,
3096
+ reason: err instanceof Error ? err.message : String(err)
3097
+ });
3098
+ }
3099
+ for (const failure of state.captureErrors) {
3100
+ var _result$signal;
3101
+ delete result.variables[failure.name];
3102
+ if ((_result$signal = result.signal) === null || _result$signal === void 0 ? void 0 : _result$signal.variables) delete result.signal.variables[failure.name];
3103
+ }
3104
+ if (result.success && !result.signal) try {
3105
+ result.return_value = require_quickjs_variant.cloneMemoryValue(result.return_value);
3106
+ } catch (err) {
3107
+ if (!state.captureErrors.some((entry) => entry.name === "$return")) state.captureErrors.push({
3108
+ name: "$return",
3109
+ reason: err instanceof Error ? err.message : String(err)
3110
+ });
3111
+ result.return_value = void 0;
3112
+ }
3113
+ return {
3114
+ ...result,
3115
+ variableWrites: state.variableWrites,
3116
+ captureErrors: state.captureErrors
3117
+ };
3118
+ }
2426
3119
  //#endregion
2427
3120
  //#region src/vm/drivers/node.ts
2428
3121
  var NodeDriver = class {
2429
3122
  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);
3123
+ const { transformed, consumer, context, traces, recordTrace, code, lines_executed, variables } = ctx;
3124
+ const state = instrumentContext(context, transformed, recordTrace, variables, lines_executed, consumer, findUserCodeStartLine(transformed), ctx.memoryNames);
2432
3125
  const AsyncFunction = async function() {}.constructor;
2433
- return await (async () => {
3126
+ return finalizeMemoryCapture(await (async () => {
2434
3127
  const descriptors = Object.getOwnPropertyDescriptors(context);
2435
3128
  const topLevelProperties = Object.keys(descriptors).filter((x) => !NO_TRACKING.includes(x) && descriptors[x] && typeof descriptors[x].value !== "function" && typeof descriptors[x].value !== "object");
2436
3129
  const __report = (name, value) => {
@@ -2438,21 +3131,59 @@ var NodeDriver = class {
2438
3131
  };
2439
3132
  context.__report = __report;
2440
3133
  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));
3134
+ const assigner = `let __${Identifiers.LineTrackingFnIdentifier} = ${Identifiers.LineTrackingFnIdentifier}; ${Identifiers.LineTrackingFnIdentifier} = function(line) { ${reportAll}; __${Identifiers.LineTrackingFnIdentifier}(line);}`;
3135
+ const trackInputs = ctx.memoryNames.map((name) => `${Identifiers.VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => eval(${JSON.stringify(name)}), undefined, "read");`).join("");
3136
+ const bindings = Object.keys(context);
3137
+ const protectedBindings = bindings.filter((name) => require_quickjs_variant.RESERVED_RUNTIME_NAMES.has(name)).map((name) => `const ${name} = __llmz_binding_${bindings.indexOf(name)};`).join("");
3138
+ const parameters = bindings.map((name, index) => require_quickjs_variant.RESERVED_RUNTIME_NAMES.has(name) ? `__llmz_binding_${index}` : name);
3139
+ const wrapper = `"use strict"; ${protectedBindings} try { ${assigner};${trackInputs}${transformed.code} } finally { ${reportAll} };`;
3140
+ const fn = AsyncFunction(...parameters, wrapper);
3141
+ try {
3142
+ return await fn(...Object.values(context));
3143
+ } finally {
3144
+ var _context$VM_PROGRAM_C;
3145
+ (_context$VM_PROGRAM_C = context[VM_PROGRAM_COMPLETE]) === null || _context$VM_PROGRAM_C === void 0 || _context$VM_PROGRAM_C.call(context);
3146
+ }
2443
3147
  })().then((res) => {
3148
+ var _context$VM_TERMINATI, _context$VM_TERMINATI2, _context$VM_TERMINATI3;
3149
+ 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);
3150
+ if (signal) throw signal;
3151
+ if ((_context$VM_TERMINATI3 = context[VM_TERMINATION]) === null || _context$VM_TERMINATI3 === void 0 ? void 0 : _context$VM_TERMINATI3.isTerminated()) res = void 0;
2444
3152
  res = require_errors.Signals.maybeDeserializeError(res);
2445
3153
  return {
2446
3154
  success: true,
2447
- variables: mapValues(variables, (getter) => require__baseIteratee.isFunction(getter) ? getter() : getter),
2448
- signal: res instanceof require_errors.VMSignal ? res : void 0,
3155
+ variables: mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter),
3156
+ signal: require_errors.VMSignal.is(res) ? res : void 0,
2449
3157
  lines_executed: Array.from(lines_executed),
2450
3158
  return_value: res
2451
3159
  };
2452
- }).catch((err) => handleErrorNode(err, code, consumer, traces, variables, lines_executed, state.currentToolCall)).catch((err) => handleCatch(err, traces, variables, lines_executed));
3160
+ }).catch((err) => {
3161
+ var _context$VM_TERMINATI4, _context$VM_TERMINATI5, _context$VM_TERMINATI6;
3162
+ 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);
3163
+ if (signal) return handleErrorNode(signal, code, consumer, recordTrace, variables, lines_executed, state.lastExecutedLine);
3164
+ if ((_context$VM_TERMINATI6 = context[VM_TERMINATION]) === null || _context$VM_TERMINATI6 === void 0 ? void 0 : _context$VM_TERMINATI6.isTerminated()) return {
3165
+ success: true,
3166
+ variables: mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter),
3167
+ lines_executed: Array.from(lines_executed)
3168
+ };
3169
+ return handleErrorNode(err, code, consumer, recordTrace, variables, lines_executed, state.lastExecutedLine);
3170
+ }).catch((err) => handleCatch(err, traces, variables, lines_executed)), state);
2453
3171
  }
2454
3172
  };
2455
3173
  //#endregion
3174
+ //#region src/vm/member-proxy.ts
3175
+ /** Host-only metadata lets QuickJS install the same missing-member behavior in its own realm. */
3176
+ const MISSING_MEMBER = Symbol("llmz.missingMember");
3177
+ /** Only registered own members are callable; inherited Object methods are not API members. */
3178
+ function withMissingMember(target, missing) {
3179
+ Object.defineProperty(target, MISSING_MEMBER, { value: missing });
3180
+ Object.freeze(target);
3181
+ return new Proxy(target, { get(object, key, receiver) {
3182
+ if (typeof key === "string" && !Object.hasOwn(object, key)) return missing(key);
3183
+ return Reflect.get(object, key, receiver);
3184
+ } });
3185
+ }
3186
+ //#endregion
2456
3187
  //#region src/vm/drivers/quickjs.ts
2457
3188
  let _quickJSModule;
2458
3189
  let _loadedVariant;
@@ -2466,9 +3197,27 @@ const loadQuickJSModule = () => {
2466
3197
  };
2467
3198
  var QuickJSDriver = class {
2468
3199
  async execute(ctx) {
2469
- const { transformed, consumer, context, traces, signal, timeout, code, lines_executed, variables } = ctx;
3200
+ const { transformed, consumer, context, traces, recordTrace, signal, timeout, code, lines_executed, variables } = ctx;
2470
3201
  const userCodeStartLine = findUserCodeStartLine(transformed);
2471
- const state = instrumentContext(context, transformed, traces, variables, lines_executed, consumer, userCodeStartLine);
3202
+ const state = instrumentContext(context, transformed, recordTrace, variables, lines_executed, consumer, userCodeStartLine, ctx.memoryNames);
3203
+ const isTerminated = () => {
3204
+ var _context$VM_TERMINATI;
3205
+ return ((_context$VM_TERMINATI = context[VM_TERMINATION]) === null || _context$VM_TERMINATI === void 0 ? void 0 : _context$VM_TERMINATI.isTerminated()) ?? false;
3206
+ };
3207
+ const shouldStopJobs = () => {
3208
+ var _context$VM_TERMINATI2, _context$VM_TERMINATI3;
3209
+ 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));
3210
+ };
3211
+ const terminalResult = () => {
3212
+ var _context$VM_TERMINATI4, _context$VM_TERMINATI5;
3213
+ 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);
3214
+ if (interruption) return finalizeMemoryCapture(handleErrorQuickJS(interruption, code, consumer, traces, variables, lines_executed, userCodeStartLine, recordTrace), state);
3215
+ return finalizeMemoryCapture({
3216
+ success: true,
3217
+ variables: mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter),
3218
+ lines_executed: Array.from(lines_executed)
3219
+ }, state);
3220
+ };
2472
3221
  const runtime = (await loadQuickJSModule()).newRuntime();
2473
3222
  runtime.setMemoryLimit(134217728);
2474
3223
  const timeoutHandler = (0, quickjs_emscripten_core.shouldInterruptAfterDeadline)(Date.now() + timeout);
@@ -2480,36 +3229,45 @@ var QuickJSDriver = class {
2480
3229
  const trackedProperties = /* @__PURE__ */ new Set();
2481
3230
  const referenceProperties = /* @__PURE__ */ new Set();
2482
3231
  const pendingPromises = [];
2483
- const toVmValue = (value) => {
3232
+ const variableGetters = /* @__PURE__ */ new Map();
3233
+ let captureValue;
3234
+ const objectConstructor = vm.getProp(vm.global, "Object");
3235
+ const freezeFunction = vm.getProp(objectConstructor, "freeze");
3236
+ objectConstructor.dispose();
3237
+ const preserveHostFreeze = (hostValue, handle, preserveFrozen) => {
3238
+ if (!preserveFrozen || !Object.isFrozen(hostValue)) return handle;
3239
+ const frozen = vm.callFunction(freezeFunction, vm.undefined, handle);
3240
+ if ("error" in frozen) {
3241
+ const error = vm.dump(frozen.error);
3242
+ frozen.error.dispose();
3243
+ handle.dispose();
3244
+ throw new Error(error.message);
3245
+ }
3246
+ frozen.value.dispose();
3247
+ return handle;
3248
+ };
3249
+ const toVmValue = (value, preserveFrozen = false) => {
2484
3250
  if (typeof value === "string") return vm.newString(value);
2485
3251
  else if (typeof value === "number") return vm.newNumber(value);
2486
3252
  else if (typeof value === "boolean") return value ? vm.true : vm.false;
2487
3253
  else if (value === null) return vm.null;
2488
3254
  else if (value === void 0) return vm.undefined;
2489
3255
  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";
3256
+ const array = vm.newArray();
3257
+ value.forEach((item, index) => {
3258
+ const handle = toVmValue(item, preserveFrozen);
3259
+ vm.setProp(array, index, handle);
3260
+ disposeIfNeeded(handle);
2497
3261
  });
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;
3262
+ return preserveHostFreeze(value, array, preserveFrozen);
2505
3263
  } else if (typeof value === "object") {
2506
3264
  const obj = vm.newObject();
2507
3265
  for (const [k, v] of Object.entries(value)) if (typeof v !== "function") {
2508
- const propHandle = toVmValue(v);
3266
+ const propHandle = toVmValue(v, preserveFrozen);
2509
3267
  vm.setProp(obj, k, propHandle);
2510
3268
  disposeIfNeeded(propHandle);
2511
3269
  }
2512
- return obj;
3270
+ return preserveHostFreeze(value, obj, preserveFrozen);
2513
3271
  }
2514
3272
  return vm.undefined;
2515
3273
  };
@@ -2523,36 +3281,94 @@ var QuickJSDriver = class {
2523
3281
  const result = fn(...args);
2524
3282
  if (result && typeof result.then === "function") {
2525
3283
  const promise = vm.newPromise();
3284
+ const hostPromise = Promise.resolve(result).then((value) => require_quickjs_variant.cloneMemoryValue(value));
3285
+ hostPromise.catch(() => {});
2526
3286
  pendingPromises.push({
2527
- hostPromise: result,
3287
+ hostPromise,
2528
3288
  deferredPromise: promise
2529
3289
  });
2530
3290
  promise.settled.then(() => {
2531
- if (runtime.alive) runtime.executePendingJobs();
3291
+ if (runtime.alive && !shouldStopJobs()) runtime.executePendingJobs();
2532
3292
  });
2533
3293
  return promise.handle;
2534
3294
  }
2535
- return toVmValue(result);
3295
+ return toVmValue(require_quickjs_variant.cloneMemoryValue(result));
2536
3296
  } catch (err) {
2537
- const serialized = err instanceof Error ? err.message : String(err);
2538
- throw new Error(serialized);
3297
+ return { error: guestError(vm, err) };
2539
3298
  }
2540
3299
  };
2541
3300
  };
2542
3301
  try {
2543
- bridgeContextToVM(context, vm, trackedProperties, referenceProperties, toVmValue, disposeIfNeeded, bridgeFunction);
2544
- setupVariableTrackingBridge(vm, variables);
3302
+ captureValue = setupMemoryCapture(vm);
3303
+ bridgeContextToVM(context, vm, trackedProperties, referenceProperties, toVmValue, disposeIfNeeded, bridgeFunction, captureValue);
3304
+ setupVariableTrackingBridge(vm, variables, variableGetters, state, captureValue);
3305
+ vm.evalCode(`(() => {
3306
+ const then = Promise.prototype.then;
3307
+ const check = globalThis.${TerminationGuardIdentifier};
3308
+ globalThis.${TerminationCheckpointIdentifier} = (value) => {
3309
+ if (value instanceof Promise) {
3310
+ then.call(value, undefined, () => {});
3311
+ }
3312
+ check();
3313
+ return value;
3314
+ };
3315
+ })()`).unwrap().dispose();
3316
+ const complete = vm.newFunction("__llmz_program_complete", () => {
3317
+ var _context$VM_PROGRAM_C;
3318
+ (_context$VM_PROGRAM_C = context[VM_PROGRAM_COMPLETE]) === null || _context$VM_PROGRAM_C === void 0 || _context$VM_PROGRAM_C.call(context);
3319
+ return vm.undefined;
3320
+ });
3321
+ vm.setProp(vm.global, "__llmz_program_complete", complete);
3322
+ complete.dispose();
3323
+ for (const name of ctx.memoryNames) {
3324
+ const tracked = vm.evalCode(`${Identifiers.VariableTrackingFnIdentifier}(${JSON.stringify(name)}, () => globalThis[${JSON.stringify(name)}], undefined, "read");`);
3325
+ if ("error" in tracked) {
3326
+ var _tracked$error;
3327
+ (_tracked$error = tracked.error) === null || _tracked$error === void 0 || _tracked$error.dispose();
3328
+ } else tracked.value.dispose();
3329
+ }
3330
+ const protect = vm.evalCode(`(() => {
3331
+ function freeze(value) {
3332
+ if (value && (typeof value === 'object' || typeof value === 'function') && !Object.isFrozen(value)) {
3333
+ Object.values(value).forEach(freeze);
3334
+ Object.freeze(value);
3335
+ }
3336
+ return value;
3337
+ }
3338
+ for (const name of ${JSON.stringify([
3339
+ ...require_quickjs_variant.RUNTIME_BINDING_NAMES,
3340
+ ...require_quickjs_variant.TERMINATION_BINDING_NAMES,
3341
+ "__llmz_program_complete"
3342
+ ])}) {
3343
+ if (Object.prototype.hasOwnProperty.call(globalThis, name)) {
3344
+ Object.defineProperty(globalThis, name, {
3345
+ value: freeze(globalThis[name]),
3346
+ writable: false,
3347
+ configurable: false,
3348
+ });
3349
+ }
3350
+ }
3351
+ })()`);
3352
+ if ("error" in protect) {
3353
+ const error = vm.dump(protect.error);
3354
+ protect.error.dispose();
3355
+ throw new Error(error.message);
3356
+ }
3357
+ protect.value.dispose();
2545
3358
  const scriptCode = buildScriptCode(transformed.code);
2546
3359
  const copyBackContextFromVM = () => {
2547
3360
  for (const key of trackedProperties) {
2548
3361
  if (referenceProperties.has(key)) continue;
2549
3362
  try {
2550
- const valueResult = vm.evalCode(`globalThis['${key}']`);
2551
- const vmValue = vm.dump(valueResult.unwrap());
2552
- valueResult.unwrap().dispose();
3363
+ const handle = vm.evalCode(`globalThis['${key}']`).unwrap();
2553
3364
  try {
2554
- context[key] = vmValue;
2555
- } catch {}
3365
+ const vmValue = ctx.memoryNames.includes(key) ? captureValue(handle) : vm.dump(handle);
3366
+ try {
3367
+ context[key] = vmValue;
3368
+ } catch {}
3369
+ } finally {
3370
+ handle.dispose();
3371
+ }
2556
3372
  } catch {}
2557
3373
  }
2558
3374
  };
@@ -2566,7 +3382,11 @@ var QuickJSDriver = class {
2566
3382
  throw new Error("Execution failed");
2567
3383
  }
2568
3384
  execResult.value.dispose();
2569
- await this._pumpEventLoop(runtime, vm, pendingPromises, signal, toVmValue, disposeIfNeeded);
3385
+ await this._pumpEventLoop(runtime, vm, pendingPromises, signal, toVmValue, disposeIfNeeded, shouldStopJobs);
3386
+ if (isTerminated()) {
3387
+ copyBackContextFromVM();
3388
+ return terminalResult();
3389
+ }
2570
3390
  const errorResult = vm.evalCode("globalThis.__llmz_error");
2571
3391
  const errorValue = vm.dump(errorResult.unwrap());
2572
3392
  errorResult.unwrap().dispose();
@@ -2583,11 +3403,14 @@ var QuickJSDriver = class {
2583
3403
  const errorStack = vm.dump(errorStackResult.unwrap()) || "";
2584
3404
  errorStackResult.unwrap().dispose();
2585
3405
  const deserializedError = require_errors.Signals.maybeDeserializeError(errorValue);
2586
- if (deserializedError instanceof require_errors.VMSignal) {
3406
+ if (require_errors.VMSignal.is(deserializedError)) {
2587
3407
  deserializedError.stack = errorStack;
2588
3408
  throw deserializedError;
2589
3409
  }
2590
3410
  const error = new Error(errorValue);
3411
+ const errorNameResult = vm.evalCode("globalThis.__llmz_error_name");
3412
+ error.name = vm.dump(errorNameResult.unwrap()) || "Error";
3413
+ errorNameResult.unwrap().dispose();
2591
3414
  error.stack = errorStack;
2592
3415
  throw error;
2593
3416
  }
@@ -2597,23 +3420,35 @@ var QuickJSDriver = class {
2597
3420
  resultSetResult.unwrap().dispose();
2598
3421
  let returnValue = void 0;
2599
3422
  if (resultSet) {
2600
- const resultResult = vm.evalCode("globalThis.__llmz_result");
2601
- returnValue = vm.dump(resultResult.unwrap());
2602
- resultResult.unwrap().dispose();
3423
+ const resultHandle = vm.evalCode("globalThis.__llmz_result").unwrap();
3424
+ try {
3425
+ returnValue = captureValue(resultHandle);
3426
+ } catch (err) {
3427
+ state.captureErrors.push({
3428
+ name: "$return",
3429
+ reason: err instanceof Error ? err.message : String(err)
3430
+ });
3431
+ } finally {
3432
+ resultHandle.dispose();
3433
+ }
2603
3434
  }
2604
3435
  returnValue = require_errors.Signals.maybeDeserializeError(returnValue);
2605
- return {
3436
+ return finalizeMemoryCapture({
2606
3437
  success: true,
2607
- variables: mapValues(variables, (getter) => require__baseIteratee.isFunction(getter) ? getter() : getter),
2608
- signal: returnValue instanceof require_errors.VMSignal ? returnValue : void 0,
3438
+ variables: mapValues(variables, (getter) => require_utils.isFunction(getter) ? getter() : getter),
3439
+ signal: require_errors.VMSignal.is(returnValue) ? returnValue : void 0,
2609
3440
  lines_executed: Array.from(lines_executed),
2610
- return_value: returnValue
2611
- };
3441
+ return_value: returnValue,
3442
+ variableWrites: state.variableWrites,
3443
+ captureErrors: state.captureErrors
3444
+ }, state);
2612
3445
  } catch (err) {
3446
+ runtime.setInterruptHandler((0, quickjs_emscripten_core.shouldInterruptAfterDeadline)(Date.now() + 1e3));
3447
+ if (isTerminated()) return terminalResult();
2613
3448
  if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
2614
3449
  const reason = signal.reason;
2615
3450
  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);
3451
+ return finalizeMemoryCapture(handleErrorQuickJS(abortError, code, consumer, traces, variables, lines_executed, userCodeStartLine, recordTrace), state);
2617
3452
  }
2618
3453
  await Promise.all(pendingPromises.map(async ({ hostPromise, deferredPromise }) => {
2619
3454
  try {
@@ -2628,8 +3463,13 @@ var QuickJSDriver = class {
2628
3463
  errValue.dispose();
2629
3464
  }
2630
3465
  })).catch(() => {});
2631
- return handleErrorQuickJS(err, code, consumer, traces, variables, lines_executed, userCodeStartLine, ctx.currentToolCall ?? state.currentToolCall);
3466
+ return finalizeMemoryCapture(handleErrorQuickJS(err, code, consumer, traces, variables, lines_executed, userCodeStartLine, recordTrace), state);
2632
3467
  } finally {
3468
+ var _context$VM_PROGRAM_C2;
3469
+ (_context$VM_PROGRAM_C2 = context[VM_PROGRAM_COMPLETE]) === null || _context$VM_PROGRAM_C2 === void 0 || _context$VM_PROGRAM_C2.call(context);
3470
+ for (const { deferredPromise } of pendingPromises) deferredPromise.dispose();
3471
+ for (const getter of variableGetters.values()) getter.dispose();
3472
+ freezeFunction.dispose();
2633
3473
  try {
2634
3474
  vm.dispose();
2635
3475
  } catch {}
@@ -2638,16 +3478,17 @@ var QuickJSDriver = class {
2638
3478
  } catch {}
2639
3479
  }
2640
3480
  }
2641
- async _pumpEventLoop(runtime, vm, pendingPromises, signal, toVmValue, disposeIfNeeded) {
3481
+ async _pumpEventLoop(runtime, vm, pendingPromises, signal, toVmValue, disposeIfNeeded, shouldStopJobs) {
2642
3482
  const maxIterations = 1e3;
2643
3483
  let iteration = 0;
2644
3484
  while (iteration < maxIterations) {
3485
+ if (shouldStopJobs()) break;
2645
3486
  let hasJobs = false;
2646
3487
  const maxJobs = 1e4;
2647
3488
  for (let i = 0; i < maxJobs; i++) {
2648
3489
  var _runtime$executePendi;
2649
3490
  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;
3491
+ if ((pending === void 0 ? 0 : pending.unwrap()) <= 0 || shouldStopJobs()) break;
2651
3492
  hasJobs = true;
2652
3493
  }
2653
3494
  const currentPromises = [...pendingPromises];
@@ -2655,7 +3496,7 @@ var QuickJSDriver = class {
2655
3496
  if (currentPromises.length > 0) {
2656
3497
  if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
2657
3498
  const reason = signal.reason;
2658
- const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3499
+ const abortMessage = describeAbortReason(reason);
2659
3500
  for (const { deferredPromise } of currentPromises) {
2660
3501
  const errValue = vm.newString(abortMessage);
2661
3502
  deferredPromise.reject(errValue);
@@ -2668,7 +3509,7 @@ var QuickJSDriver = class {
2668
3509
  if (signal) {
2669
3510
  abortListener = () => {
2670
3511
  const reason = signal.reason;
2671
- const abortMessage = reason instanceof Error ? `${reason.name}: ${reason.message}` : reason ? String(reason) : "Execution was aborted";
3512
+ const abortMessage = describeAbortReason(reason);
2672
3513
  for (const { deferredPromise } of currentPromises) {
2673
3514
  const errValue = vm.newString(abortMessage);
2674
3515
  deferredPromise.reject(errValue);
@@ -2680,17 +3521,18 @@ var QuickJSDriver = class {
2680
3521
  }
2681
3522
  try {
2682
3523
  await Promise.all(currentPromises.map(async ({ hostPromise, deferredPromise }) => {
2683
- if (signal === null || signal === void 0 ? void 0 : signal.aborted) return;
3524
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || shouldStopJobs()) return;
2684
3525
  try {
2685
3526
  const value = await hostPromise;
2686
- if (signal === null || signal === void 0 ? void 0 : signal.aborted) return;
3527
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || shouldStopJobs()) return;
2687
3528
  const vmValue = toVmValue(value);
2688
3529
  deferredPromise.resolve(vmValue);
2689
3530
  disposeIfNeeded(vmValue);
2690
3531
  } 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)})`);
3532
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || shouldStopJobs()) return;
3533
+ const message = err instanceof Error ? err.message : String(err);
3534
+ const serialized = err instanceof Error ? require_errors.Signals.serializeError(err) : message;
3535
+ const createErrorResult = vm.evalCode(`Object.assign(new Error(${JSON.stringify(message)}), { __llmz_error: ${JSON.stringify(serialized)} })`);
2694
3536
  if ("error" in createErrorResult) {
2695
3537
  const errValue = vm.newString(serialized);
2696
3538
  deferredPromise.reject(errValue);
@@ -2704,9 +3546,10 @@ var QuickJSDriver = class {
2704
3546
  }));
2705
3547
  } finally {
2706
3548
  if (signal && abortListener) signal.removeEventListener("abort", abortListener);
3549
+ if (shouldStopJobs()) currentPromises.forEach(({ deferredPromise }) => deferredPromise.dispose());
2707
3550
  }
2708
- runtime.executePendingJobs();
2709
- if (signal === null || signal === void 0 ? void 0 : signal.aborted) break;
3551
+ if (!shouldStopJobs()) runtime.executePendingJobs();
3552
+ if ((signal === null || signal === void 0 ? void 0 : signal.aborted) || shouldStopJobs()) break;
2710
3553
  }
2711
3554
  if (!hasJobs && pendingPromises.length === 0) break;
2712
3555
  iteration++;
@@ -2714,13 +3557,13 @@ var QuickJSDriver = class {
2714
3557
  if (iteration >= maxIterations) throw new Error("Maximum event loop iterations exceeded");
2715
3558
  }
2716
3559
  };
2717
- function bridgeContextToVM(context, vm, trackedProperties, referenceProperties, toVmValue, disposeIfNeeded, bridgeFunction) {
3560
+ function bridgeContextToVM(context, vm, trackedProperties, referenceProperties, toVmValue, disposeIfNeeded, bridgeFunction, captureValue) {
2718
3561
  for (const [key, value] of Object.entries(context)) {
2719
3562
  const descriptor = Object.getOwnPropertyDescriptor(context, key);
2720
3563
  if (descriptor && (descriptor.get || descriptor.set)) {
2721
3564
  referenceProperties.add(key);
2722
3565
  trackedProperties.add(key);
2723
- bridgeGetterSetter(vm, key, void 0, descriptor, context, toVmValue);
3566
+ bridgeGetterSetter(vm, key, void 0, descriptor, context, toVmValue, captureValue);
2724
3567
  continue;
2725
3568
  }
2726
3569
  if (typeof value === "function") {
@@ -2757,18 +3600,25 @@ function bridgeContextToVM(context, vm, trackedProperties, referenceProperties,
2757
3600
  }
2758
3601
  vm.setProp(vm.global, key, objHandle);
2759
3602
  objHandle.dispose();
2760
- for (const { prop, descriptor } of getterSetterProps) bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue);
3603
+ for (const { prop, descriptor } of getterSetterProps) bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue, captureValue);
3604
+ const missing = value[MISSING_MEMBER];
3605
+ if (missing) {
3606
+ trackedProperties.delete(key);
3607
+ installMemberProxy(vm, key, bridgeFunction(missing));
3608
+ }
2761
3609
  if (Object.isSealed(value)) {
2762
- var _sealResult$error;
2763
3610
  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();
3611
+ if ("error" in sealResult) {
3612
+ var _sealResult$error;
3613
+ (_sealResult$error = sealResult.error) === null || _sealResult$error === void 0 || _sealResult$error.dispose();
3614
+ } else sealResult.value.dispose();
2766
3615
  }
2767
3616
  if (!Object.isExtensible(value)) {
2768
- var _preventResult$error;
2769
3617
  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();
3618
+ if ("error" in preventResult) {
3619
+ var _preventResult$error;
3620
+ (_preventResult$error = preventResult.error) === null || _preventResult$error === void 0 || _preventResult$error.dispose();
3621
+ } else preventResult.value.dispose();
2772
3622
  }
2773
3623
  } else {
2774
3624
  trackedProperties.add(key);
@@ -2778,8 +3628,43 @@ function bridgeContextToVM(context, vm, trackedProperties, referenceProperties,
2778
3628
  }
2779
3629
  }
2780
3630
  }
2781
- function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue) {
2782
- var _result$error2;
3631
+ function installMemberProxy(vm, key, missing) {
3632
+ 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); } }); })");
3633
+ if ("error" in factory) {
3634
+ var _factory$error;
3635
+ (_factory$error = factory.error) === null || _factory$error === void 0 || _factory$error.dispose();
3636
+ throw new Error("Could not create the API member proxy.");
3637
+ }
3638
+ const missingHandle = vm.newFunction("missingMember", missing);
3639
+ const target = vm.getProp(vm.global, key);
3640
+ try {
3641
+ const result = vm.callFunction(factory.value, vm.undefined, target, missingHandle);
3642
+ if ("error" in result) {
3643
+ var _result$error;
3644
+ (_result$error = result.error) === null || _result$error === void 0 || _result$error.dispose();
3645
+ throw new Error("Could not install the API member proxy.");
3646
+ }
3647
+ vm.setProp(vm.global, key, result.value);
3648
+ result.value.dispose();
3649
+ } finally {
3650
+ target.dispose();
3651
+ factory.value.dispose();
3652
+ missingHandle.dispose();
3653
+ }
3654
+ }
3655
+ /** Preserve readable guest messages and host error types without serializing Error as a string. */
3656
+ function guestError(vm, cause) {
3657
+ const error = cause instanceof Error ? cause : new Error(String(cause));
3658
+ const handle = vm.newError({
3659
+ name: error.name,
3660
+ message: error.message
3661
+ });
3662
+ const details = vm.newString(require_errors.Signals.serializeError(error));
3663
+ vm.setProp(handle, "__llmz_error", details);
3664
+ details.dispose();
3665
+ return handle;
3666
+ }
3667
+ function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue, captureValue) {
2783
3668
  const target = prop ? `${key}` : "globalThis";
2784
3669
  const propName = prop ?? key;
2785
3670
  const prefix = prop ? `${key}_${prop}` : key;
@@ -2787,9 +3672,9 @@ function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue) {
2787
3672
  if (descriptor.get) {
2788
3673
  const getterBridge = vm.newFunction(`get_${propName}`, () => {
2789
3674
  try {
2790
- return toVmValue(prop ? context[key][prop] : context[key]);
3675
+ return toVmValue(prop ? context[key][prop] : context[key], true);
2791
3676
  } catch (err) {
2792
- throw new Error(err instanceof Error ? err.message : String(err));
3677
+ return { error: guestError(vm, err) };
2793
3678
  }
2794
3679
  });
2795
3680
  const getterName = `__getter_${prefix}__`;
@@ -2801,12 +3686,12 @@ function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue) {
2801
3686
  if (descriptor.set) {
2802
3687
  const setterBridge = vm.newFunction(`set_${propName}`, (valueHandle) => {
2803
3688
  try {
2804
- const jsValue = vm.dump(valueHandle);
3689
+ const jsValue = captureValue(valueHandle);
2805
3690
  if (prop) context[key][prop] = jsValue;
2806
3691
  else context[key] = jsValue;
2807
3692
  return vm.undefined;
2808
3693
  } catch (err) {
2809
- throw new Error(err instanceof Error ? err.message : String(err));
3694
+ return { error: guestError(vm, err) };
2810
3695
  }
2811
3696
  });
2812
3697
  const setterName = `__setter_${prefix}__`;
@@ -2823,31 +3708,131 @@ function bridgeGetterSetter(vm, key, prop, descriptor, context, toVmValue) {
2823
3708
  });
2824
3709
  `;
2825
3710
  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();
3711
+ if ("error" in result) {
3712
+ var _result$error2;
3713
+ (_result$error2 = result.error) === null || _result$error2 === void 0 || _result$error2.dispose();
3714
+ } else result.value.dispose();
2828
3715
  }
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;
3716
+ function setupMemoryCapture(vm) {
3717
+ const installed = vm.evalCode(`
3718
+ globalThis.__llmz_encode_memory = function encode(value, seen = new Set()) {
3719
+ if (value === undefined) {
3720
+ return ['undefined'];
3721
+ }
3722
+ if (Object.is(value, -0)) {
3723
+ return ['negative-zero'];
3724
+ }
3725
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') {
3726
+ return ['value', value];
3727
+ }
3728
+ if (typeof value === 'number' && Number.isFinite(value)) {
3729
+ return ['value', value];
3730
+ }
3731
+ if (!value || typeof value !== 'object') {
3732
+ throw new Error('Unsupported memory value: ' + typeof value);
3733
+ }
3734
+ if (seen.has(value)) {
3735
+ throw new Error('Cyclic values cannot be retained in memory');
3736
+ }
3737
+ const plainObject = Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null;
3738
+ if (!Array.isArray(value) && !plainObject) {
3739
+ throw new Error('Only plain objects and arrays can be retained in memory');
3740
+ }
3741
+ if (Object.getOwnPropertySymbols(value).length) {
3742
+ throw new Error('Symbol properties cannot be retained in memory');
3743
+ }
3744
+ seen.add(value);
3745
+ try {
3746
+ if (Array.isArray(value)) {
3747
+ if (Object.keys(value).length !== value.length) {
3748
+ throw new Error('Sparse arrays and custom array properties are unsupported');
3749
+ }
3750
+ const items = [];
3751
+ for (let index = 0; index < value.length; index++) {
3752
+ const descriptor = Object.getOwnPropertyDescriptor(value, index);
3753
+ if (!descriptor || descriptor.get || descriptor.set) {
3754
+ throw new Error('Array accessor properties cannot be retained in memory');
3755
+ }
3756
+ items.push(encode(descriptor.value, seen));
3757
+ }
3758
+ return ['array', items];
3759
+ }
3760
+ const entries = [];
3761
+ for (const [key, descriptor] of Object.entries(Object.getOwnPropertyDescriptors(value))) {
3762
+ if (descriptor.get || descriptor.set || !descriptor.enumerable) {
3763
+ throw new Error('Accessor and non-enumerable properties cannot be retained in memory');
3764
+ }
3765
+ entries.push([key, encode(descriptor.value, seen)]);
3766
+ }
3767
+ return ['object', entries];
3768
+ } finally {
3769
+ seen.delete(value);
3770
+ }
3771
+ };
3772
+ `);
3773
+ if ("error" in installed) {
3774
+ const error = vm.dump(installed.error);
3775
+ installed.error.dispose();
3776
+ throw new Error(error.message);
3777
+ }
3778
+ installed.value.dispose();
3779
+ return (handle) => {
3780
+ const encoder = vm.getProp(vm.global, "__llmz_encode_memory");
2833
3781
  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;
3782
+ const encoded = vm.callFunction(encoder, vm.undefined, handle);
3783
+ if ("error" in encoded) {
3784
+ const error = vm.dump(encoded.error);
3785
+ encoded.error.dispose();
3786
+ throw new Error(error.message);
2840
3787
  }
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]]";
3788
+ try {
3789
+ return require_quickjs_variant.decodeMemoryValue(vm.dump(encoded.value));
3790
+ } finally {
3791
+ encoded.value.dispose();
3792
+ }
3793
+ } finally {
3794
+ encoder.dispose();
2847
3795
  }
3796
+ };
3797
+ }
3798
+ function setupVariableTrackingBridge(vm, variables, getters, state, capture) {
3799
+ const tracker = vm.newFunction(Identifiers.VariableTrackingFnIdentifier, (nameHandle, getterHandle, resultHandle, kindHandle) => {
3800
+ var _getters$get;
3801
+ const name = vm.getString(nameHandle);
3802
+ if (NO_TRACKING.includes(name) || !state.memoryNames.has(name)) return (resultHandle === null || resultHandle === void 0 ? void 0 : resultHandle.dup()) ?? vm.undefined;
3803
+ const kind = kindHandle ? vm.dump(kindHandle) : "assignment";
3804
+ if (kind !== "initialize" && kind !== "read") state.variableWrites.push({
3805
+ name,
3806
+ timestamp: Date.now(),
3807
+ kind: kind === "mutation" ? "mutation" : "assignment"
3808
+ });
3809
+ (_getters$get = getters.get(name)) === null || _getters$get === void 0 || _getters$get.dispose();
3810
+ getters.set(name, getterHandle.dup());
3811
+ variables[name] = () => {
3812
+ try {
3813
+ const result = vm.callFunction(getters.get(name), vm.undefined);
3814
+ if ("error" in result) {
3815
+ const error = vm.dump(result.error);
3816
+ result.error.dispose();
3817
+ throw new Error(error.message);
3818
+ }
3819
+ try {
3820
+ return capture(result.value);
3821
+ } finally {
3822
+ result.value.dispose();
3823
+ }
3824
+ } catch (err) {
3825
+ if (!state.captureErrors.some((entry) => entry.name === name)) state.captureErrors.push({
3826
+ name,
3827
+ reason: err instanceof Error ? err.message : String(err)
3828
+ });
3829
+ return;
3830
+ }
3831
+ };
3832
+ return (resultHandle === null || resultHandle === void 0 ? void 0 : resultHandle.dup()) ?? vm.undefined;
2848
3833
  });
2849
- vm.setProp(vm.global, require_compiler.Identifiers.VariableTrackingFnIdentifier, varTrackFnHandle);
2850
- varTrackFnHandle.dispose();
3834
+ vm.setProp(vm.global, Identifiers.VariableTrackingFnIdentifier, tracker);
3835
+ tracker.dispose();
2851
3836
  }
2852
3837
  function buildScriptCode(transformedCode) {
2853
3838
  return `
@@ -2866,12 +3851,19 @@ ${transformedCode}
2866
3851
  globalThis.__llmz_result = await __fn__();
2867
3852
  globalThis.__llmz_result_set = true;
2868
3853
  } catch (err) {
2869
- globalThis.__llmz_error = typeof err === 'string' ? err : String(err.message || err || '');
3854
+ globalThis.__llmz_error = typeof err === 'string' ? err : String(err.__llmz_error || err.message || err || '');
3855
+ globalThis.__llmz_error_name = typeof err?.name === 'string' ? err.name : 'Error';
2870
3856
  globalThis.__llmz_error_stack = '' + (err.stack || '');
3857
+ } finally {
3858
+ __llmz_program_complete();
2871
3859
  }
2872
3860
  })();
2873
3861
  `.trim();
2874
3862
  }
3863
+ function describeAbortReason(reason) {
3864
+ if (reason instanceof Error) return `${reason.name}: ${reason.message}`;
3865
+ return reason ? String(reason) : "Execution was aborted";
3866
+ }
2875
3867
  //#endregion
2876
3868
  //#region src/vm/index.ts
2877
3869
  const MAX_VM_EXECUTION_TIME = 6e4;
@@ -2883,27 +3875,20 @@ const isWorkerd = () => {
2883
3875
  var _navigator;
2884
3876
  return typeof navigator !== "undefined" && ((_navigator = navigator) === null || _navigator === void 0 ? void 0 : _navigator.userAgent) === "Cloudflare-Workers";
2885
3877
  };
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) {
3878
+ async function runAsyncFunction(context, code, traces = [], signal = null, timeout = MAX_VM_EXECUTION_TIME, memoryNames, recordTrace = (trace) => {
3879
+ traces.push(trace);
3880
+ }) {
2896
3881
  const transformed = (() => {
2897
3882
  try {
2898
- return require_compiler.compile(code);
3883
+ return compile(code);
2899
3884
  } catch (err) {
2900
- traces.push({
3885
+ recordTrace({
2901
3886
  type: "invalid_code_exception",
2902
3887
  message: (err === null || err === void 0 ? void 0 : err.message) ?? "Unknown error",
2903
3888
  code,
2904
3889
  started_at: Date.now()
2905
3890
  });
2906
- throw new require_errors.InvalidCodeError(err.message, code);
3891
+ throw require_errors.isLLMzError(err) ? err : new require_errors.InvalidCodeError(err.message, code, { cause: err });
2907
3892
  }
2908
3893
  })();
2909
3894
  const lines_executed = /* @__PURE__ */ new Map();
@@ -2917,22 +3902,21 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
2917
3902
  file: transformed.map.file
2918
3903
  });
2919
3904
  context ??= {};
3905
+ memoryNames ??= Object.keys(context).filter((name) => {
3906
+ if (name.startsWith("__") || require_quickjs_variant.RESERVED_RUNTIME_NAMES.has(name)) return false;
3907
+ try {
3908
+ require_quickjs_variant.cloneMemoryValue(context[name]);
3909
+ return true;
3910
+ } catch {
3911
+ return false;
3912
+ }
3913
+ });
3914
+ memoryNames = memoryNames.filter((name) => !transformed.variables.has(name) && !require_quickjs_variant.RESERVED_RUNTIME_NAMES.has(name) && !name.startsWith("__"));
2920
3915
  for (const name of Array.from(transformed.variables)) delete context[name];
2921
- let driver;
3916
+ let driver = new NodeDriver();
2922
3917
  if (useQuickJS()) try {
3918
+ await loadQuickJSModule();
2923
3919
  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
3920
  } catch (quickjsError) {
2937
3921
  const variant = require_quickjs_variant.getQuickJSVariant();
2938
3922
  const debugInfo = {
@@ -2949,7 +3933,7 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
2949
3933
  console.error("QuickJS failed to load and the node driver is unavailable on Cloudflare Workers.");
2950
3934
  console.error("Debug info:", JSON.stringify(debugInfo, null, 2));
2951
3935
  if (quickjsError instanceof Error) {
2952
- quickjsError.debugInfo = debugInfo;
3936
+ Object.assign(quickjsError, { debugInfo });
2953
3937
  throw quickjsError;
2954
3938
  }
2955
3939
  throw new Error(`QuickJS failed to load on Cloudflare Workers: ${debugInfo.error}`);
@@ -2958,20 +3942,24 @@ async function runAsyncFunction(context, code, traces = [], signal = null, timeo
2958
3942
  console.warn("Error:", (quickjsError === null || quickjsError === void 0 ? void 0 : quickjsError.message) || quickjsError);
2959
3943
  console.warn("Debug info:", JSON.stringify(debugInfo, null, 2));
2960
3944
  }
2961
- driver = new NodeDriver();
2962
3945
  return await driver.execute({
2963
3946
  transformed,
3947
+ memoryNames,
2964
3948
  consumer,
2965
3949
  context,
2966
3950
  traces,
3951
+ recordTrace,
2967
3952
  signal,
2968
3953
  timeout,
2969
3954
  code,
2970
3955
  lines_executed,
2971
- variables,
2972
- currentToolCall: void 0
3956
+ variables
2973
3957
  });
2974
3958
  }
2975
3959
  //#endregion
3960
+ exports.VM_ON_ERROR = VM_ON_ERROR;
3961
+ exports.VM_PROGRAM_COMPLETE = VM_PROGRAM_COMPLETE;
3962
+ exports.VM_TERMINATION = VM_TERMINATION;
3963
+ exports.compile = compile;
2976
3964
  exports.runAsyncFunction = runAsyncFunction;
2977
- exports.warmupVM = warmupVM;
3965
+ exports.withMissingMember = withMissingMember;