llmz 0.9.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (238) hide show
  1. package/DOCS.md +232 -1794
  2. package/ERRORS.md +101 -0
  3. package/README.md +96 -582
  4. package/dist/chat/chat.d.ts +63 -0
  5. package/dist/chat/component.d.ts +31 -0
  6. package/dist/chat/component.default.d.ts +58 -0
  7. package/dist/chat/response.d.ts +15 -0
  8. package/dist/compiler/compiler.d.ts +2 -7
  9. package/dist/compiler/plugins/dynamic-code.d.ts +7 -0
  10. package/dist/compiler/plugins/replace-comment.d.ts +2 -3
  11. package/dist/compiler/plugins/return-async.d.ts +5 -4
  12. package/dist/compiler/plugins/termination.d.ts +8 -0
  13. package/dist/compiler/plugins/tool-resolution.d.ts +4 -0
  14. package/dist/compiler/plugins/variable-extraction.d.ts +2 -8
  15. package/dist/component-CMFoCHyu.cjs +649 -0
  16. package/dist/component-DncqP4fB.js +614 -0
  17. package/dist/context.d.ts +71 -378
  18. package/dist/custom-client-C-WXvLD9.js +1655 -0
  19. package/dist/custom-client-Cgt9_0r1.cjs +1732 -0
  20. package/dist/custom-client.d.ts +12 -2
  21. package/dist/errors/catalog.d.ts +294 -0
  22. package/dist/errors/hooks.d.ts +2 -0
  23. package/dist/errors-C6ppQUZX.cjs +893 -0
  24. package/dist/errors-Crk5P8jo.js +636 -0
  25. package/dist/errors.d.ts +24 -36
  26. package/dist/execute-CiYvPs5Q.js +2061 -0
  27. package/dist/execute-DTTfacsi.cjs +2062 -0
  28. package/dist/{exit-DUM96DN1.cjs → exit-BOtKWPuT.cjs} +38 -28
  29. package/dist/{exit-CDdxDBRT.js → exit-DMPwCSba.js} +37 -27
  30. package/dist/exit.d.ts +19 -16
  31. package/dist/index.cjs +177 -1237
  32. package/dist/index.d.ts +25 -28
  33. package/dist/index.js +137 -1213
  34. package/dist/index.workerd.js +8974 -11145
  35. package/dist/inspect.d.ts +18 -4
  36. package/dist/inspection.d.ts +40 -0
  37. package/dist/native-0bq5ATZM.cjs +212 -0
  38. package/dist/native-n_718Z-T.js +177 -0
  39. package/dist/objects.d.ts +2 -57
  40. package/dist/prompts/native.d.ts +2 -0
  41. package/dist/prompts/prompt.d.ts +10 -101
  42. package/dist/quickjs-variant-21IO97PF.cjs +1080 -0
  43. package/dist/quickjs-variant-CtuGagsb.js +985 -0
  44. package/dist/result.d.ts +30 -861
  45. package/dist/runtime/execute.d.ts +3 -2
  46. package/dist/runtime/execution-activity.d.ts +11 -0
  47. package/dist/runtime/execution-diagnostics.d.ts +11 -0
  48. package/dist/runtime/execution-report.d.ts +51 -0
  49. package/dist/runtime/fixtures/chat.d.ts +8 -0
  50. package/dist/runtime/fixtures/long-search.d.ts +1 -1
  51. package/dist/runtime/fixtures/native-client.d.ts +33 -0
  52. package/dist/runtime/fixtures/protocol-languages.d.ts +1 -1
  53. package/dist/runtime/forced-inspection.d.ts +13 -0
  54. package/dist/runtime/forced-inspection.test.d.ts +1 -0
  55. package/dist/runtime/generate.d.ts +23 -20
  56. package/dist/runtime/generate.test.d.ts +1 -0
  57. package/dist/runtime/hook-provenance.test.d.ts +1 -0
  58. package/dist/runtime/inspection-hook.test.d.ts +1 -0
  59. package/dist/runtime/inspection-values.d.ts +14 -0
  60. package/dist/runtime/inspection-values.test.d.ts +1 -0
  61. package/dist/runtime/interruption-control-flow.test.d.ts +1 -0
  62. package/dist/runtime/interruption-settings.test.d.ts +1 -0
  63. package/dist/runtime/javascript-api.d.ts +62 -0
  64. package/dist/runtime/javascript-api.test.d.ts +1 -0
  65. package/dist/runtime/native-review.test.d.ts +1 -0
  66. package/dist/runtime/native-tools.d.ts +18 -0
  67. package/dist/runtime/native-tools.test.d.ts +1 -0
  68. package/dist/runtime/object-memory.test.d.ts +1 -0
  69. package/dist/runtime/single-tool.test.d.ts +1 -0
  70. package/dist/runtime/think-signal.test.d.ts +1 -0
  71. package/dist/runtime/token-budget.d.ts +22 -0
  72. package/dist/runtime/token-budget.test.d.ts +1 -0
  73. package/dist/runtime/tool-wrapper.d.ts +6 -5
  74. package/dist/runtime/traces.test.d.ts +1 -0
  75. package/dist/runtime/truncation.test.d.ts +1 -0
  76. package/dist/runtime/types.d.ts +47 -31
  77. package/dist/runtime/variable-recovery.test.d.ts +1 -0
  78. package/dist/runtime/vm-context.d.ts +6 -1
  79. package/dist/runtime/worker-completion.test.d.ts +1 -0
  80. package/dist/runtime-names.d.ts +4 -0
  81. package/dist/schema-CXlnbb3n.cjs +68 -0
  82. package/dist/schema-GE4ISPCR.js +45 -0
  83. package/dist/schema.d.ts +10 -0
  84. package/dist/schema.test.d.ts +1 -0
  85. package/dist/session/compactor.d.ts +51 -0
  86. package/dist/session/compactor.test.d.ts +1 -0
  87. package/dist/session/history.d.ts +36 -0
  88. package/dist/session/history.test.d.ts +1 -0
  89. package/dist/session/json.d.ts +3 -0
  90. package/dist/session/json.test.d.ts +1 -0
  91. package/dist/session/memory-codec.d.ts +9 -0
  92. package/dist/session/memory-codec.test.d.ts +1 -0
  93. package/dist/session/memory-render.d.ts +15 -0
  94. package/dist/session/memory-render.test.d.ts +1 -0
  95. package/dist/session/memory.d.ts +112 -0
  96. package/dist/session/memory.test.d.ts +1 -0
  97. package/dist/session/messages.d.ts +19 -0
  98. package/dist/session/messages.test.d.ts +1 -0
  99. package/dist/session/serialization.d.ts +36 -0
  100. package/dist/session/serialization.test.d.ts +1 -0
  101. package/dist/session/session-memory.test.d.ts +1 -0
  102. package/dist/session/session.d.ts +121 -0
  103. package/dist/session/session.test.d.ts +1 -0
  104. package/dist/session/speaker.test.d.ts +1 -0
  105. package/dist/{transcript.d.ts → session/transcript.d.ts} +4 -8
  106. package/dist/session/transcript.test.d.ts +1 -0
  107. package/dist/{tool-Bv8N4IPj.js → tool-DstssiAs.js} +144 -92
  108. package/dist/{tool-Dy6AJpJH.cjs → tool-_wK9hQOb.cjs} +146 -94
  109. package/dist/tool.d.ts +25 -17
  110. package/dist/truncate-BEKbdo3t.js +79 -0
  111. package/dist/truncate-uomAMGPs.cjs +102 -0
  112. package/dist/truncate.d.ts +24 -0
  113. package/dist/truncate.test.d.ts +1 -0
  114. package/dist/types.d.ts +33 -9
  115. package/dist/{typings-3lsqCbkn.cjs → typings-BA_XxAcY.cjs} +38 -193
  116. package/dist/{typings-CrBa7Tyy.js → typings-BEVDvtuk.js} +38 -175
  117. package/dist/typings-formatter.d.ts +1 -1
  118. package/dist/typings.d.ts +3 -0
  119. package/dist/{uniq-BYQ7GWwb.js → uniq-DfUeSNaX.js} +2 -2
  120. package/dist/{uniq-G872RWmE.cjs → uniq-DiXgysNV.cjs} +6 -18
  121. package/dist/{_baseIteratee-P_firB7b.js → utils-BOFzb8Ok.js} +1134 -16
  122. package/dist/{_baseIteratee-CF4qP2a8.cjs → utils-CTlsXvdj.cjs} +1281 -84
  123. package/dist/vm/drivers/node.d.ts +1 -1
  124. package/dist/vm/drivers/quickjs.d.ts +1 -1
  125. package/dist/vm/errors.d.ts +4 -4
  126. package/dist/vm/index.d.ts +3 -4
  127. package/dist/vm/instrument.d.ts +14 -6
  128. package/dist/vm/member-proxy.d.ts +4 -0
  129. package/dist/vm/member-proxy.test.d.ts +1 -0
  130. package/dist/vm/memory.test.d.ts +1 -0
  131. package/dist/vm/return-semantics.test.d.ts +1 -0
  132. package/dist/vm/types.d.ts +20 -3
  133. package/dist/{vm-BLsHw1da.js → vm-C7SfutHn.js} +1187 -180
  134. package/dist/{vm-D6s1zF6M.cjs → vm-gmekHc0i.cjs} +1221 -207
  135. package/package.json +13 -6
  136. package/dist/_baseForOwn-BfWDTL8L.cjs +0 -53
  137. package/dist/_baseForOwn-CFhWe_W6.js +0 -48
  138. package/dist/_getPrototype-CG7Dxrrz.js +0 -6
  139. package/dist/_getPrototype-DQDlNVVM.cjs +0 -10
  140. package/dist/_overArg-C5Hy7oCi.cjs +0 -196
  141. package/dist/_overArg-CRYbj1NH.js +0 -155
  142. package/dist/chat.d.ts +0 -401
  143. package/dist/common-BlRFtdf2.js +0 -807
  144. package/dist/common-BnvrDnIT.cjs +0 -860
  145. package/dist/compiler/plugins/track-tool-calls.d.ts +0 -33
  146. package/dist/compiler-C-OI9sim.cjs +0 -547
  147. package/dist/compiler-CW1VjQsn.js +0 -473
  148. package/dist/component-C6Agl2ns.cjs +0 -73
  149. package/dist/component-DGG7d_Mz.js +0 -44
  150. package/dist/component.d.ts +0 -88
  151. package/dist/component.default.d.ts +0 -278
  152. package/dist/custom-client-ChuZ63zp.js +0 -2658
  153. package/dist/custom-client-DAsGRnYc.cjs +0 -2729
  154. package/dist/dual-modes-DDkoCp3R.js +0 -3006
  155. package/dist/dual-modes-DPXiuvNe.cjs +0 -3090
  156. package/dist/errors-C962uJdS.cjs +0 -220
  157. package/dist/errors-Cg1G0Awu.js +0 -161
  158. package/dist/example-format.d.ts +0 -8
  159. package/dist/example.d.ts +0 -45
  160. package/dist/execute-BWcdv9so.js +0 -1059
  161. package/dist/execute-DM2-7y86.cjs +0 -1060
  162. package/dist/exit-parser.d.ts +0 -39
  163. package/dist/handlers.d.ts +0 -10
  164. package/dist/hoist.d.ts +0 -2
  165. package/dist/isEmpty-BhJRCqIF.js +0 -52
  166. package/dist/isEmpty-LY533Wmh.cjs +0 -57
  167. package/dist/isPlainObject-CSxXVKCk.cjs +0 -56
  168. package/dist/isPlainObject-D39AzPO2.js +0 -51
  169. package/dist/jsx-CIgdGGVs.js +0 -52
  170. package/dist/jsx-owqxrquU.cjs +0 -75
  171. package/dist/jsx.d.ts +0 -11
  172. package/dist/message-stream/index.d.ts +0 -9
  173. package/dist/message-stream/instructions.d.ts +0 -30
  174. package/dist/message-stream/normalizer.d.ts +0 -21
  175. package/dist/message-stream/parser.d.ts +0 -89
  176. package/dist/message-stream/registry.d.ts +0 -14
  177. package/dist/message-stream/replayable.d.ts +0 -27
  178. package/dist/message-stream/response-parser.d.ts +0 -24
  179. package/dist/message-stream/sanitize.d.ts +0 -10
  180. package/dist/message-stream/stream.d.ts +0 -54
  181. package/dist/message-stream/types.d.ts +0 -97
  182. package/dist/message-stream/validator.d.ts +0 -23
  183. package/dist/prompts/chat-mode/protocol.d.ts +0 -2
  184. package/dist/prompts/chat-mode/system.d.ts +0 -2
  185. package/dist/prompts/chat-mode/system.md.d.ts +0 -2
  186. package/dist/prompts/chat-mode/user.d.ts +0 -2
  187. package/dist/prompts/chat-mode/user.md.d.ts +0 -2
  188. package/dist/prompts/code-examples.d.ts +0 -2
  189. package/dist/prompts/common.d.ts +0 -7
  190. package/dist/prompts/dual-modes.d.ts +0 -2
  191. package/dist/prompts/execution-history.d.ts +0 -6
  192. package/dist/prompts/execution-state.d.ts +0 -3
  193. package/dist/prompts/protocol-basics.d.ts +0 -5
  194. package/dist/prompts/protocol.d.ts +0 -31
  195. package/dist/prompts/worker-mode/protocol.d.ts +0 -2
  196. package/dist/prompts/worker-mode/system.d.ts +0 -2
  197. package/dist/prompts/worker-mode/system.md.d.ts +0 -2
  198. package/dist/prompts/worker-mode/user.d.ts +0 -2
  199. package/dist/prompts/worker-mode/user.md.d.ts +0 -2
  200. package/dist/quickjs-variant-BYhMBpwU.js +0 -45
  201. package/dist/quickjs-variant-CsIwTVFC.cjs +0 -56
  202. package/dist/rolldown-runtime-EAsCxrDo.js +0 -14
  203. package/dist/runtime/fixtures/qwen-protocol-failures.d.ts +0 -29
  204. package/dist/runtime/interpret-result.d.ts +0 -22
  205. package/dist/snapshots.d.ts +0 -249
  206. package/dist/stack-traces-BIE_5Xwf.js +0 -21
  207. package/dist/stack-traces-ntw_qhoy.cjs +0 -26
  208. package/dist/truncator-CLkouTCO.cjs +0 -276
  209. package/dist/truncator-DZqEqnpD.js +0 -253
  210. package/dist/truncator.d.ts +0 -118
  211. package/dist/utils-3ESwP3yg.cjs +0 -1075
  212. package/dist/utils-UBeAFeEI.js +0 -950
  213. /package/dist/{citations.d.ts → chat/citations.d.ts} +0 -0
  214. /package/dist/{citations.test.d.ts → chat/citations.test.d.ts} +0 -0
  215. /package/dist/{component.default.test.d.ts → chat/component.default.test.d.ts} +0 -0
  216. /package/dist/{compiler/plugins/track-tool-calls.test.d.ts → chat/component.test.d.ts} +0 -0
  217. /package/dist/{example.test.d.ts → chat/response.test.d.ts} +0 -0
  218. /package/dist/{exit-parser.test.d.ts → compiler/plugins/dynamic-code.test.d.ts} +0 -0
  219. /package/dist/{handlers.test.d.ts → compiler/plugins/tool-resolution.test.d.ts} +0 -0
  220. /package/dist/{hoist.test.d.ts → errors/catalog.test.d.ts} +0 -0
  221. /package/dist/{message-stream/instructions.test.d.ts → exit.test.d.ts} +0 -0
  222. /package/dist/{message-stream/normalizer.test.d.ts → inspection.test.d.ts} +0 -0
  223. /package/dist/{message-stream/parser.test.d.ts → prompts/native.test.d.ts} +0 -0
  224. /package/dist/{message-stream/response-parser.test.d.ts → result.test.d.ts} +0 -0
  225. /package/dist/{message-stream/stream.test.d.ts → runtime/chat-completion.test.d.ts} +0 -0
  226. /package/dist/{message-stream/validator.test.d.ts → runtime/chat-delivery.test.d.ts} +0 -0
  227. /package/dist/{prompts/adherence.test.d.ts → runtime/chat-last-speaker.test.d.ts} +0 -0
  228. /package/dist/{prompts/catalogue-examples.test.d.ts → runtime/compatibility-regressions.test.d.ts} +0 -0
  229. /package/dist/{prompts/code-examples.test.d.ts → runtime/context-registration.test.d.ts} +0 -0
  230. /package/dist/{prompts/common.test.d.ts → runtime/empty-completion.test.d.ts} +0 -0
  231. /package/dist/{prompts/concrete-patterns.test.d.ts → runtime/error-recovery.test.d.ts} +0 -0
  232. /package/dist/{prompts/long-search.test.d.ts → runtime/errors.test.d.ts} +0 -0
  233. /package/dist/{prompts/protocol-simple.test.d.ts → runtime/execution-activity.test.d.ts} +0 -0
  234. /package/dist/{prompts/protocol.test.d.ts → runtime/execution-diagnostics.test.d.ts} +0 -0
  235. /package/dist/{prompts/sections.test.d.ts → runtime/execution-report.test.d.ts} +0 -0
  236. /package/dist/runtime/{interpret-result.test.d.ts → execution-safety.test.d.ts} +0 -0
  237. /package/dist/{transcript.test.d.ts → runtime/exit-control-flow.test.d.ts} +0 -0
  238. /package/dist/{truncator.test.d.ts → runtime/fixtures/long-search.test.d.ts} +0 -0
