llmz 0.9.0 → 1.0.1

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