@@ -0,0 +1,2062 @@
1
+ const require_utils = require("./utils-CTlsXvdj.cjs");
2
+ const require_errors = require("./errors-C6ppQUZX.cjs");
3
+ const require_component = require("./component-CMFoCHyu.cjs");
4
+ const require_schema = require("./schema-CXlnbb3n.cjs");
5
+ const require_truncate = require("./truncate-uomAMGPs.cjs");
6
+ const require_quickjs_variant = require("./quickjs-variant-21IO97PF.cjs");
7
+ const require_typings = require("./typings-BA_XxAcY.cjs");
8
+ const require_custom_client = require("./custom-client-Cgt9_0r1.cjs");
9
+ const require_native = require("./native-0bq5ATZM.cjs");
10
+ const require_vm = require("./vm-gmekHc0i.cjs");
11
+ let _bpinternal_zui = require("@bpinternal/zui");
12
+ let ulid = require("ulid");
13
+ let _botpress_cognitive = require("@botpress/cognitive");
14
+ let _botpress_client = require("@botpress/client");
15
+ let ms = require("ms");
16
+ ms = require_utils.__toESM(ms, 1);
17
+ //#region ../../node_modules/.pnpm/lodash-es@4.17.21/node_modules/lodash-es/isEqual.js
18
+ /**
19
+ * Performs a deep comparison between two values to determine if they are
20
+ * equivalent.
21
+ *
22
+ * **Note:** This method supports comparing arrays, array buffers, booleans,
23
+ * date objects, error objects, maps, numbers, `Object` objects, regexes,
24
+ * sets, strings, symbols, and typed arrays. `Object` objects are compared
25
+ * by their own, not inherited, enumerable properties. Functions and DOM
26
+ * nodes are compared by strict equality, i.e. `===`.
27
+ *
28
+ * @static
29
+ * @memberOf _
30
+ * @since 0.1.0
31
+ * @category Lang
32
+ * @param {*} value The value to compare.
33
+ * @param {*} other The other value to compare.
34
+ * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
35
+ * @example
36
+ *
37
+ * var object = { 'a': 1 };
38
+ * var other = { 'a': 1 };
39
+ *
40
+ * _.isEqual(object, other);
41
+ * // => true
42
+ *
43
+ * object === other;
44
+ * // => false
45
+ */
46
+ function isEqual(value, other) {
47
+ return require_utils.baseIsEqual(value, other);
48
+ }
49
+ //#endregion
50
+ //#region src/abort-signal.ts
51
+ /**
52
+ * Creates a new AbortController that aborts when any of the provided signals abort.
53
+ * This is useful for combining multiple abort conditions (e.g., user cancellation, timeout, parent operation abort).
54
+ *
55
+ * @param signals - Array of AbortSignals to listen to. Undefined/null signals are ignored.
56
+ * @returns A new AbortController that will abort if any input signal aborts
57
+ *
58
+ * @example
59
+ * ```typescript
60
+ * const userController = new AbortController()
61
+ * const timeoutController = new AbortController()
62
+ *
63
+ * // Create a joined controller that aborts if either signal aborts
64
+ * const joinedController = createJoinedAbortController([
65
+ * userController.signal,
66
+ * timeoutController.signal
67
+ * ])
68
+ *
69
+ * // Use the joined signal in operations
70
+ * await fetch('/api/data', { signal: joinedController.signal })
71
+ * ```
72
+ */
73
+ function createJoinedAbortController(signals) {
74
+ const controller = new AbortController();
75
+ const validSignals = signals.filter((signal) => signal != null);
76
+ if (validSignals.length === 0) return controller;
77
+ for (const signal of validSignals) if (signal.aborted) {
78
+ controller.abort(signal.reason);
79
+ return controller;
80
+ }
81
+ const abortListeners = [];
82
+ for (const signal of validSignals) {
83
+ const listener = () => {
84
+ controller.abort(signal.reason);
85
+ cleanup();
86
+ };
87
+ signal.addEventListener("abort", listener);
88
+ abortListeners.push(() => signal.removeEventListener("abort", listener));
89
+ }
90
+ const cleanup = () => {
91
+ abortListeners.forEach((removeListener) => removeListener());
92
+ };
93
+ controller.signal.addEventListener("abort", cleanup, { once: true });
94
+ return controller;
95
+ }
96
+ //#endregion
97
+ //#region src/errors/hooks.ts
98
+ /** Hooks may reject an iteration to request a correction; explicit critical errors still stop execution. */
99
+ async function callHook(callback) {
100
+ try {
101
+ return await callback();
102
+ } catch (cause) {
103
+ if (require_errors.isLLMzError(cause) || require_errors.VMSignal.is(cause)) throw cause;
104
+ throw new require_errors.HookError(cause instanceof Error ? cause.message : String(cause), { cause });
105
+ }
106
+ }
107
+ //#endregion
108
+ //#region src/runtime/execution-activity.ts
109
+ const MAX_ENTRIES = 20;
110
+ const PAYLOAD_PREVIEW_TOKENS = 80;
111
+ const ERROR_PREVIEW_TOKENS = 60;
112
+ const NAME_PREVIEW_TOKENS = 16;
113
+ /** Collect recorded operations, excluding ordinary assistant text delivery. */
114
+ function getExecutionActivity(iteration) {
115
+ return {
116
+ calls: iteration.traces.filter((trace) => trace.type === "tool_call"),
117
+ deliveries: iteration.traces.filter((trace) => trace.type === "message_delivery" && !!trace.message_id)
118
+ };
119
+ }
120
+ function renderToolCalls(activity, includeRecoveryValues = false, inspector = require_quickjs_variant.createInspector(), identity = {}) {
121
+ if (!activity.calls.length) return;
122
+ const lines = activity.calls.slice(0, MAX_ENTRIES).map((call) => {
123
+ const name = call.object ? `${call.object}.${call.tool_name}` : call.tool_name;
124
+ const outcome = getToolOutcome(call);
125
+ const detailsIdentity = {
126
+ ...identity,
127
+ tool: call.tool_name,
128
+ object: call.object
129
+ };
130
+ const input = call.input === void 0 ? "" : inspector(call.input, {
131
+ purpose: "tool-input",
132
+ maxTokens: PAYLOAD_PREVIEW_TOKENS,
133
+ compact: true,
134
+ identity: detailsIdentity
135
+ });
136
+ const details = [`- ${inspector(name, {
137
+ purpose: "name",
138
+ maxTokens: NAME_PREVIEW_TOKENS,
139
+ identity: detailsIdentity
140
+ })}(${input}): ${outcome}`];
141
+ if (outcome === "interrupted") {
142
+ const reason = getInterruption(call).reason;
143
+ details.push(`pending; ${errorPreview(reason, inspector, detailsIdentity)}`);
144
+ } else if (!call.success) details.push(`error: ${errorPreview(call.error, inspector, detailsIdentity)}`);
145
+ else if (includeRecoveryValues) details.push(`returned ${inspector(call.output, {
146
+ purpose: "tool-output",
147
+ maxTokens: PAYLOAD_PREVIEW_TOKENS,
148
+ compact: true,
149
+ identity: detailsIdentity
150
+ })}`);
151
+ return details.join("; ");
152
+ });
153
+ if (activity.calls.length > lines.length) lines.push(`- ${activity.calls.length - lines.length} additional calls are recorded in the execution traces.`);
154
+ return `Tools called\n${lines.join("\n")}`;
155
+ }
156
+ function renderMessageDeliveries({ deliveries }, cancelled = false, inspector = require_quickjs_variant.createInspector(), identity = {}) {
157
+ if (!deliveries.length) return;
158
+ const lines = deliveries.slice(0, MAX_ENTRIES).map((delivery) => {
159
+ const outcome = delivery.success === true ? "delivered" : "uncertain";
160
+ const details = [`- ${messagePreview(delivery.value, inspector, identity)}: ${outcome}`];
161
+ if (delivery.error !== void 0) details.push(`error: ${errorPreview(delivery.error, inspector, identity)}`);
162
+ return details.join("; ");
163
+ });
164
+ if (deliveries.length > lines.length) lines.push(`- ${deliveries.length - lines.length} additional deliveries are recorded in the execution traces.`);
165
+ if (deliveries.some((delivery) => delivery.success === false)) lines.push("Messages queued after the failed delivery were skipped.");
166
+ else if (cancelled) lines.push("Messages still queued when execution was cancelled were skipped.");
167
+ return `Messages sent\n${lines.join("\n")}`;
168
+ }
169
+ function getInterruption(call) {
170
+ if ("output" in call && require_errors.ThinkSignal.is(call.output)) return call.output;
171
+ if (!call.success) {
172
+ const error = require_errors.Signals.maybeDeserializeError(call.error);
173
+ if (require_errors.ThinkSignal.is(error)) return error;
174
+ }
175
+ }
176
+ function getToolOutcome(call) {
177
+ if (getInterruption(call)) return "interrupted";
178
+ return call.success ? "succeeded" : "failed";
179
+ }
180
+ function messagePreview(value, inspector, identity) {
181
+ const component = require_component.isAnyComponent(value) ? value : void 0;
182
+ const detailsIdentity = component ? {
183
+ ...identity,
184
+ component: component.name
185
+ } : identity;
186
+ const body = inspector(component ? component.props : value, {
187
+ purpose: "message",
188
+ maxTokens: PAYLOAD_PREVIEW_TOKENS,
189
+ compact: true,
190
+ identity: detailsIdentity
191
+ });
192
+ if (!component) return body;
193
+ return `${inspector(component.name, {
194
+ purpose: "name",
195
+ maxTokens: NAME_PREVIEW_TOKENS,
196
+ identity: detailsIdentity
197
+ })} ${body}`;
198
+ }
199
+ function errorPreview(value, inspector, identity) {
200
+ const error = require_errors.Signals.maybeDeserializeError(value);
201
+ return inspector((error instanceof Error ? error.message : String(error ?? "Unknown error")).replace(/\s+/g, " ").trim(), {
202
+ purpose: "error",
203
+ maxTokens: ERROR_PREVIEW_TOKENS,
204
+ compact: true,
205
+ identity
206
+ });
207
+ }
208
+ //#endregion
209
+ //#region src/runtime/execution-diagnostics.ts
210
+ /** XML-style boundaries keep diagnostic text separate from recovery instructions. */
211
+ function reportSection(name, content, maxTokens = 2e3, options = {}) {
212
+ return `<${name}>\n${options.heading ? `${options.heading}\n` : ""}${require_quickjs_variant.limitInspectionOutput(content, maxTokens, false, options.preserve ?? "top")}\n</${name}>`;
213
+ }
214
+ /** Show the specific failure and guest source, never the host's implementation stack. */
215
+ function renderExecutionDiagnostics(error, message, inspector, identity) {
216
+ const cause = require_errors.CodeExecutionError.is(error) ? error.cause : error;
217
+ const candidate = require_errors.isLLMzError(cause) ? cause : error;
218
+ const failure = require_errors.isLLMzError(candidate) ? candidate : void 0;
219
+ const sections = [reportSection("error", inspector([failure ? `Code: ${failure.code}` : void 0, (failure === null || failure === void 0 ? void 0 : failure.message) ?? message].filter(Boolean).join("\n"), {
220
+ purpose: "error",
221
+ maxTokens: 1e3,
222
+ identity
223
+ }), 1e3)];
224
+ if (require_errors.CodeExecutionError.is(error) && error.stacktrace) sections.push(renderSourceTrace(error.stacktrace, inspector, identity));
225
+ else if (require_errors.InvalidCodeError.is(error) && error.source) sections.push(reportSection("invalid_code", inspector(error.source, {
226
+ purpose: "code",
227
+ maxTokens: 800,
228
+ identity
229
+ }), 800));
230
+ return sections;
231
+ }
232
+ /** Keep failure sites visible even when they are near the end of a long program. */
233
+ function renderSourceTrace(stack, inspector, identity) {
234
+ const lines = stack.split("\n");
235
+ const marked = lines.flatMap((line, index) => /^> \d+ \|/.test(line) ? [index] : []);
236
+ const selected = /* @__PURE__ */ new Set();
237
+ for (const index of marked.slice(0, 8)) for (let nearby = Math.max(0, index - 2); nearby <= Math.min(lines.length - 1, index + 3); nearby++) selected.add(nearby);
238
+ const excerpt = [];
239
+ let previous = -1;
240
+ for (const index of [...selected].sort((a, b) => a - b)) {
241
+ if (index > previous + 1) excerpt.push("... omitted source ...");
242
+ excerpt.push(lines[index]);
243
+ previous = index;
244
+ }
245
+ if (selected.size && previous < lines.length - 1) excerpt.push("... omitted source ...");
246
+ return reportSection("stack_trace", inspector(selected.size ? excerpt.join("\n") : stack, {
247
+ purpose: "code",
248
+ maxTokens: 1e3,
249
+ identity
250
+ }), 1e3);
251
+ }
252
+ //#endregion
253
+ //#region src/runtime/forced-inspection.ts
254
+ /** Keep attribution and content together, using the same display budgets as inspect(). */
255
+ function renderForcedInspection(inspections, inspector, identity, maxTokens, policies) {
256
+ return [
257
+ "<forced_inspection>",
258
+ "Forced inspection: the tools listed below completed successfully and requested review of their results.",
259
+ "This is the equivalent of an inspect() call. Do not repeat these tool calls; use the results below and retained variables.",
260
+ "No exit was applied. Review the evidence before continuing or completing the task.",
261
+ "",
262
+ "Tools requesting inspection (lines refer to the executed JavaScript):",
263
+ ...inspections.map((entry) => {
264
+ const entryIdentity = {
265
+ ...identity,
266
+ tool: entry.tool
267
+ };
268
+ const name = inspector(entry.tool, {
269
+ purpose: "name",
270
+ maxTokens: 80,
271
+ identity: entryIdentity
272
+ });
273
+ const reason = inspector(entry.reason, {
274
+ purpose: "error",
275
+ maxTokens: 1e3,
276
+ identity: entryIdentity
277
+ });
278
+ const budget = require_quickjs_variant.resolveInspectionBudget(entry.value, {
279
+ tokens: maxTokens,
280
+ policies
281
+ });
282
+ const result = inspector(entry.value, {
283
+ purpose: "result",
284
+ maxTokens,
285
+ policies,
286
+ identity: entryIdentity
287
+ });
288
+ return [
289
+ `<tool name="${name}" line="${entry.line ?? "unknown"}">`,
290
+ `<reason>${reason}</reason>`,
291
+ reportSection("result", result, budget.tokens, { preserve: budget.preserve }),
292
+ "</tool>"
293
+ ].join("\n");
294
+ }),
295
+ "</forced_inspection>"
296
+ ].join("\n");
297
+ }
298
+ //#endregion
299
+ //#region src/runtime/execution-report.ts
300
+ const MAX_REPORTED_CHANGES = 40;
301
+ const MAX_OVERRIDE_SOURCE_LENGTH = 3e3;
302
+ /** Format one settled outcome; execution is responsible for deciding what happened. */
303
+ function renderExecutionReport({ outcome, activity, memory, source, requiresExit = false, iteration, identity = { iteration }, inspector = require_quickjs_variant.createInspector(), maxTokens = require_truncate.DEFAULT_TOOL_RESULT_MAX_TOKENS, policies }) {
304
+ var _outcome$forcedInspec, _outcome$forcedInspec2;
305
+ const detail = (value) => inspector(value, {
306
+ purpose: "error",
307
+ maxTokens: 1e3,
308
+ identity
309
+ });
310
+ const name = (value) => inspector(value, {
311
+ purpose: "name",
312
+ maxTokens: 40,
313
+ identity
314
+ });
315
+ const resultSection = (tag, heading, value) => {
316
+ const budget = require_quickjs_variant.resolveInspectionBudget(value, {
317
+ tokens: maxTokens,
318
+ policies
319
+ });
320
+ return reportSection(tag, inspector(value, {
321
+ purpose: "result",
322
+ maxTokens,
323
+ policies,
324
+ identity
325
+ }), budget.tokens, {
326
+ heading,
327
+ preserve: budget.preserve
328
+ });
329
+ };
330
+ const sections = [renderStatus(outcome, memory)];
331
+ if (outcome.type === "inspect" && ((_outcome$forcedInspec = outcome.forcedInspections) === null || _outcome$forcedInspec === void 0 ? void 0 : _outcome$forcedInspec.length)) {
332
+ sections.push(renderForcedInspection(outcome.forcedInspections, inspector, identity, maxTokens, policies));
333
+ if (outcome.downstreamError) {
334
+ sections.push(...renderExecutionDiagnostics(outcome.downstreamError, require_utils.getErrorMessage(outcome.downstreamError), inspector, identity));
335
+ sections.push(reportSection("recovery", "A later operation failed. The tool results above were successfully retrieved; inspect them and repair only the failed work. Do not repeat successful calls."));
336
+ }
337
+ }
338
+ if (outcome.type === "error") {
339
+ sections.push(...renderExecutionDiagnostics(outcome.error, outcome.message, inspector, identity));
340
+ sections.push(reportSection("recovery", [
341
+ outcome.exitName !== void 0 ? `Completion through ${outcome.exitName} failed; no exit was applied.` : "Fix the error before continuing.",
342
+ "The iteration did not complete successfully. Review the error and recorded outcomes before continuing.",
343
+ "Use retained variables and acknowledged results. Do not repeat completed actions or messages.",
344
+ "Check uncertain external outcomes before retrying an operation."
345
+ ].join("\n")));
346
+ } else if (outcome.type === "interrupted") {
347
+ sections.push(reportSection("interruption", detail(outcome.message ?? "The response stream failed after JavaScript started.")));
348
+ if (outcome.stacktrace && /^(?:> | {2})?\d+ \|/m.test(outcome.stacktrace)) sections.push(renderSourceTrace(outcome.stacktrace, inspector, identity));
349
+ sections.push(reportSection("recovery", outcome.reason === "thinking" ? "Execution paused at the thinking request. Remaining statements did not run. Review the context below and continue from retained variables and acknowledged results; do not repeat completed actions or messages." : "The terminal decision was not applied. Earlier actions may have completed. Inspect the recorded outcomes before continuing; do not repeat acknowledged actions or messages."));
350
+ } else if (outcome.type === "cancelled") sections.push(reportSection("cancellation", detail(outcome.message)));
351
+ const override = renderExecutionOverride(source === null || source === void 0 ? void 0 : source.executed, source === null || source === void 0 ? void 0 : source.requested, inspector, identity);
352
+ if (override) {
353
+ sections.push(reportSection("execution_override", override));
354
+ if (outcome.type === "inspect" && requiresExit) sections.push(reportSection("recovery", "No exit was applied. The executed program returned an inspection result; use that result for any required completion. Do not call the originally requested business tools merely to compensate for the hook replacement."));
355
+ }
356
+ if (outcome.type === "error" && isReferenceError(outcome.error)) sections.push(reportSection("reference_recovery", "REFERENCE RECOVERY\nCheck the Memory overview and JavaScript API for the missing name. Declare new variables with const or let; assignment alone never creates a variable. If a preceding business call already returned, reuse its acknowledged result rather than repeating the call. Do not invent values or functions for unknown names."));
357
+ const completed = outcome.type === "inspect" || outcome.type === "exit";
358
+ const calls = renderToolCalls(activity, !!override || !completed, inspector, identity);
359
+ const deliveries = renderMessageDeliveries(activity, outcome.type === "cancelled", inspector, identity);
360
+ if (calls) sections.push(reportSection("tool_calls", calls, 4e3));
361
+ if (deliveries) sections.push(reportSection("messages", deliveries, 4e3));
362
+ const changes = [renderChanges("Created", memory.created, name), renderChanges("Updated", memory.updated, name)].filter(Boolean).join("\n");
363
+ if (changes) sections.push(reportSection("memory_changes", `Memory changes\n${changes}`));
364
+ if (memory.unavailable.length) {
365
+ const failures = memory.unavailable.slice(0, MAX_REPORTED_CHANGES);
366
+ const entries = failures.map((failure) => `- ${name(failure.name)}: ${detail(failure.reason)}`);
367
+ if (memory.unavailable.length > failures.length) entries.push(`- ${memory.unavailable.length - failures.length} additional values could not be retained.`);
368
+ sections.push(reportSection("memory_errors", `Memory errors\n${entries.join("\n")}`));
369
+ }
370
+ if (outcome.type === "inspect" && ((_outcome$forcedInspec2 = outcome.forcedInspections) === null || _outcome$forcedInspec2 === void 0 ? void 0 : _outcome$forcedInspec2.length) && (!outcome.explicit || outcome.forcedInspections.some((entry) => isEqual(entry.value, outcome.value)))) {} else if (outcome.type === "inspect") {
371
+ const heading = outcome.explicit ? "inspect() result" : "Result";
372
+ sections.push(outcome.available ? resultSection("result", heading, outcome.value) : reportSection("result", "Unavailable; see memory errors above.", maxTokens, { heading }));
373
+ } else if (outcome.type === "exit") sections.push(resultSection("completion", `Completion\nExit "${outcome.name}" completed.`, outcome.value === void 0 ? "" : outcome.value));
374
+ else {
375
+ sections.push(reportSection("result", "Not produced; execution did not complete an inspection.", maxTokens, { heading: "inspect() result" }));
376
+ if (outcome.type === "interrupted" && outcome.reason === "thinking" && outcome.context !== void 0) sections.push(resultSection("interruption_context", "Interruption context", outcome.context));
377
+ }
378
+ return sections.join("\n\n");
379
+ }
380
+ function renderStatus(outcome, memory) {
381
+ switch (outcome.type) {
382
+ case "cancelled": return "run_javascript: cancelled";
383
+ case "interrupted": return outcome.reason === "thinking" ? "run_javascript: paused" : "run_javascript: interrupted";
384
+ case "error": return "run_javascript: failed";
385
+ case "inspect":
386
+ case "exit": return memory.unavailable.length ? "run_javascript: completed with memory errors\nJavaScript ran successfully, but some values could not be retained." : "run_javascript: succeeded";
387
+ }
388
+ }
389
+ function isReferenceError(value) {
390
+ const error = require_errors.Signals.maybeDeserializeError(value);
391
+ return require_errors.UnknownToolError.is(error) || require_errors.UnknownToolError.is(error === null || error === void 0 ? void 0 : error.cause) || (require_errors.CodeExecutionError.is(error) ? error.originalErrorName : error === null || error === void 0 ? void 0 : error.name) === "ReferenceError";
392
+ }
393
+ /** Keep the requested assistant call intact while disclosing the source the host actually ran. */
394
+ function renderExecutionOverride(executedCode, requestedCode, inspector = require_quickjs_variant.createInspector(), identity) {
395
+ if (executedCode === void 0 || requestedCode === void 0 || executedCode === requestedCode) return;
396
+ const source = executedCode.slice(0, MAX_OVERRIDE_SOURCE_LENGTH);
397
+ return [
398
+ "EXECUTION OVERRIDE",
399
+ "The host onBeforeExecution hook replaced the requested JavaScript. The original assistant tool call records the requested program. Replacement source is shown below; the outcomes report what actually executed.",
400
+ "Continue from the actual results and retained variables. Do not replay the requested program to compensate for this intentional replacement.",
401
+ "Replacement JavaScript (bounded preview):",
402
+ inspector(source, {
403
+ purpose: "code",
404
+ maxTokens: 800,
405
+ identity
406
+ }),
407
+ ...source.length < executedCode.length ? ["The replacement source preview was truncated."] : []
408
+ ].join("\n");
409
+ }
410
+ function renderChanges(label, changes, name) {
411
+ if (!changes.length) return;
412
+ const names = changes.slice(0, MAX_REPORTED_CHANGES).map((change) => name(change.name));
413
+ const lines = [`${label}: ${names.join(", ")}`];
414
+ if (changes.length > names.length) lines.push(`${changes.length - names.length} more changes are retained in memory.`);
415
+ return lines.join("\n");
416
+ }
417
+ //#endregion
418
+ //#region src/runtime/generate.ts
419
+ const STREAM_IDLE_TIMEOUT = 18e4;
420
+ const STATIC_TOKEN_PARTS = [
421
+ "instructions",
422
+ "tools",
423
+ "protocol"
424
+ ];
425
+ const staticTokenEstimates = /* @__PURE__ */ new WeakMap();
426
+ function assertSuccessfulGeneration(metadata) {
427
+ if (!metadata || metadata.provider === "unknown") throw new require_errors.CognitiveError("LLM generation failed: missing successful provider metadata");
428
+ if (metadata.stopReason === "max_tokens") {
429
+ var _metadata$usage;
430
+ throw new require_errors.TokenOverflowError("LLM generation did not complete: stopReason=max_tokens", (_metadata$usage = metadata.usage) === null || _metadata$usage === void 0 ? void 0 : _metadata$usage.outputTokens, void 0, "output");
431
+ }
432
+ if (metadata.stopReason === "content_filter" || metadata.stopReason === "other") throw new require_errors.CognitiveError(`LLM generation did not complete: stopReason=${metadata.stopReason}`);
433
+ }
434
+ function measureNativeContextTokens(iteration, messages, tools, total) {
435
+ let estimates = staticTokenEstimates.get(iteration);
436
+ if (!estimates) {
437
+ var _iteration$tokens;
438
+ const initial = (_iteration$tokens = iteration.tokens) === null || _iteration$tokens === void 0 ? void 0 : _iteration$tokens.context;
439
+ estimates = {
440
+ instructions: (initial === null || initial === void 0 ? void 0 : initial.instructions) ?? 0,
441
+ tools: (initial === null || initial === void 0 ? void 0 : initial.tools) ?? 0,
442
+ protocol: (initial === null || initial === void 0 ? void 0 : initial.protocol) ?? 0
443
+ };
444
+ staticTokenEstimates.set(iteration, estimates);
445
+ }
446
+ const history = messages.filter((message) => message.role !== "system");
447
+ const emptyRequestTokens = require_custom_client.countNativeRequestTokens([], []);
448
+ const requestWithToolsTokens = require_custom_client.countNativeRequestTokens([], tools);
449
+ const requestWithHistoryTokens = require_custom_client.countNativeRequestTokens(history, tools);
450
+ const structuralTokens = Math.min(total, emptyRequestTokens);
451
+ const schemaTokens = Math.min(total - structuralTokens, Math.max(0, requestWithToolsTokens - emptyRequestTokens));
452
+ const iterations = Math.min(total - structuralTokens - schemaTokens, Math.max(0, requestWithHistoryTokens - requestWithToolsTokens));
453
+ const systemBudget = total - structuralTokens - schemaTokens - iterations;
454
+ const estimatedSystemParts = STATIC_TOKEN_PARTS.reduce((sum, part) => sum + estimates[part], 0);
455
+ const scale = estimatedSystemParts > 0 ? Math.min(1, systemBudget / estimatedSystemParts) : 0;
456
+ const instructions = Math.floor(estimates.instructions * scale);
457
+ const toolsTokens = Math.floor(estimates.tools * scale) + schemaTokens;
458
+ const protocol = Math.floor(estimates.protocol * scale);
459
+ return {
460
+ total,
461
+ framework: total - instructions - toolsTokens - protocol - iterations,
462
+ instructions,
463
+ tools: toolsTokens,
464
+ protocol,
465
+ iterations
466
+ };
467
+ }
468
+ /** A client may ignore its AbortSignal; cancellation must still release LLMz. */
469
+ function abortable(operation, signal) {
470
+ return new Promise((resolve, reject) => {
471
+ const aborted = () => reject(signal.reason ?? /* @__PURE__ */ new Error("Generation aborted"));
472
+ operation.then(resolve, reject).finally(() => signal.removeEventListener("abort", aborted));
473
+ if (signal.aborted) {
474
+ aborted();
475
+ return;
476
+ }
477
+ signal.addEventListener("abort", aborted, { once: true });
478
+ });
479
+ }
480
+ function validateResponse(output, calls, assistant) {
481
+ if (typeof output !== "string") throw new require_errors.CognitiveError("Provider returned invalid assistant output");
482
+ if (!Array.isArray(calls)) throw new require_errors.CognitiveError("Provider returned invalid native tool calls");
483
+ const ids = /* @__PURE__ */ new Set();
484
+ for (const call of calls) {
485
+ if (!call || typeof call.id !== "string" || !call.id || ids.has(call.id)) throw new require_errors.CognitiveError("Provider returned missing or duplicate native call IDs");
486
+ if (typeof call.name !== "string" || !call.name || !call.input || typeof call.input !== "object" || Array.isArray(call.input)) throw new require_errors.CognitiveError("Provider returned invalid native tool arguments");
487
+ ids.add(call.id);
488
+ }
489
+ if (assistant) {
490
+ var _assistant$content;
491
+ if (assistant.role !== "assistant") throw new require_errors.CognitiveError("Provider continuation must be an assistant message");
492
+ const normalized = (assistant.toolCalls ?? []).map((call) => ({
493
+ id: call.id,
494
+ name: call.function.name,
495
+ input: call.function.arguments ?? {}
496
+ }));
497
+ if (require_custom_client.stableJSON(normalized) !== require_custom_client.stableJSON(calls)) throw new require_errors.CognitiveError("Provider assistant message and normalized tool calls disagree");
498
+ if ((typeof assistant.content === "string" ? assistant.content : ((_assistant$content = assistant.content) === null || _assistant$content === void 0 ? void 0 : _assistant$content.filter((part) => part.type === "text").map((part) => part.text ?? "").join("")) ?? "") !== output) throw new require_errors.CognitiveError("Provider assistant message and visible output disagree");
499
+ }
500
+ }
501
+ async function prepareNativeRequest({ iteration, ctx, cognitive, controller, metadata, onBeforeRequest }) {
502
+ const modelRefs = Array.isArray(iteration.model) ? iteration.model : [iteration.model];
503
+ if (!modelRefs.length) throw new require_errors.CognitiveError("At least one model is required.");
504
+ const models = await Promise.all(modelRefs.map(async (ref) => {
505
+ try {
506
+ return await abortable(cognitive.getModelDetails(ref), controller.signal);
507
+ } catch (error) {
508
+ throw new require_errors.CognitiveError(`Failed to fetch model details for ${ref}: ${require_utils.getErrorMessage(error)}`, { cause: error });
509
+ }
510
+ }));
511
+ const model = models[0];
512
+ const { limit, output: reserve } = require_custom_client.resolveTokenBudget(models, ctx.maxTokens);
513
+ const tools = [require_native.getRunJavaScriptTool(!!ctx.chat)];
514
+ const system = [iteration.systemMessage];
515
+ const budgetInstruction = getBudgetInstruction(ctx, iteration);
516
+ const budget = `\n\nExecution budget: response ${ctx.iterations.length} of ${ctx.loop}. ${budgetInstruction}`;
517
+ const buildMessages = (retainedIds, summary) => {
518
+ const history = ctx.session.requestMessages({
519
+ inspector: ctx.inspector,
520
+ retainedIterationIds: retainedIds,
521
+ summary
522
+ });
523
+ const messages = [...structuredClone(system), ...history];
524
+ const last = messages.at(-1);
525
+ if (last) last.content = typeof last.content === "string" ? last.content + budget : [...last.content ?? [], {
526
+ type: "text",
527
+ text: budget.trim()
528
+ }];
529
+ return messages;
530
+ };
531
+ const compaction = await require_custom_client.prepareAutoCompaction(ctx.session, {
532
+ client: cognitive,
533
+ model: iteration.model,
534
+ signal: controller.signal,
535
+ contextWindow: ctx.maxTokens,
536
+ iterationId: iteration.id,
537
+ inputLimit: limit - reserve,
538
+ metadata,
539
+ measure: (ids, summary) => require_custom_client.countNativeRequestTokens(buildMessages(ids, summary), tools)
540
+ });
541
+ let messages = buildMessages((compaction === null || compaction === void 0 ? void 0 : compaction.retainedIterationIds) ?? ctx.session.retainedIterationIds, compaction === null || compaction === void 0 ? void 0 : compaction.summary);
542
+ let tokens = require_custom_client.countNativeRequestTokens(messages, tools);
543
+ const override = await callHook(() => onBeforeRequest === null || onBeforeRequest === void 0 ? void 0 : onBeforeRequest({
544
+ messages: structuredClone(messages),
545
+ iteration,
546
+ controller
547
+ }));
548
+ if (override) {
549
+ messages = structuredClone(override.messages);
550
+ tokens = require_custom_client.countNativeRequestTokens(messages, tools);
551
+ }
552
+ if (tokens > limit - reserve) throw new require_errors.TokenOverflowError(override ? "The onBeforeRequest messages exceed the context budget. Shorten them or increase options.maxTokens." : "The native prompt exceeds the context budget. Compact session input or increase options.maxTokens.", tokens, limit - reserve);
553
+ controller.signal.throwIfAborted();
554
+ compaction === null || compaction === void 0 || compaction.commit();
555
+ if (iteration.tokens) {
556
+ iteration.tokens.limit = limit;
557
+ iteration.tokens.context = measureNativeContextTokens(iteration, messages, tools, tokens);
558
+ }
559
+ const hasAudio = messages.some((message) => Array.isArray(message.content) && message.content.some((part) => part.type === "audio"));
560
+ return {
561
+ input: {
562
+ model: iteration.model,
563
+ temperature: iteration.temperature,
564
+ responseFormat: "text",
565
+ reasoningEffort: iteration.reasoningEffort,
566
+ messages,
567
+ tools,
568
+ toolControl: {
569
+ mode: ctx.chat ? "auto" : "required",
570
+ parallel: false
571
+ },
572
+ maxTokens: reserve,
573
+ meta: metadata ? { metadata } : void 0,
574
+ options: {
575
+ ...hasAudio ? { transcriptionModel: ctx.transcriptionModel ?? "fast" } : {},
576
+ ...ctx.maxTimeToFirstToken ? { maxTimeToFirstToken: ctx.maxTimeToFirstToken } : {},
577
+ ...ctx.midStreamFallback ? { midStreamFallback: true } : {}
578
+ }
579
+ },
580
+ model
581
+ };
582
+ }
583
+ function getBudgetInstruction(ctx, iteration) {
584
+ if (ctx.iterations.length < ctx.loop) return `Inspect business results that need interpretation before completing; never guess missing completion fields. Once the required facts are known, complete using retained values without repeating successful calls. ${ctx.chat ? "Component delivery needs no inspection. Keep lookups and retries silent unless progress updates were requested. If requested, include the update alongside the continuing call." : require_native.WORKER_RESPONSE_INSTRUCTION}`;
585
+ if (ctx.chat) return "This is the last response. Answer from inspected evidence with normal assistant text, or use JavaScript with an explicit return exit(\"listen\") or another registered named exit. Do not start work that needs another model response.";
586
+ if (!iteration.exits.length) return `${require_native.WORKER_RESPONSE_INSTRUCTION} This is the last response. Every JavaScript program must explicitly return inspect(value) with the available evidence. Do not start work that needs another model response.`;
587
+ return `${require_native.WORKER_RESPONSE_INSTRUCTION} This is the last response. Finish with return exit("NAME", payload) from run_javascript, using a registered name. Build the payload from inspected $return and retained variables; do not repeat successful lookups to reconstruct it. If the task is incomplete, report it honestly with an incomplete or error payload only when the exit schema permits it. Assistant prose and inspection returns do not complete a worker. Do not start work that requires another model response.`;
588
+ }
589
+ async function consumeNativeStream({ cognitive, input, controller, maxIdleTime, onChunk }) {
590
+ const streamController = createJoinedAbortController([controller.signal]);
591
+ const stream = cognitive.generateTextStream(input, { signal: streamController.signal });
592
+ let completed = false;
593
+ try {
594
+ while (true) {
595
+ controller.signal.throwIfAborted();
596
+ const chunk = await readNextStreamChunk(stream, streamController, maxIdleTime);
597
+ if (chunk.done) {
598
+ completed = true;
599
+ return;
600
+ }
601
+ await onChunk(chunk.value);
602
+ }
603
+ } finally {
604
+ streamController.abort("LLM stream closed");
605
+ if (!completed) stream.return(void 0).catch(() => {});
606
+ }
607
+ }
608
+ async function readNextStreamChunk(stream, controller, maxIdleTime) {
609
+ let timer;
610
+ const timeout = new Promise((_resolve, reject) => {
611
+ timer = setTimeout(() => {
612
+ controller.abort("LLM stream stalled");
613
+ reject(new require_errors.CognitiveError("LLM stream stalled"));
614
+ }, maxIdleTime);
615
+ });
616
+ try {
617
+ return await abortable(Promise.race([stream.next(), timeout]), controller.signal);
618
+ } finally {
619
+ clearTimeout(timer);
620
+ }
621
+ }
622
+ async function generateCode({ iteration, ctx, cognitive, controller, metadata, onSendDelta, onToolCalls, onBeforeRequest }) {
623
+ var _toolCalls$find;
624
+ const startedAt = Date.now();
625
+ controller.signal.throwIfAborted();
626
+ const { input, model } = await prepareNativeRequest({
627
+ iteration,
628
+ ctx,
629
+ cognitive,
630
+ controller,
631
+ metadata,
632
+ onBeforeRequest
633
+ });
634
+ iteration.recordTrace({
635
+ type: "llm_call_started",
636
+ started_at: startedAt,
637
+ model: model.id
638
+ });
639
+ let output = "";
640
+ let toolCalls = [];
641
+ let responseMetadata;
642
+ let assistantMessage;
643
+ let continuation;
644
+ let attempt = 1;
645
+ let ttft;
646
+ let ttl;
647
+ let previewed = false;
648
+ let accepted = false;
649
+ let dispatchedCalls;
650
+ let dispatchedFingerprint;
651
+ let offeredFingerprint;
652
+ const messageMetadata = () => ({
653
+ iterationId: iteration.id,
654
+ id: `${iteration.id}:${attempt}:text`
655
+ });
656
+ const preview = async (delta) => {
657
+ try {
658
+ await (onSendDelta === null || onSendDelta === void 0 ? void 0 : onSendDelta(delta));
659
+ } catch (err) {
660
+ if (delta.restart) throw new require_errors.CognitiveError(`LLM stream restart handler failed: ${require_utils.getErrorMessage(err)}`, { cause: err });
661
+ }
662
+ };
663
+ try {
664
+ controller.signal.throwIfAborted();
665
+ if (typeof cognitive.generateTextStream === "function") {
666
+ let finished = false;
667
+ await consumeNativeStream({
668
+ cognitive,
669
+ input,
670
+ controller,
671
+ maxIdleTime: Math.max(STREAM_IDLE_TIMEOUT, ctx.maxTimeToFirstToken ?? 0),
672
+ onChunk: async (value) => {
673
+ if (value.error) throw new require_errors.CognitiveError(`LLM generation failed: ${value.error}`);
674
+ if (value.restart) {
675
+ if (dispatchedCalls) throw new require_errors.CognitiveError("The LLM stream restarted after tool execution began; completed work cannot be replayed.");
676
+ if (!ctx.midStreamFallback) throw new require_errors.CognitiveError("Unexpected LLM stream restart");
677
+ if (!Number.isInteger(value.restart.attempt) || value.restart.attempt <= attempt) throw new require_errors.CognitiveError("Provider returned an invalid stream restart attempt");
678
+ if (value.output || value.toolCalls || value.finished) throw new require_errors.CognitiveError("A stream restart must not contain output from either attempt");
679
+ iteration.recordTrace({
680
+ type: "llm_call_restarted",
681
+ started_at: Date.now(),
682
+ ...value.restart
683
+ });
684
+ previewed = false;
685
+ await preview({
686
+ restart: true,
687
+ iterationId: iteration.id,
688
+ ...value.restart
689
+ });
690
+ attempt = value.restart.attempt;
691
+ output = "";
692
+ toolCalls = [];
693
+ responseMetadata = void 0;
694
+ assistantMessage = void 0;
695
+ continuation = void 0;
696
+ ttft = void 0;
697
+ ttl = void 0;
698
+ finished = false;
699
+ previewed = false;
700
+ offeredFingerprint = void 0;
701
+ return;
702
+ }
703
+ const callsFingerprint = value.toolCalls ? require_custom_client.stableJSON(value.toolCalls) : void 0;
704
+ if (dispatchedCalls && callsFingerprint !== void 0 && callsFingerprint !== dispatchedFingerprint) throw new require_errors.CognitiveError("The LLM stream changed tool calls after execution began; completed work cannot be replayed.");
705
+ const repeatedDispatchedCalls = dispatchedCalls && callsFingerprint === dispatchedFingerprint;
706
+ if (finished && (value.output || value.toolCalls && !repeatedDispatchedCalls || value.assistantMessage || value.continuation !== void 0)) throw new require_errors.CognitiveError("Received content after stream completion");
707
+ if (value.metadata) responseMetadata = value.metadata;
708
+ if (value.toolCalls) {
709
+ toolCalls = dispatchedCalls ?? value.toolCalls;
710
+ if (onToolCalls && !dispatchedCalls && toolCalls.length && offeredFingerprint !== callsFingerprint) {
711
+ validateResponse(output + (value.output ?? ""), toolCalls, value.assistantMessage ?? assistantMessage);
712
+ if (responseMetadata) assertSuccessfulGeneration(responseMetadata);
713
+ const snapshot = freezeToolCalls(structuredClone(toolCalls));
714
+ offeredFingerprint = callsFingerprint;
715
+ if (onToolCalls(snapshot)) {
716
+ dispatchedCalls = snapshot;
717
+ dispatchedFingerprint = callsFingerprint;
718
+ toolCalls = snapshot;
719
+ }
720
+ }
721
+ }
722
+ if (value.assistantMessage) assistantMessage = value.assistantMessage;
723
+ if (value.continuation !== void 0) continuation = value.continuation;
724
+ if (value.output) {
725
+ output += value.output;
726
+ ttl = Date.now() - startedAt;
727
+ ttft ??= ttl;
728
+ previewed = true;
729
+ await preview({
730
+ restart: false,
731
+ ...messageMetadata(),
732
+ type: "text",
733
+ delta: value.output,
734
+ content: output
735
+ });
736
+ }
737
+ if (value.finished) finished = true;
738
+ }
739
+ });
740
+ if (!finished) throw new require_errors.CognitiveError("LLM stream ended without a completion signal");
741
+ } else {
742
+ const response = await abortable(cognitive.generateText(input, { signal: controller.signal }), controller.signal);
743
+ if (response.error) throw new require_errors.CognitiveError(`LLM generation failed: ${response.error}`);
744
+ output = response.output ?? "";
745
+ toolCalls = response.toolCalls ?? [];
746
+ assistantMessage = response.assistantMessage;
747
+ continuation = response.continuation;
748
+ responseMetadata = response.metadata;
749
+ }
750
+ controller.signal.throwIfAborted();
751
+ assertSuccessfulGeneration(responseMetadata);
752
+ validateResponse(output, toolCalls, assistantMessage);
753
+ if ((responseMetadata === null || responseMetadata === void 0 ? void 0 : responseMetadata.stopReason) === "tool_calls" && !toolCalls.length) throw new require_errors.CognitiveError("Provider signaled tool calls but returned none");
754
+ accepted = true;
755
+ } catch (err) {
756
+ throw require_errors.isLLMzError(err) ? err : new require_errors.CognitiveError(`LLM generation failed: ${require_utils.getErrorMessage(err)}`, { cause: err });
757
+ } finally {
758
+ const usage = (responseMetadata === null || responseMetadata === void 0 ? void 0 : responseMetadata.usage) ?? {
759
+ inputTokens: 0,
760
+ outputTokens: 0,
761
+ inputCost: 0,
762
+ outputCost: 0
763
+ };
764
+ iteration.llm = {
765
+ started_at: startedAt,
766
+ ended_at: Date.now(),
767
+ status: accepted ? "success" : "error",
768
+ output,
769
+ cached: (responseMetadata === null || responseMetadata === void 0 ? void 0 : responseMetadata.cached) ?? false,
770
+ tokens: usage.inputTokens + usage.outputTokens,
771
+ spend: (responseMetadata === null || responseMetadata === void 0 ? void 0 : responseMetadata.cost) ?? 0,
772
+ model: (responseMetadata === null || responseMetadata === void 0 ? void 0 : responseMetadata.model) ?? model.id,
773
+ time_to_first_token: ttft,
774
+ time_to_last_token: ttl,
775
+ usage
776
+ };
777
+ if (iteration.tokens) Object.assign(iteration.tokens, {
778
+ input: usage.inputTokens,
779
+ output: usage.outputTokens,
780
+ total: usage.inputTokens + usage.outputTokens
781
+ });
782
+ if (!accepted && previewed) await preview({
783
+ restart: true,
784
+ iterationId: iteration.id,
785
+ attempt: attempt + 1,
786
+ fromModel: model.id,
787
+ toModel: model.id,
788
+ reason: "Generation did not complete successfully"
789
+ });
790
+ }
791
+ const code = (_toolCalls$find = toolCalls.find((call) => call.name === "run_javascript")) === null || _toolCalls$find === void 0 || (_toolCalls$find = _toolCalls$find.input) === null || _toolCalls$find === void 0 ? void 0 : _toolCalls$find.code;
792
+ iteration.recordTrace({
793
+ type: "llm_call_success",
794
+ started_at: startedAt,
795
+ ended_at: Date.now(),
796
+ model: model.id,
797
+ code: typeof code === "string" ? code : ""
798
+ });
799
+ return {
800
+ attempt,
801
+ output,
802
+ toolCalls,
803
+ assistantMessage,
804
+ continuation,
805
+ metadata: responseMetadata,
806
+ messageMetadata: messageMetadata()
807
+ };
808
+ }
809
+ /** Keep execution's accepted arguments independent of later provider or callback mutations. */
810
+ function freezeToolCalls(calls) {
811
+ const freeze = (value) => {
812
+ if (!value || typeof value !== "object" || Object.isFrozen(value)) return;
813
+ for (const child of Object.values(value)) freeze(child);
814
+ Object.freeze(value);
815
+ };
816
+ freeze(calls);
817
+ return calls;
818
+ }
819
+ //#endregion
820
+ //#region src/runtime/inspection-values.ts
821
+ /** Explicit display policies apply only to unchanged values in this JavaScript execution. */
822
+ var InspectionValues = class {
823
+ _primitives = /* @__PURE__ */ new Map();
824
+ _objects = /* @__PURE__ */ new Map();
825
+ capture(value, policy) {
826
+ this._register(value, policy, true);
827
+ }
828
+ captureDefault(value, maxTokens) {
829
+ this._register(value, {
830
+ maxTokens,
831
+ preserve: "top"
832
+ }, false);
833
+ }
834
+ _register(value, policy, explicit) {
835
+ let captured;
836
+ try {
837
+ captured = require_quickjs_variant.cloneMemoryValue(value);
838
+ } catch {
839
+ return;
840
+ }
841
+ if (!captured || typeof captured !== "object") {
842
+ const previous = this._primitives.get(captured);
843
+ this._primitives.set(captured, this._mergePolicy(previous, {
844
+ policy,
845
+ explicit
846
+ }));
847
+ return;
848
+ }
849
+ const key = this._objectKey(captured);
850
+ const candidates = this._objects.get(key) ?? [];
851
+ const previous = candidates.find((candidate) => isEqual(candidate.value, captured));
852
+ if (previous) {
853
+ const selected = this._mergePolicy(previous, {
854
+ policy,
855
+ explicit
856
+ });
857
+ previous.policy = selected.policy;
858
+ previous.explicit = selected.explicit;
859
+ return;
860
+ }
861
+ candidates.push({
862
+ value: captured,
863
+ policy: { ...policy },
864
+ explicit
865
+ });
866
+ this._objects.set(key, candidates);
867
+ }
868
+ /** Match unchanged VM copies without rebuilding a wrapped display graph. */
869
+ getPolicy = (value) => {
870
+ var _candidates$find;
871
+ if (!value || typeof value !== "object") {
872
+ var _this$_primitives$get;
873
+ return (_this$_primitives$get = this._primitives.get(value)) === null || _this$_primitives$get === void 0 ? void 0 : _this$_primitives$get.policy;
874
+ }
875
+ return (_candidates$find = (this._objects.get(this._objectKey(value)) ?? []).find((candidate) => isEqual(candidate.value, value))) === null || _candidates$find === void 0 ? void 0 : _candidates$find.policy;
876
+ };
877
+ _objectKey(value) {
878
+ return Array.isArray(value) ? `array:${value.length}` : `object:${Object.keys(value).length}`;
879
+ }
880
+ _mergePolicy(previous, next) {
881
+ if ((previous === null || previous === void 0 ? void 0 : previous.explicit) && !next.explicit) return previous;
882
+ if (!previous || !previous.explicit && next.explicit || next.policy.maxTokens < previous.policy.maxTokens) return {
883
+ policy: { ...next.policy },
884
+ explicit: next.explicit
885
+ };
886
+ if (next.policy.maxTokens === previous.policy.maxTokens && next.policy.preserve !== previous.policy.preserve) return {
887
+ policy: {
888
+ maxTokens: next.policy.maxTokens,
889
+ preserve: "top"
890
+ },
891
+ explicit: next.explicit
892
+ };
893
+ return previous;
894
+ }
895
+ };
896
+ //#endregion
897
+ //#region src/runtime/javascript-api.ts
898
+ const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
899
+ /**
900
+ * Component methods send synchronously; the runtime joins delivery in close().
901
+ * Inspection returns a decision, while exit latches an outcome and stops the program.
902
+ */
903
+ function createJavaScriptApi({ iteration, components, exits, deliver, signal, onError }) {
904
+ const decisions = /* @__PURE__ */ new Map();
905
+ const pending = /* @__PURE__ */ new Set();
906
+ const inspections = [];
907
+ let open = true;
908
+ let outstanding = [];
909
+ let delivery;
910
+ let nextMessage = 0;
911
+ let terminalOutcome;
912
+ let interruption;
913
+ let criticalFailure;
914
+ const termination = /* @__PURE__ */ new Error("JavaScript execution terminated.");
915
+ const reportError = (error) => {
916
+ onError === null || onError === void 0 || onError(error);
917
+ if (require_errors.isCriticalError(error)) {
918
+ criticalFailure = error;
919
+ complete();
920
+ }
921
+ };
922
+ const throwIfTerminated = () => {
923
+ if (criticalFailure) throw criticalFailure;
924
+ if (interruption || terminalOutcome) throw termination;
925
+ };
926
+ const assertOpen = () => {
927
+ throwIfTerminated();
928
+ if (!open) throw new require_errors.HostOperationError("JavaScript has completed. Host operations and Object writes are closed.");
929
+ signal === null || signal === void 0 || signal.throwIfAborted();
930
+ };
931
+ const resolve = (value) => {
932
+ if (!isRecord(value) || typeof value.__llmz_decision !== "string") return;
933
+ return decisions.get(value.__llmz_decision);
934
+ };
935
+ const issue = (outcome) => {
936
+ assertOpen();
937
+ const token = (0, ulid.ulid)();
938
+ decisions.set(token, outcome);
939
+ return Object.freeze({ __llmz_decision: token });
940
+ };
941
+ const validateExit = (name = "listen", value) => {
942
+ assertOpen();
943
+ const registered = exits.find((candidate) => candidate.name === name || candidate.aliases.includes(name));
944
+ if (!registered) throw new require_errors.UnknownExitError(name, exits.map((exit) => exit.name));
945
+ if (!registered.schema && value !== void 0) throw new require_errors.ExitInputError(registered.name, [{
946
+ path: [],
947
+ message: "This exit takes no payload."
948
+ }], "undefined");
949
+ const schema = registered.zSchema;
950
+ const parsed = schema ? require_schema.parseSchemaSync(schema, value, `Exit "${registered.name}"`) : void 0;
951
+ if (parsed && !parsed.success) throw new require_errors.ExitInputError(registered.name, parsed.error.issues, require_typings.schemaToTypeScript(schema));
952
+ const validated = parsed === null || parsed === void 0 ? void 0 : parsed.data;
953
+ return {
954
+ type: "exit",
955
+ exit: registered,
956
+ value: require_quickjs_variant.cloneMemoryValue(validated)
957
+ };
958
+ };
959
+ const exit = (name = "listen", value) => {
960
+ let outcome;
961
+ try {
962
+ outcome = validateExit(name, value);
963
+ } catch (error) {
964
+ reportError(error);
965
+ throw error;
966
+ }
967
+ terminalOutcome = outcome;
968
+ complete();
969
+ throw termination;
970
+ };
971
+ const track = (operation) => {
972
+ assertOpen();
973
+ const tracked = (async () => operation())().then((value) => {
974
+ pending.delete(tracked);
975
+ return value;
976
+ }, (error) => {
977
+ pending.delete(tracked);
978
+ if (require_errors.isCriticalError(error)) {
979
+ criticalFailure = error;
980
+ complete();
981
+ }
982
+ if (!interruption && require_errors.ThinkSignal.is(error)) {
983
+ interruption = error;
984
+ complete();
985
+ }
986
+ throw error;
987
+ });
988
+ pending.add(tracked);
989
+ tracked.catch(() => {});
990
+ return tracked;
991
+ };
992
+ const enqueue = (messages) => {
993
+ const dispatch = async () => deliver(messages);
994
+ delivery = delivery ? delivery.then(dispatch) : dispatch();
995
+ delivery.catch(() => {});
996
+ return delivery;
997
+ };
998
+ const complete = () => {
999
+ if (!open) return;
1000
+ open = false;
1001
+ outstanding = [...pending];
1002
+ };
1003
+ const close = async () => {
1004
+ var _delivered$;
1005
+ complete();
1006
+ const [, delivered] = await Promise.all([Promise.allSettled(outstanding), Promise.allSettled(delivery ? [delivery] : [])]);
1007
+ if (criticalFailure) throw criticalFailure;
1008
+ if (((_delivered$ = delivered[0]) === null || _delivered$ === void 0 ? void 0 : _delivered$.status) === "rejected") throw delivered[0].reason;
1009
+ if (outstanding.length && !interruption) throw new require_errors.HostOperationError(`JavaScript completed with ${outstanding.length} unawaited host operation(s). Await all business tools before returning. Started operations have settled and may have completed effects; do not replay them.`);
1010
+ };
1011
+ const inspect = (value) => issue({
1012
+ type: "inspect",
1013
+ value: require_quickjs_variant.cloneMemoryValue(value)
1014
+ });
1015
+ const chat = require_vm.withMissingMember(Object.fromEntries([...components].map(([name, component]) => [name, Object.freeze((input) => {
1016
+ assertOpen();
1017
+ let rendered;
1018
+ try {
1019
+ rendered = component.render(input);
1020
+ } catch (error) {
1021
+ reportError(error);
1022
+ throw error;
1023
+ }
1024
+ enqueue([{
1025
+ id: `${iteration.nativeCallId ?? iteration.id}:message:${++nextMessage}`,
1026
+ component: rendered
1027
+ }]);
1028
+ })])), (name) => {
1029
+ const error = new require_errors.UnknownComponentError(name, [...components.keys()]);
1030
+ onError === null || onError === void 0 || onError(error);
1031
+ throw error;
1032
+ });
1033
+ return {
1034
+ bindings: Object.freeze({
1035
+ exit: Object.freeze(exit),
1036
+ inspect: Object.freeze(inspect),
1037
+ chat: Object.freeze(chat)
1038
+ }),
1039
+ resolve,
1040
+ isReceipt: (value) => resolve(value) !== void 0,
1041
+ getTerminalOutcome: () => terminalOutcome,
1042
+ getInterruption: () => interruption,
1043
+ requestInspection: (inspection) => {
1044
+ inspections.push(inspection);
1045
+ },
1046
+ getForcedInspections: () => inspections,
1047
+ throwIfTerminated,
1048
+ track,
1049
+ assertOpen,
1050
+ reportError,
1051
+ complete,
1052
+ close
1053
+ };
1054
+ }
1055
+ //#endregion
1056
+ //#region src/runtime/utils.ts
1057
+ const finalizeIteration = async ({ iteration, status, controller, onIterationEnd }) => {
1058
+ if (status) iteration.end(status);
1059
+ if (iteration.status.type === "pending") return;
1060
+ try {
1061
+ await (onIterationEnd === null || onIterationEnd === void 0 ? void 0 : onIterationEnd(iteration, controller));
1062
+ } catch (err) {
1063
+ if (require_errors.isCriticalError(err)) {
1064
+ iteration.recordError(err);
1065
+ throw err;
1066
+ }
1067
+ iteration.recordError(new require_errors.HookError(err instanceof Error ? err.message : String(err), { cause: err }));
1068
+ console.error(err);
1069
+ }
1070
+ };
1071
+ //#endregion
1072
+ //#region src/runtime/tool-wrapper.ts
1073
+ const SLOW_TOOL_WARNING = (0, ms.default)("15s");
1074
+ function wrapTool({ tool, object, iteration, beforeHook, afterHook, onTruncation, onResult, controller, onThink }) {
1075
+ return async function(input, line) {
1076
+ controller.signal.throwIfAborted();
1077
+ const toolCallId = `tcall_${(0, ulid.ulid)()}`;
1078
+ const originalInput = input;
1079
+ let reportedInput = originalInput;
1080
+ let effectiveInput = input;
1081
+ const alertSlowTool = setTimeout(() => iteration.recordTrace({
1082
+ type: "tool_slow",
1083
+ tool_name: tool.name,
1084
+ tool_call_id: toolCallId,
1085
+ started_at: Date.now(),
1086
+ input: reportedInput,
1087
+ object,
1088
+ duration: SLOW_TOOL_WARNING
1089
+ }), SLOW_TOOL_WARNING);
1090
+ const toolStart = Date.now();
1091
+ let output;
1092
+ let error;
1093
+ let success = true;
1094
+ const inspections = [];
1095
+ const pushToolCallTrace = () => {
1096
+ iteration.recordTrace({
1097
+ type: "tool_call",
1098
+ tool_call_id: toolCallId,
1099
+ native_call_id: iteration.nativeCallId,
1100
+ started_at: toolStart,
1101
+ ended_at: Date.now(),
1102
+ tool_name: tool.name,
1103
+ object,
1104
+ input: reportedInput,
1105
+ output,
1106
+ error,
1107
+ success
1108
+ });
1109
+ };
1110
+ const unwrapSignal = (value) => {
1111
+ if (!require_errors.ThinkSignal.is(value)) return value;
1112
+ const context = value.context;
1113
+ const output = require_truncate.unwrapTruncated(context);
1114
+ if (require_truncate.isTruncated(context)) onTruncation === null || onTruncation === void 0 || onTruncation(output, context.$$truncate);
1115
+ const inspection = {
1116
+ tool: object ? `${object}.${tool.name}` : tool.name,
1117
+ toolCallId,
1118
+ line,
1119
+ reason: value.reason,
1120
+ value: output,
1121
+ metadata: value.metadata
1122
+ };
1123
+ inspections.push(inspection);
1124
+ return output;
1125
+ };
1126
+ try {
1127
+ const beforeRes = await callHook(() => beforeHook === null || beforeHook === void 0 ? void 0 : beforeHook({
1128
+ iteration,
1129
+ tool,
1130
+ input: effectiveInput,
1131
+ controller,
1132
+ object,
1133
+ toolCallId,
1134
+ nativeCallId: iteration.nativeCallId
1135
+ }));
1136
+ if (require_errors.ThinkSignal.is(beforeRes)) throw new require_errors.HookError("Tool hooks cannot request inspection with ThinkSignal. Return it from the tool handler instead.");
1137
+ if (typeof (beforeRes === null || beforeRes === void 0 ? void 0 : beforeRes.input) !== "undefined") effectiveInput = beforeRes.input;
1138
+ controller.signal.throwIfAborted();
1139
+ try {
1140
+ output = await tool.execute(effectiveInput, {
1141
+ callId: toolCallId,
1142
+ iterationId: iteration.id,
1143
+ nativeCallId: iteration.nativeCallId,
1144
+ onTruncation,
1145
+ onInput: (parsed) => {
1146
+ controller.signal.throwIfAborted();
1147
+ if (effectiveInput === originalInput) reportedInput = parsed;
1148
+ }
1149
+ });
1150
+ } catch (error) {
1151
+ if (!require_errors.ThinkSignal.is(error)) throw error;
1152
+ output = error;
1153
+ }
1154
+ output = unwrapSignal(output);
1155
+ const afterRes = await callHook(() => afterHook === null || afterHook === void 0 ? void 0 : afterHook({
1156
+ iteration,
1157
+ tool,
1158
+ input: effectiveInput,
1159
+ output,
1160
+ controller,
1161
+ object,
1162
+ toolCallId,
1163
+ nativeCallId: iteration.nativeCallId
1164
+ }));
1165
+ if (require_errors.ThinkSignal.is(afterRes) || require_errors.ThinkSignal.is(afterRes === null || afterRes === void 0 ? void 0 : afterRes.output)) throw new require_errors.HookError("Tool hooks cannot request inspection with ThinkSignal. Return it from the tool handler instead.");
1166
+ if (typeof (afterRes === null || afterRes === void 0 ? void 0 : afterRes.output) !== "undefined") output = afterRes.output;
1167
+ controller.signal.throwIfAborted();
1168
+ } catch (err) {
1169
+ success = false;
1170
+ output = void 0;
1171
+ if (require_errors.ThinkSignal.is(err)) error = new require_errors.HookError("Tool hooks cannot request inspection with ThinkSignal. Return it from the tool handler instead.");
1172
+ else error = require_errors.isLLMzError(err) ? err : new require_errors.ToolExecutionError(tool.name, err);
1173
+ iteration.recordError(error);
1174
+ } finally {
1175
+ clearTimeout(alertSlowTool);
1176
+ for (const inspection of success ? inspections : []) {
1177
+ const value = require_quickjs_variant.snapshotInspectionValue(output);
1178
+ onThink === null || onThink === void 0 || onThink({
1179
+ ...inspection,
1180
+ value
1181
+ });
1182
+ iteration.recordTrace({
1183
+ type: "think_signal",
1184
+ started_at: Date.now(),
1185
+ ended_at: Date.now(),
1186
+ line: line ?? 0,
1187
+ tool_name: tool.name,
1188
+ tool_call_id: toolCallId,
1189
+ object,
1190
+ reason: inspection.reason,
1191
+ context: value,
1192
+ metadata: inspection.metadata
1193
+ });
1194
+ }
1195
+ pushToolCallTrace();
1196
+ }
1197
+ if (!success) throw error;
1198
+ onResult === null || onResult === void 0 || onResult(output);
1199
+ return output;
1200
+ };
1201
+ }
1202
+ //#endregion
1203
+ //#region src/runtime/vm-context.ts
1204
+ const buildVMContext = ({ ctx, iteration, controller, onBeforeTool, onAfterTool, onTruncation, onToolResult, javascriptApi }) => {
1205
+ const memoryBindings = ctx.session.getBindings();
1206
+ const vmContext = {
1207
+ ...require_utils.stripInvalidIdentifiers(memoryBindings),
1208
+ [require_vm.VM_ON_ERROR]: (error) => {
1209
+ iteration.recordError(error);
1210
+ }
1211
+ };
1212
+ const reject = (error) => {
1213
+ iteration.recordError(error);
1214
+ javascriptApi === null || javascriptApi === void 0 || javascriptApi.reportError(error);
1215
+ throw error;
1216
+ };
1217
+ for (const name of ["$return", "$iterations"]) Object.defineProperty(vmContext, name, {
1218
+ value: memoryBindings[name],
1219
+ enumerable: true,
1220
+ writable: false,
1221
+ configurable: false
1222
+ });
1223
+ if (javascriptApi) {
1224
+ for (const [name, value] of Object.entries(javascriptApi.bindings)) Object.defineProperty(vmContext, name, {
1225
+ value,
1226
+ enumerable: true,
1227
+ writable: false,
1228
+ configurable: false
1229
+ });
1230
+ Object.defineProperty(vmContext, require_vm.VM_PROGRAM_COMPLETE, { value: javascriptApi.complete });
1231
+ Object.defineProperty(vmContext, require_vm.VM_TERMINATION, { value: {
1232
+ isTerminated: () => javascriptApi.getTerminalOutcome() !== void 0 || javascriptApi.getInterruption() !== void 0,
1233
+ check: javascriptApi.throwIfTerminated,
1234
+ getSignal: javascriptApi.getInterruption
1235
+ } });
1236
+ }
1237
+ for (const obj of iteration.objects) {
1238
+ const internalValues = {};
1239
+ const instance = {};
1240
+ for (const { name, writable, type } of obj.properties ?? []) {
1241
+ const initialValue = ctx.session.memory.getObjectPropertyValue(obj.name, name);
1242
+ internalValues[name] = freezePropertyValue(initialValue);
1243
+ const schema = type ?? _bpinternal_zui.z.any();
1244
+ Object.defineProperty(instance, name, {
1245
+ enumerable: true,
1246
+ configurable: true,
1247
+ get() {
1248
+ return internalValues[name];
1249
+ },
1250
+ set(value) {
1251
+ javascriptApi === null || javascriptApi === void 0 || javascriptApi.assertOpen();
1252
+ if (!writable) reject(new require_errors.AssignmentError(`Property ${obj.name}.${name} is read-only and cannot be modified`));
1253
+ let parsed;
1254
+ try {
1255
+ parsed = require_schema.parseSchemaSync(schema, value, `Object property ${obj.name}.${name}`);
1256
+ } catch (error) {
1257
+ const failure = iteration.recordError(error);
1258
+ javascriptApi === null || javascriptApi === void 0 || javascriptApi.reportError(failure);
1259
+ throw failure;
1260
+ }
1261
+ if (!parsed.success) reject(new require_errors.ObjectPropertyError(obj.name, name, parsed.error.issues, require_typings.schemaToTypeScript(schema)));
1262
+ internalValues[name] = freezePropertyValue(require_quickjs_variant.cloneMemoryValue(parsed.data));
1263
+ iteration.recordTrace({
1264
+ type: "property",
1265
+ started_at: Date.now(),
1266
+ object: obj.name,
1267
+ property: name,
1268
+ value: parsed.data
1269
+ });
1270
+ iteration.trackMutation({
1271
+ object: obj.name,
1272
+ property: name,
1273
+ before: initialValue,
1274
+ after: parsed.data
1275
+ });
1276
+ }
1277
+ });
1278
+ }
1279
+ for (const tool of obj.tools ?? []) {
1280
+ const wrapped = wrapTool({
1281
+ tool,
1282
+ object: obj.name,
1283
+ iteration,
1284
+ beforeHook: onBeforeTool,
1285
+ afterHook: onAfterTool,
1286
+ onTruncation,
1287
+ onResult: onToolResult,
1288
+ controller,
1289
+ onThink: javascriptApi === null || javascriptApi === void 0 ? void 0 : javascriptApi.requestInspection
1290
+ });
1291
+ instance[tool.name] = javascriptApi ? (input) => {
1292
+ var _vmContext$VM_CALL_SI;
1293
+ const line = (_vmContext$VM_CALL_SI = vmContext[require_vm.VM_CALL_SITE]) === null || _vmContext$VM_CALL_SI === void 0 ? void 0 : _vmContext$VM_CALL_SI.call(vmContext);
1294
+ return javascriptApi.track(() => wrapped(input, line));
1295
+ } : wrapped;
1296
+ }
1297
+ vmContext[obj.name] = require_vm.withMissingMember(instance, (name) => {
1298
+ const error = new require_errors.UnknownToolError(`${obj.name}.${name}`, (obj.tools ?? []).map((tool) => `${obj.name}.${tool.name}`));
1299
+ iteration.recordError(error);
1300
+ throw error;
1301
+ });
1302
+ }
1303
+ for (const tool of iteration.tools) {
1304
+ const wrapped = wrapTool({
1305
+ tool,
1306
+ iteration,
1307
+ beforeHook: onBeforeTool,
1308
+ afterHook: onAfterTool,
1309
+ onTruncation,
1310
+ onResult: onToolResult,
1311
+ controller,
1312
+ onThink: javascriptApi === null || javascriptApi === void 0 ? void 0 : javascriptApi.requestInspection
1313
+ });
1314
+ const callable = javascriptApi ? (input) => {
1315
+ var _vmContext$VM_CALL_SI2;
1316
+ const line = (_vmContext$VM_CALL_SI2 = vmContext[require_vm.VM_CALL_SITE]) === null || _vmContext$VM_CALL_SI2 === void 0 ? void 0 : _vmContext$VM_CALL_SI2.call(vmContext);
1317
+ return javascriptApi.track(() => wrapped(input, line));
1318
+ } : wrapped;
1319
+ for (const key of [tool.name, ...tool.aliases ?? []]) vmContext[key] = callable;
1320
+ }
1321
+ return vmContext;
1322
+ };
1323
+ /** Nested edits must go through whole-property assignment so its schema always runs. */
1324
+ function freezePropertyValue(value) {
1325
+ if (value && typeof value === "object") {
1326
+ for (const child of Object.values(value)) freezePropertyValue(child);
1327
+ Object.freeze(value);
1328
+ }
1329
+ return value;
1330
+ }
1331
+ //#endregion
1332
+ //#region src/runtime/execute.ts
1333
+ /** Each iteration joins generation and execution before settling its transcript. */
1334
+ async function executeContext(props) {
1335
+ await require_utils.init();
1336
+ const result = await executeContextInternal(props);
1337
+ try {
1338
+ var _result$context$chat, _result$context$chat$;
1339
+ await ((_result$context$chat = result.context.chat) === null || _result$context$chat === void 0 || (_result$context$chat$ = _result$context$chat.onExecutionDone) === null || _result$context$chat$ === void 0 ? void 0 : _result$context$chat$.call(_result$context$chat, result));
1340
+ } catch {}
1341
+ return result;
1342
+ }
1343
+ async function executeContextInternal(props) {
1344
+ var _props$options, _props$options2, _props$options3, _props$options4, _props$options5, _props$options6, _props$options7;
1345
+ const controller = createJoinedAbortController([props.signal]);
1346
+ const ctx = new require_custom_client.Context({
1347
+ ...props,
1348
+ loop: (_props$options = props.options) === null || _props$options === void 0 ? void 0 : _props$options.loop,
1349
+ timeout: (_props$options2 = props.options) === null || _props$options2 === void 0 ? void 0 : _props$options2.timeout,
1350
+ maxTokens: (_props$options3 = props.options) === null || _props$options3 === void 0 ? void 0 : _props$options3.maxTokens,
1351
+ toolResultMaxTokens: (_props$options4 = props.options) === null || _props$options4 === void 0 ? void 0 : _props$options4.toolResultMaxTokens,
1352
+ maxTimeToFirstToken: (_props$options5 = props.options) === null || _props$options5 === void 0 ? void 0 : _props$options5.maxTimeToFirstToken,
1353
+ midStreamFallback: (_props$options6 = props.options) === null || _props$options6 === void 0 ? void 0 : _props$options6.midStreamFallback,
1354
+ transcriptionModel: (_props$options7 = props.options) === null || _props$options7 === void 0 ? void 0 : _props$options7.transcriptionModel
1355
+ });
1356
+ let release;
1357
+ try {
1358
+ var _props$options8, _ctx$iterations$at;
1359
+ if ("snapshot" in props) throw new require_errors.InvalidConfigurationError("Snapshots and external pause/resume are no longer supported. Use a session for conversation history and memory.");
1360
+ if ("messages" in props) throw new require_errors.InvalidConfigurationError("Append input with session.append(message) before calling execute(). execute.messages is no longer supported.");
1361
+ if (((_props$options8 = props.options) === null || _props$options8 === void 0 ? void 0 : _props$options8.requireChatResponse) !== void 0 && typeof props.options.requireChatResponse !== "boolean") throw new require_errors.InvalidConfigurationError("Invalid requireChatResponse. Expected a boolean.");
1362
+ release = ctx.session.acquire();
1363
+ prepareSession(ctx);
1364
+ const client = props.client ?? new _botpress_client.Client();
1365
+ const execution = {
1366
+ ctx,
1367
+ props,
1368
+ cognitive: _botpress_cognitive.Cognitive.isCognitiveClient(client) || require_custom_client._CustomModelClient.isCustomClient(client) ? client : new _botpress_cognitive.Cognitive({ client }),
1369
+ controller
1370
+ };
1371
+ while (ctx.iterations.length < ctx.loop) {
1372
+ const result = await executeNextIteration(execution);
1373
+ if (result) {
1374
+ if (result.isSuccess()) ctx.session.completeTurn();
1375
+ return result;
1376
+ }
1377
+ }
1378
+ const error = new require_errors.LoopExceededError(ctx.loop);
1379
+ (_ctx$iterations$at = ctx.iterations.at(-1)) === null || _ctx$iterations$at === void 0 || _ctx$iterations$at.recordError(error);
1380
+ return new require_custom_client.ErrorExecutionResult(ctx, error);
1381
+ } catch (error) {
1382
+ return new require_custom_client.ErrorExecutionResult(ctx, error);
1383
+ } finally {
1384
+ release === null || release === void 0 || release();
1385
+ }
1386
+ }
1387
+ function prepareSession(ctx) {
1388
+ if (ctx.chat && ctx.session.turn > 0 && !ctx.session.hasActiveTurn && !ctx.session.pendingMessages.length) throw new require_errors.SessionStateError("No pending input. Append a message to the session before starting another chat turn.");
1389
+ ctx.session.beginTurn();
1390
+ }
1391
+ async function executeNextIteration(execution) {
1392
+ const { ctx, props, controller } = execution;
1393
+ let onTrace = props.onTrace;
1394
+ const iterationNumber = ctx.iterations.length + 1;
1395
+ const iteration = await ctx.nextIteration((trace) => {
1396
+ onTrace === null || onTrace === void 0 || onTrace({
1397
+ trace,
1398
+ iteration: iterationNumber,
1399
+ controller
1400
+ });
1401
+ });
1402
+ const state = {
1403
+ ...execution,
1404
+ iteration,
1405
+ inspectionValues: new InspectionValues()
1406
+ };
1407
+ try {
1408
+ await executeIteration(state);
1409
+ } catch (error) {
1410
+ handleIterationFailure(state, error);
1411
+ } finally {
1412
+ try {
1413
+ try {
1414
+ var _state$capture;
1415
+ state.memory ??= commitMemory(state, (_state$capture = state.capture) === null || _state$capture === void 0 ? void 0 : _state$capture.result);
1416
+ } catch (error) {
1417
+ failFinalization(state, error);
1418
+ }
1419
+ const memory = state.memory;
1420
+ for (const failure of memory.unavailable) iteration.recordError(new require_errors.MemoryValueError(`Memory variable "${failure.name}": ${failure.reason}`));
1421
+ const outcome = getExecutionOutcome(state, memory);
1422
+ if (state.capture) {
1423
+ var _iteration$sessionInf;
1424
+ ctx.session.appendToolResult(iteration.id, state.capture.call.id, renderExecutionReport({
1425
+ outcome,
1426
+ memory,
1427
+ activity: getExecutionActivity(iteration),
1428
+ source: {
1429
+ requested: state.capture.call.code,
1430
+ executed: iteration.code
1431
+ },
1432
+ requiresExit: !iteration.isChatEnabled,
1433
+ identity: {
1434
+ sessionId: ctx.session.id,
1435
+ ...iteration.sessionInfo,
1436
+ iterationId: iteration.id,
1437
+ iteration: (_iteration$sessionInf = iteration.sessionInfo) === null || _iteration$sessionInf === void 0 ? void 0 : _iteration$sessionInf.number
1438
+ },
1439
+ inspector: ctx.inspector,
1440
+ maxTokens: ctx.toolResultMaxTokens,
1441
+ policies: state.inspectionValues.getPolicy
1442
+ }));
1443
+ }
1444
+ try {
1445
+ ctx.session.settleIteration(iteration.id, {
1446
+ outcome: iteration.status.type,
1447
+ error: iteration.error ?? void 0
1448
+ });
1449
+ } catch (error) {
1450
+ if (!require_errors.MemoryCapacityError.is(error)) throw error;
1451
+ failFinalization(state, error);
1452
+ ctx.session.settleIteration(iteration.id, { outcome: "error" });
1453
+ }
1454
+ await finalizeIteration({
1455
+ iteration,
1456
+ controller,
1457
+ onIterationEnd: props.onIterationEnd
1458
+ });
1459
+ } finally {
1460
+ onTrace = void 0;
1461
+ }
1462
+ }
1463
+ return getIterationResult(state);
1464
+ }
1465
+ async function executeIteration(state) {
1466
+ const { ctx, props, iteration, cognitive, controller } = state;
1467
+ await callHook(() => {
1468
+ var _props$onIterationSta;
1469
+ return (_props$onIterationSta = props.onIterationStart) === null || _props$onIterationSta === void 0 ? void 0 : _props$onIterationSta.call(props, iteration, controller, ctx);
1470
+ });
1471
+ controller.signal.throwIfAborted();
1472
+ let execution;
1473
+ let assistantCommitted = false;
1474
+ try {
1475
+ var _iteration$response;
1476
+ const generated = await generateCode({
1477
+ iteration,
1478
+ ctx,
1479
+ cognitive,
1480
+ controller,
1481
+ metadata: props.metadata,
1482
+ onSendDelta: (_iteration$response = iteration.response) === null || _iteration$response === void 0 ? void 0 : _iteration$response.onDelta,
1483
+ onBeforeRequest: props.onBeforeRequest,
1484
+ onToolCalls: (calls) => {
1485
+ var _iteration$response2;
1486
+ if (ctx.chat && !((_iteration$response2 = iteration.response) === null || _iteration$response2 === void 0 ? void 0 : _iteration$response2.onDelta)) return false;
1487
+ const validation = require_native.validateNativeToolCalls(calls);
1488
+ const call = validation.valid ? validation.call : void 0;
1489
+ if (!call) return false;
1490
+ if (ctx.session.messages.some((message) => {
1491
+ var _message$toolCalls;
1492
+ return (_message$toolCalls = message.toolCalls) === null || _message$toolCalls === void 0 ? void 0 : _message$toolCalls.some((previous) => previous.id === call.id);
1493
+ })) throw new require_errors.CognitiveError("Native call IDs must be unique in retained session history.");
1494
+ execution = startJavaScriptCall(state, call);
1495
+ return true;
1496
+ }
1497
+ });
1498
+ await (execution === null || execution === void 0 ? void 0 : execution.result);
1499
+ controller.signal.throwIfAborted();
1500
+ const validation = require_native.validateNativeToolCalls(generated.toolCalls);
1501
+ ctx.session.appendAssistant(iteration.id, generated);
1502
+ assistantCommitted = true;
1503
+ if (!validation.valid) {
1504
+ await rejectNativeBatch(state, generated, validation.errors);
1505
+ return;
1506
+ }
1507
+ await deliverAssistantText(state, generated);
1508
+ const call = validation.call;
1509
+ if (call) {
1510
+ execution ??= startJavaScriptCall(state, call);
1511
+ await settleJavaScriptCall(state, execution);
1512
+ }
1513
+ if (iteration.status.type === "pending") await finishNativeResponse(state, generated);
1514
+ } catch (error) {
1515
+ if (execution) await preserveInterruptedExecution(state, execution, error, assistantCommitted);
1516
+ throw error;
1517
+ }
1518
+ }
1519
+ async function rejectNativeBatch({ ctx, iteration }, generated, errors) {
1520
+ var _iteration$response3;
1521
+ const message = [reportSection("error", `Native tool batch rejected before execution:\n${ctx.inspector(errors.join("\n"), {
1522
+ purpose: "error",
1523
+ maxTokens: 500
1524
+ })}`, 500), reportSection("recovery", "No code ran and no actions were performed. Call run_javascript with exactly one non-empty code string.")].join("\n\n");
1525
+ for (const call of generated.toolCalls) ctx.session.appendToolResult(iteration.id, call.id, message);
1526
+ if (generated.output && ((_iteration$response3 = iteration.response) === null || _iteration$response3 === void 0 ? void 0 : _iteration$response3.onDelta)) try {
1527
+ await iteration.response.onDelta({
1528
+ restart: true,
1529
+ iterationId: iteration.id,
1530
+ attempt: generated.attempt + 1,
1531
+ fromModel: generated.metadata.model ?? "unknown",
1532
+ toModel: generated.metadata.model ?? "unknown",
1533
+ reason: message
1534
+ });
1535
+ } catch (error) {
1536
+ throw new require_errors.CognitiveError(`Could not retract the rejected response: ${require_utils.getErrorMessage(error)}`);
1537
+ }
1538
+ iteration.end({
1539
+ type: "invalid_code_error",
1540
+ invalid_code_error: { message }
1541
+ }, generated.toolCalls.some((call) => call.name !== "run_javascript") ? new require_errors.UnknownToolError(generated.toolCalls.find((call) => call.name !== "run_javascript").name, ["run_javascript"], message) : new require_errors.NativeProtocolError(message));
1542
+ }
1543
+ async function deliverAssistantText(state, generated) {
1544
+ var _iteration$response4;
1545
+ const { ctx, iteration } = state;
1546
+ if (!generated.output.trim() || !ctx.chat || !((_iteration$response4 = iteration.response) === null || _iteration$response4 === void 0 ? void 0 : _iteration$response4.handler)) return;
1547
+ const startedAt = Date.now();
1548
+ const message = {
1549
+ type: "text",
1550
+ text: generated.output
1551
+ };
1552
+ try {
1553
+ await iteration.response.handler(generated.output.trim(), generated.messageMetadata);
1554
+ } catch (cause) {
1555
+ if (require_errors.isCriticalError(cause)) throw cause;
1556
+ throw new require_errors.DeliveryError(`Assistant response delivery failed: ${require_utils.getErrorMessage(cause)}`, { cause });
1557
+ }
1558
+ ctx.session.recordAssistantDelivery(iteration.id);
1559
+ iteration.recordTrace({
1560
+ type: "message_delivery",
1561
+ value: message,
1562
+ started_at: startedAt,
1563
+ ended_at: Date.now()
1564
+ });
1565
+ }
1566
+ function startJavaScriptCall(state, call) {
1567
+ const { iteration, controller } = state;
1568
+ iteration.code = call.code;
1569
+ iteration.nativeCallId = call.id;
1570
+ const api = createJavaScriptApi({
1571
+ iteration,
1572
+ components: iteration.components,
1573
+ exits: iteration.exits,
1574
+ signal: controller.signal,
1575
+ deliver: (messages) => deliverJavaScriptMessages(state, messages),
1576
+ onError: (error) => iteration.recordError(error)
1577
+ });
1578
+ return {
1579
+ call,
1580
+ api,
1581
+ result: executeJavaScript(state, api)
1582
+ };
1583
+ }
1584
+ async function settleJavaScriptCall(state, execution) {
1585
+ const { iteration, controller } = state;
1586
+ const { call, api } = execution;
1587
+ const result = await execution.result;
1588
+ const outcome = result.success && !result.signal ? api.getTerminalOutcome() ?? api.resolve(result.return_value) : void 0;
1589
+ removeCapturedDecisions(result, api);
1590
+ state.capture = {
1591
+ call,
1592
+ result,
1593
+ inspected: (outcome === null || outcome === void 0 ? void 0 : outcome.type) === "inspect"
1594
+ };
1595
+ if ((outcome === null || outcome === void 0 ? void 0 : outcome.type) === "inspect" && result.success) result.return_value = outcome.value;
1596
+ const forcedInspections = api.getForcedInspections();
1597
+ if (forcedInspections.length && !controller.signal.aborted && !require_errors.isCriticalError(result.error)) {
1598
+ if (!result.success && result.error) {
1599
+ iteration.recordError(result.error);
1600
+ state.capture.downstreamError = result.error;
1601
+ }
1602
+ state.capture.forcedInspections = forcedInspections;
1603
+ let value = forcedInspections.length === 1 ? forcedInspections[0].value : forcedInspections.map((entry) => entry.value);
1604
+ if ((outcome === null || outcome === void 0 ? void 0 : outcome.type) === "inspect") value = outcome.value;
1605
+ state.capture.result = {
1606
+ ...result,
1607
+ success: true,
1608
+ signal: void 0,
1609
+ return_value: value
1610
+ };
1611
+ iteration.end({
1612
+ type: "thinking_requested",
1613
+ thinking_requested: {
1614
+ reason: "Tools completed successfully and requested forced inspection.",
1615
+ variables: value,
1616
+ metadata: forcedInspections.length === 1 ? forcedInspections[0].metadata : void 0
1617
+ }
1618
+ });
1619
+ return;
1620
+ }
1621
+ if ((outcome === null || outcome === void 0 ? void 0 : outcome.type) === "exit") {
1622
+ await completeJavaScriptExit(state, result, outcome);
1623
+ return;
1624
+ }
1625
+ if (result.success && containsDecision(result.return_value, api)) {
1626
+ result.captureErrors ??= [];
1627
+ result.captureErrors.push({
1628
+ name: "$return",
1629
+ reason: "Execution decisions cannot be nested inside returned data. Use return inspect(value) with plain values."
1630
+ });
1631
+ }
1632
+ endJavaScriptIteration(iteration, controller, result);
1633
+ }
1634
+ async function preserveInterruptedExecution(state, execution, error, assistantCommitted) {
1635
+ const { ctx, iteration, controller } = state;
1636
+ execution.api.complete();
1637
+ const result = await execution.result;
1638
+ if (state.memory) return;
1639
+ if (!assistantCommitted) ctx.session.appendAssistant(iteration.id, {
1640
+ output: "",
1641
+ toolCalls: [{
1642
+ id: execution.call.id,
1643
+ name: "run_javascript",
1644
+ input: { code: execution.call.code }
1645
+ }]
1646
+ });
1647
+ removeCapturedDecisions(result, execution.api);
1648
+ if (iteration.status.type === "pending") endFailedIteration(iteration, controller, error);
1649
+ const interrupted = {
1650
+ ...result,
1651
+ success: false,
1652
+ signal: void 0,
1653
+ error: error instanceof Error ? error : new Error(require_utils.getErrorMessage(error)),
1654
+ traces: []
1655
+ };
1656
+ state.capture = {
1657
+ call: execution.call,
1658
+ result: interrupted,
1659
+ inspected: false,
1660
+ interrupted: true
1661
+ };
1662
+ }
1663
+ function removeCapturedDecisions(result, api) {
1664
+ for (const [name, value] of Object.entries(result.variables)) if (containsDecision(value, api)) {
1665
+ delete result.variables[name];
1666
+ result.captureErrors ??= [];
1667
+ result.captureErrors.push({
1668
+ name,
1669
+ reason: "Execution decisions cannot be retained as memory variables."
1670
+ });
1671
+ }
1672
+ }
1673
+ function containsDecision(value, api, seen = /* @__PURE__ */ new Set()) {
1674
+ if (api.isReceipt(value)) return true;
1675
+ if (value === null || typeof value !== "object" || seen.has(value)) return false;
1676
+ seen.add(value);
1677
+ return Object.values(value).some((nested) => containsDecision(nested, api, seen));
1678
+ }
1679
+ async function completeJavaScriptExit(state, result, outcome) {
1680
+ const { iteration, controller } = state;
1681
+ state.memory = commitMemory(state, result, false);
1682
+ try {
1683
+ controller.signal.throwIfAborted();
1684
+ await applyNativeExit(state, outcome.exit, outcome.value);
1685
+ } catch (error) {
1686
+ endFailedIteration(iteration, controller, error);
1687
+ }
1688
+ }
1689
+ async function deliverJavaScriptMessages({ ctx, iteration, controller }, messages) {
1690
+ if (!messages.length) return;
1691
+ if (!ctx.chat) throw new require_errors.DeliveryError("Component delivery requires chat mode.");
1692
+ for (const message of messages) {
1693
+ controller.signal.throwIfAborted();
1694
+ const startedAt = Date.now();
1695
+ try {
1696
+ if (!require_component.isAnyComponent(message.component)) throw new require_errors.DeliveryError("Only registered rich components can be delivered from JavaScript.");
1697
+ const component = iteration.components.get(message.component.name);
1698
+ if (!(component === null || component === void 0 ? void 0 : component.handler)) throw new require_errors.DeliveryError(`Component "${message.component.name}" has no registered handler.`);
1699
+ await component.handler(message.component.props, {
1700
+ iterationId: iteration.id,
1701
+ id: message.id
1702
+ });
1703
+ } catch (error) {
1704
+ iteration.recordTrace({
1705
+ type: "message_delivery",
1706
+ value: message.component,
1707
+ message_id: message.id,
1708
+ native_call_id: iteration.nativeCallId,
1709
+ success: false,
1710
+ error: require_utils.getErrorMessage(error),
1711
+ started_at: startedAt,
1712
+ ended_at: Date.now()
1713
+ });
1714
+ throw require_errors.isCriticalError(error) ? error : new require_errors.DeliveryError(`Delivery ${message.id} failed: ${require_utils.getErrorMessage(error)}. Its external outcome is uncertain. Later messages were skipped; earlier acknowledged messages remain delivered.`, { cause: error });
1715
+ }
1716
+ ctx.session.recordAssistantDelivery(iteration.id);
1717
+ iteration.recordTrace({
1718
+ type: "message_delivery",
1719
+ value: message.component,
1720
+ message_id: message.id,
1721
+ native_call_id: iteration.nativeCallId,
1722
+ success: true,
1723
+ started_at: startedAt,
1724
+ ended_at: Date.now()
1725
+ });
1726
+ }
1727
+ }
1728
+ async function finishNativeResponse(state, generated) {
1729
+ const { ctx, iteration } = state;
1730
+ if (!generated.toolCalls.length && ctx.chat && (generated.output.trim() || generated.metadata.stopReason === "stop")) {
1731
+ await applyNativeExit(state, require_custom_client.ListenExit, {});
1732
+ if (!iteration.hasExited()) ctx.session.appendContext(ctx.inspector(iteration.error ?? "Completion rejected.", {
1733
+ purpose: "error",
1734
+ maxTokens: 200
1735
+ }));
1736
+ return;
1737
+ }
1738
+ let reason = iteration.exits.length ? "This is a worker task. Every run_javascript program must explicitly return inspect(value) or return exit(name, payload) with a registered name and a valid payload. Assistant prose alone does not complete the task." : "Every run_javascript program must explicitly return inspect(value). To see a business tool result in the next response, return inspect(result).";
1739
+ if (ctx.chat) reason = generated.toolCalls.length ? "Every run_javascript program must explicitly return inspect(value) or return exit(name, payload). Use return exit(\"listen\") to wait for the user." : "Reply with assistant text, or use run_javascript with an explicit return inspect(value) or return exit(name, payload). Use return exit(\"listen\") to wait for the user.";
1740
+ if (!ctx.chat) reason = `${require_native.WORKER_RESPONSE_INSTRUCTION} ${reason}`;
1741
+ iteration.end({
1742
+ type: "thinking_requested",
1743
+ thinking_requested: {
1744
+ reason,
1745
+ variables: {}
1746
+ }
1747
+ });
1748
+ if (!generated.toolCalls.length) ctx.session.appendContext(reason);
1749
+ }
1750
+ function commitMemory(state, result, includeReturn = true) {
1751
+ const { ctx, iteration, controller } = state;
1752
+ const report = ctx.session.commitIteration({
1753
+ ...iteration.sessionInfo,
1754
+ timestamp: Date.now(),
1755
+ variables: result === null || result === void 0 ? void 0 : result.variables,
1756
+ variableWrites: result === null || result === void 0 ? void 0 : result.variableWrites,
1757
+ captureErrors: result === null || result === void 0 ? void 0 : result.captureErrors,
1758
+ hasResult: includeReturn && !!(result === null || result === void 0 ? void 0 : result.success) && !result.signal && !controller.signal.aborted,
1759
+ result: (result === null || result === void 0 ? void 0 : result.success) ? result.return_value : void 0
1760
+ });
1761
+ state.memory = report;
1762
+ for (const mutation of iteration.mutations) {
1763
+ const trace = [...iteration.traces].reverse().find((trace) => trace.type === "property" && trace.object === mutation.object && trace.property === mutation.property);
1764
+ const changes = ctx.session.memory.recordObjectMutations([mutation], {
1765
+ ...iteration.sessionInfo,
1766
+ timestamp: (trace === null || trace === void 0 ? void 0 : trace.started_at) ?? Date.now()
1767
+ });
1768
+ report.updated.push(...changes);
1769
+ }
1770
+ return report;
1771
+ }
1772
+ function failFinalization(state, error) {
1773
+ const { iteration } = state;
1774
+ iteration.status = {
1775
+ type: "execution_error",
1776
+ execution_error: {
1777
+ message: require_utils.getErrorMessage(error),
1778
+ stack: executionErrorStack(error)
1779
+ }
1780
+ };
1781
+ iteration.ended_ts = Date.now();
1782
+ iteration.exception = iteration.recordError(error);
1783
+ state.terminalError = error;
1784
+ state.memory ??= {
1785
+ created: [],
1786
+ updated: [],
1787
+ unavailable: [],
1788
+ resultAvailable: false
1789
+ };
1790
+ }
1791
+ function getExecutionOutcome(state, memory) {
1792
+ const { iteration, capture } = state;
1793
+ const status = iteration.status;
1794
+ if (status.type === "aborted") return {
1795
+ type: "cancelled",
1796
+ message: status.aborted.reason
1797
+ };
1798
+ if (capture === null || capture === void 0 ? void 0 : capture.interrupted) return {
1799
+ type: "interrupted",
1800
+ reason: "stream",
1801
+ message: iteration.error ?? void 0
1802
+ };
1803
+ if (status.type === "exit_success") return {
1804
+ type: "exit",
1805
+ name: status.exit_success.exit_name,
1806
+ value: status.exit_success.return_value
1807
+ };
1808
+ if (status.type === "exit_error") return {
1809
+ type: "error",
1810
+ exitName: status.exit_error.exit,
1811
+ message: status.exit_error.message,
1812
+ error: iteration.exception
1813
+ };
1814
+ if (status.type === "thinking_requested") {
1815
+ const thinking = status.thinking_requested;
1816
+ if (thinking.interrupted) {
1817
+ var _capture$result$signa;
1818
+ return {
1819
+ type: "interrupted",
1820
+ reason: "thinking",
1821
+ message: thinking.reason,
1822
+ context: thinking.variables,
1823
+ stacktrace: capture === null || capture === void 0 || (_capture$result$signa = capture.result.signal) === null || _capture$result$signa === void 0 ? void 0 : _capture$result$signa.stack
1824
+ };
1825
+ }
1826
+ return {
1827
+ type: "inspect",
1828
+ value: (capture === null || capture === void 0 ? void 0 : capture.result.success) ? capture.result.return_value : void 0,
1829
+ available: memory.resultAvailable,
1830
+ explicit: (capture === null || capture === void 0 ? void 0 : capture.inspected) ?? false,
1831
+ forcedInspections: capture === null || capture === void 0 ? void 0 : capture.forcedInspections,
1832
+ downstreamError: capture === null || capture === void 0 ? void 0 : capture.downstreamError
1833
+ };
1834
+ }
1835
+ return {
1836
+ type: "error",
1837
+ message: iteration.error ?? "Execution failed.",
1838
+ error: iteration.exception ?? (capture === null || capture === void 0 ? void 0 : capture.result.error)
1839
+ };
1840
+ }
1841
+ function handleIterationFailure(state, error) {
1842
+ const { ctx, iteration, controller } = state;
1843
+ if (iteration.status.type === "pending") endFailedIteration(iteration, controller, error);
1844
+ if (require_errors.MemoryCapacityError.is(error)) state.memory ??= {
1845
+ created: [],
1846
+ updated: [],
1847
+ unavailable: [],
1848
+ resultAvailable: false
1849
+ };
1850
+ const pending = ctx.session.pendingCalls.filter((call) => call.iterationId === iteration.id);
1851
+ for (const call of pending) {
1852
+ var _state$capture2;
1853
+ if (call.callId === ((_state$capture2 = state.capture) === null || _state$capture2 === void 0 ? void 0 : _state$capture2.call.id)) continue;
1854
+ const outcome = call.callId === iteration.nativeCallId ? "This call failed without a confirmed successful result; its external effects may be incomplete." : "This call was skipped and did not run.";
1855
+ ctx.session.appendToolResult(iteration.id, call.callId, `Execution stopped: ${ctx.inspector(require_utils.getErrorMessage(error), {
1856
+ purpose: "error",
1857
+ maxTokens: 200
1858
+ })}. ${outcome} Earlier acknowledged calls remain completed.`);
1859
+ }
1860
+ if (require_errors.isCriticalError(error) || controller.signal.aborted) {
1861
+ state.terminalError = controller.signal.aborted ? new require_errors.ExecutionAbortedError(require_utils.getErrorMessage(controller.signal.reason ?? error), { cause: controller.signal.reason ?? error }) : error;
1862
+ return;
1863
+ }
1864
+ if (ctx.session.pendingCalls.length) return;
1865
+ ctx.session.appendContext(`Execution stopped: ${ctx.inspector(require_utils.getErrorMessage(error), {
1866
+ purpose: "error",
1867
+ maxTokens: 200
1868
+ })}. Continue using the retained state.`);
1869
+ }
1870
+ function endFailedIteration(iteration, controller, error) {
1871
+ if (controller.signal.aborted) {
1872
+ iteration.end({
1873
+ type: "aborted",
1874
+ aborted: { reason: require_utils.getErrorMessage(controller.signal.reason ?? error) }
1875
+ }, new require_errors.ExecutionAbortedError(require_utils.getErrorMessage(controller.signal.reason ?? error), { cause: controller.signal.reason ?? error }));
1876
+ return;
1877
+ }
1878
+ if (require_errors.CognitiveError.is(error) || require_errors.TokenOverflowError.is(error) || require_errors.CompactionError.is(error)) {
1879
+ iteration.end({
1880
+ type: "generation_error",
1881
+ generation_error: { message: error.message }
1882
+ }, error);
1883
+ return;
1884
+ }
1885
+ if (require_errors.ThinkSignal.is(error)) {
1886
+ iteration.end({
1887
+ type: "thinking_requested",
1888
+ thinking_requested: {
1889
+ reason: error.reason,
1890
+ variables: error.context,
1891
+ interrupted: true
1892
+ }
1893
+ });
1894
+ return;
1895
+ }
1896
+ iteration.end({
1897
+ type: "execution_error",
1898
+ execution_error: {
1899
+ message: require_utils.getErrorMessage(error),
1900
+ stack: executionErrorStack(error)
1901
+ }
1902
+ }, error);
1903
+ }
1904
+ function executionErrorStack(error) {
1905
+ if (require_errors.CodeExecutionError.is(error) && error.stacktrace) return error.stacktrace;
1906
+ if (require_errors.HookError.is(error) && error.cause instanceof Error) return require_errors.cleanStackTrace(error.cause.stack ?? "");
1907
+ if (error instanceof Error) return require_errors.cleanStackTrace(error.stack ?? "");
1908
+ return "";
1909
+ }
1910
+ function getIterationResult(state) {
1911
+ const { ctx, iteration } = state;
1912
+ const critical = iteration.errors.find(require_errors.isCriticalError);
1913
+ state.terminalError ??= critical;
1914
+ if (state.terminalError !== void 0) return new require_custom_client.ErrorExecutionResult(ctx, state.terminalError);
1915
+ if (iteration.status.type === "exit_success") {
1916
+ const outcome = iteration.status.exit_success;
1917
+ return new require_custom_client.SuccessExecutionResult(ctx, {
1918
+ exit: iteration.exits.find((exit) => exit.name === outcome.exit_name),
1919
+ result: outcome.return_value
1920
+ });
1921
+ }
1922
+ if (iteration.status.type === "aborted") return new require_custom_client.ErrorExecutionResult(ctx, iteration.error);
1923
+ }
1924
+ async function applyNativeExit(state, exit, value) {
1925
+ const { ctx, iteration, controller, props } = state;
1926
+ try {
1927
+ var _props$options9;
1928
+ if (ctx.chat && exit === require_custom_client.ListenExit && ((_props$options9 = props.options) === null || _props$options9 === void 0 ? void 0 : _props$options9.requireChatResponse) !== false && ctx.session.lastSpeaker !== "assistant") throw new require_errors.MissingChatResponseError("The assistant has not delivered a message since the last user message. Send a response using the inspected results before waiting for the user. Do not repeat completed tool calls.");
1929
+ await callHook(() => {
1930
+ var _props$onExit;
1931
+ return (_props$onExit = props.onExit) === null || _props$onExit === void 0 ? void 0 : _props$onExit.call(props, {
1932
+ exit,
1933
+ result: value
1934
+ }, controller);
1935
+ });
1936
+ controller.signal.throwIfAborted();
1937
+ iteration.end({
1938
+ type: "exit_success",
1939
+ exit_success: {
1940
+ exit_name: exit.name,
1941
+ return_value: value
1942
+ }
1943
+ });
1944
+ } catch (error) {
1945
+ if (controller.signal.aborted) throw error;
1946
+ iteration.end({
1947
+ type: "exit_error",
1948
+ exit_error: {
1949
+ exit: exit.name,
1950
+ message: require_utils.getErrorMessage(error),
1951
+ return_value: value
1952
+ }
1953
+ }, error);
1954
+ }
1955
+ }
1956
+ async function executeJavaScript(state, api) {
1957
+ const { iteration, ctx, controller, props } = state;
1958
+ const startedAt = Date.now();
1959
+ let result;
1960
+ try {
1961
+ const override = await callHook(() => {
1962
+ var _props$onBeforeExecut;
1963
+ return (_props$onBeforeExecut = props.onBeforeExecution) === null || _props$onBeforeExecut === void 0 ? void 0 : _props$onBeforeExecut.call(props, iteration, controller);
1964
+ });
1965
+ if (typeof (override === null || override === void 0 ? void 0 : override.code) === "string") iteration.code = override.code;
1966
+ controller.signal.throwIfAborted();
1967
+ const code = iteration.code;
1968
+ ctx.session.memory.assertNamesAvailable(require_vm.compile(code).variables);
1969
+ const vmContext = buildVMContext({
1970
+ ctx,
1971
+ iteration,
1972
+ controller,
1973
+ onBeforeTool: props.onBeforeTool,
1974
+ onAfterTool: props.onAfterTool,
1975
+ onTruncation: (value, policy) => state.inspectionValues.capture(value, policy),
1976
+ onToolResult: (value) => state.inspectionValues.captureDefault(value, ctx.toolResultMaxTokens),
1977
+ javascriptApi: api
1978
+ });
1979
+ result = await require_vm.runAsyncFunction(vmContext, code, iteration.traces, controller.signal, ctx.timeout, Object.keys(ctx.session.memory.variables), iteration.recordTrace);
1980
+ } catch (error) {
1981
+ result = interruptedVMResult(error);
1982
+ }
1983
+ try {
1984
+ await api.close();
1985
+ } catch (error) {
1986
+ result = {
1987
+ ...result,
1988
+ success: !!result.signal,
1989
+ error: error instanceof Error ? error : new Error(require_utils.getErrorMessage(error)),
1990
+ traces: []
1991
+ };
1992
+ }
1993
+ const interruption = api.getInterruption();
1994
+ if (interruption && !result.signal) {
1995
+ interruption.variables = result.variables;
1996
+ result = {
1997
+ ...result,
1998
+ success: true,
1999
+ signal: interruption,
2000
+ error: void 0,
2001
+ return_value: void 0
2002
+ };
2003
+ }
2004
+ iteration.recordTrace({
2005
+ type: "code_execution",
2006
+ lines_executed: result.lines_executed,
2007
+ started_at: startedAt,
2008
+ ended_at: Date.now()
2009
+ });
2010
+ return result;
2011
+ }
2012
+ function interruptedVMResult(error) {
2013
+ if (require_errors.ThinkSignal.is(error)) return {
2014
+ success: true,
2015
+ signal: error,
2016
+ return_value: void 0,
2017
+ variables: {},
2018
+ lines_executed: []
2019
+ };
2020
+ return {
2021
+ success: false,
2022
+ error: error instanceof Error ? error : new Error(require_utils.getErrorMessage(error)),
2023
+ variables: {},
2024
+ lines_executed: [],
2025
+ traces: []
2026
+ };
2027
+ }
2028
+ function endJavaScriptIteration(iteration, controller, result) {
2029
+ if (controller.signal.aborted) {
2030
+ endFailedIteration(iteration, controller, controller.signal.reason);
2031
+ return;
2032
+ }
2033
+ if (!result.success) {
2034
+ if (require_errors.InvalidCodeError.is(result.error)) iteration.end({
2035
+ type: "invalid_code_error",
2036
+ invalid_code_error: { message: result.error.message }
2037
+ }, result.error);
2038
+ else endFailedIteration(iteration, controller, result.error);
2039
+ return;
2040
+ }
2041
+ if (require_errors.ThinkSignal.is(result.signal)) {
2042
+ iteration.end({
2043
+ type: "thinking_requested",
2044
+ thinking_requested: {
2045
+ reason: result.signal.reason,
2046
+ variables: result.signal.context,
2047
+ metadata: result.signal.metadata,
2048
+ interrupted: true
2049
+ }
2050
+ });
2051
+ return;
2052
+ }
2053
+ iteration.end({
2054
+ type: "thinking_requested",
2055
+ thinking_requested: {
2056
+ reason: "JavaScript completed. Inspect the return value and memory changes.",
2057
+ variables: {}
2058
+ }
2059
+ });
2060
+ }
2061
+ //#endregion
2062
+ exports.executeContext = executeContext;