@nhtio/adk 0.1.0-master-f0aa531d

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 (297) hide show
  1. package/LICENSE.md +9 -0
  2. package/README.md +3 -0
  3. package/batteries/index.d.ts +28 -0
  4. package/batteries/llm/index.d.ts +11 -0
  5. package/batteries/llm/openai_chat_completions/adapter.cjs +916 -0
  6. package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -0
  7. package/batteries/llm/openai_chat_completions/adapter.d.ts +101 -0
  8. package/batteries/llm/openai_chat_completions/adapter.mjs +914 -0
  9. package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -0
  10. package/batteries/llm/openai_chat_completions/exceptions.cjs +89 -0
  11. package/batteries/llm/openai_chat_completions/exceptions.cjs.map +1 -0
  12. package/batteries/llm/openai_chat_completions/exceptions.d.ts +97 -0
  13. package/batteries/llm/openai_chat_completions/exceptions.mjs +81 -0
  14. package/batteries/llm/openai_chat_completions/exceptions.mjs.map +1 -0
  15. package/batteries/llm/openai_chat_completions/helpers.cjs +819 -0
  16. package/batteries/llm/openai_chat_completions/helpers.cjs.map +1 -0
  17. package/batteries/llm/openai_chat_completions/helpers.d.ts +233 -0
  18. package/batteries/llm/openai_chat_completions/helpers.mjs +783 -0
  19. package/batteries/llm/openai_chat_completions/helpers.mjs.map +1 -0
  20. package/batteries/llm/openai_chat_completions/index.d.ts +27 -0
  21. package/batteries/llm/openai_chat_completions/types.cjs +1 -0
  22. package/batteries/llm/openai_chat_completions/types.d.ts +524 -0
  23. package/batteries/llm/openai_chat_completions/types.mjs +0 -0
  24. package/batteries/llm/openai_chat_completions/validation.cjs +190 -0
  25. package/batteries/llm/openai_chat_completions/validation.cjs.map +1 -0
  26. package/batteries/llm/openai_chat_completions/validation.d.ts +31 -0
  27. package/batteries/llm/openai_chat_completions/validation.mjs +187 -0
  28. package/batteries/llm/openai_chat_completions/validation.mjs.map +1 -0
  29. package/batteries/llm/openai_chat_completions.cjs +51 -0
  30. package/batteries/llm/openai_chat_completions.mjs +5 -0
  31. package/batteries/llm/webllm_chat_completions/adapter.cjs +658 -0
  32. package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -0
  33. package/batteries/llm/webllm_chat_completions/adapter.d.ts +103 -0
  34. package/batteries/llm/webllm_chat_completions/adapter.mjs +656 -0
  35. package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -0
  36. package/batteries/llm/webllm_chat_completions/exceptions.cjs +70 -0
  37. package/batteries/llm/webllm_chat_completions/exceptions.cjs.map +1 -0
  38. package/batteries/llm/webllm_chat_completions/exceptions.d.ts +74 -0
  39. package/batteries/llm/webllm_chat_completions/exceptions.mjs +65 -0
  40. package/batteries/llm/webllm_chat_completions/exceptions.mjs.map +1 -0
  41. package/batteries/llm/webllm_chat_completions/helpers.cjs +38 -0
  42. package/batteries/llm/webllm_chat_completions/helpers.d.ts +6 -0
  43. package/batteries/llm/webllm_chat_completions/helpers.mjs +2 -0
  44. package/batteries/llm/webllm_chat_completions/index.d.ts +25 -0
  45. package/batteries/llm/webllm_chat_completions/types.d.ts +31 -0
  46. package/batteries/llm/webllm_chat_completions/validation.cjs +115 -0
  47. package/batteries/llm/webllm_chat_completions/validation.cjs.map +1 -0
  48. package/batteries/llm/webllm_chat_completions/validation.d.ts +8 -0
  49. package/batteries/llm/webllm_chat_completions/validation.mjs +112 -0
  50. package/batteries/llm/webllm_chat_completions/validation.mjs.map +1 -0
  51. package/batteries/llm/webllm_chat_completions.cjs +50 -0
  52. package/batteries/llm/webllm_chat_completions.mjs +6 -0
  53. package/batteries/llm.cjs +63 -0
  54. package/batteries/llm.mjs +10 -0
  55. package/batteries/storage/flydrive/index.d.ts +167 -0
  56. package/batteries/storage/flydrive.cjs +249 -0
  57. package/batteries/storage/flydrive.cjs.map +1 -0
  58. package/batteries/storage/flydrive.mjs +249 -0
  59. package/batteries/storage/flydrive.mjs.map +1 -0
  60. package/batteries/storage/in_memory/index.d.ts +106 -0
  61. package/batteries/storage/in_memory.cjs +121 -0
  62. package/batteries/storage/in_memory.cjs.map +1 -0
  63. package/batteries/storage/in_memory.mjs +119 -0
  64. package/batteries/storage/in_memory.mjs.map +1 -0
  65. package/batteries/storage/index.d.ts +18 -0
  66. package/batteries/storage/opfs/index.d.ts +299 -0
  67. package/batteries/storage/opfs.cjs +368 -0
  68. package/batteries/storage/opfs.cjs.map +1 -0
  69. package/batteries/storage/opfs.mjs +366 -0
  70. package/batteries/storage/opfs.mjs.map +1 -0
  71. package/batteries/storage.cjs +4 -0
  72. package/batteries/storage.mjs +2 -0
  73. package/batteries/tools/color/index.d.ts +37 -0
  74. package/batteries/tools/color.cjs +659 -0
  75. package/batteries/tools/color.cjs.map +1 -0
  76. package/batteries/tools/color.mjs +655 -0
  77. package/batteries/tools/color.mjs.map +1 -0
  78. package/batteries/tools/comparison/index.d.ts +29 -0
  79. package/batteries/tools/comparison.cjs +171 -0
  80. package/batteries/tools/comparison.cjs.map +1 -0
  81. package/batteries/tools/comparison.mjs +168 -0
  82. package/batteries/tools/comparison.mjs.map +1 -0
  83. package/batteries/tools/data_structure/index.d.ts +30 -0
  84. package/batteries/tools/data_structure.cjs +270 -0
  85. package/batteries/tools/data_structure.cjs.map +1 -0
  86. package/batteries/tools/data_structure.mjs +267 -0
  87. package/batteries/tools/data_structure.mjs.map +1 -0
  88. package/batteries/tools/datetime_extended/index.d.ts +51 -0
  89. package/batteries/tools/datetime_extended.cjs +309 -0
  90. package/batteries/tools/datetime_extended.cjs.map +1 -0
  91. package/batteries/tools/datetime_extended.mjs +302 -0
  92. package/batteries/tools/datetime_extended.mjs.map +1 -0
  93. package/batteries/tools/datetime_math/index.d.ts +36 -0
  94. package/batteries/tools/datetime_math.cjs +175 -0
  95. package/batteries/tools/datetime_math.cjs.map +1 -0
  96. package/batteries/tools/datetime_math.mjs +171 -0
  97. package/batteries/tools/datetime_math.mjs.map +1 -0
  98. package/batteries/tools/encoding/index.d.ts +36 -0
  99. package/batteries/tools/encoding.cjs +156 -0
  100. package/batteries/tools/encoding.cjs.map +1 -0
  101. package/batteries/tools/encoding.mjs +152 -0
  102. package/batteries/tools/encoding.mjs.map +1 -0
  103. package/batteries/tools/formatting/index.d.ts +28 -0
  104. package/batteries/tools/formatting.cjs +120 -0
  105. package/batteries/tools/formatting.cjs.map +1 -0
  106. package/batteries/tools/formatting.mjs +117 -0
  107. package/batteries/tools/formatting.mjs.map +1 -0
  108. package/batteries/tools/geo_basics/index.d.ts +33 -0
  109. package/batteries/tools/geo_basics.cjs +136 -0
  110. package/batteries/tools/geo_basics.cjs.map +1 -0
  111. package/batteries/tools/geo_basics.mjs +132 -0
  112. package/batteries/tools/geo_basics.mjs.map +1 -0
  113. package/batteries/tools/index.d.ts +32 -0
  114. package/batteries/tools/math/index.d.ts +37 -0
  115. package/batteries/tools/math.cjs +136 -0
  116. package/batteries/tools/math.cjs.map +1 -0
  117. package/batteries/tools/math.mjs +133 -0
  118. package/batteries/tools/math.mjs.map +1 -0
  119. package/batteries/tools/memory/index.d.ts +73 -0
  120. package/batteries/tools/memory.cjs +193 -0
  121. package/batteries/tools/memory.cjs.map +1 -0
  122. package/batteries/tools/memory.mjs +187 -0
  123. package/batteries/tools/memory.mjs.map +1 -0
  124. package/batteries/tools/parsing/index.d.ts +47 -0
  125. package/batteries/tools/parsing.cjs +191 -0
  126. package/batteries/tools/parsing.cjs.map +1 -0
  127. package/batteries/tools/parsing.mjs +185 -0
  128. package/batteries/tools/parsing.mjs.map +1 -0
  129. package/batteries/tools/retrievables/index.d.ts +81 -0
  130. package/batteries/tools/retrievables.cjs +215 -0
  131. package/batteries/tools/retrievables.cjs.map +1 -0
  132. package/batteries/tools/retrievables.mjs +209 -0
  133. package/batteries/tools/retrievables.mjs.map +1 -0
  134. package/batteries/tools/standing_instructions/index.d.ts +64 -0
  135. package/batteries/tools/standing_instructions.cjs +126 -0
  136. package/batteries/tools/standing_instructions.cjs.map +1 -0
  137. package/batteries/tools/standing_instructions.mjs +121 -0
  138. package/batteries/tools/standing_instructions.mjs.map +1 -0
  139. package/batteries/tools/statistics/index.d.ts +46 -0
  140. package/batteries/tools/statistics.cjs +253 -0
  141. package/batteries/tools/statistics.cjs.map +1 -0
  142. package/batteries/tools/statistics.mjs +248 -0
  143. package/batteries/tools/statistics.mjs.map +1 -0
  144. package/batteries/tools/string_processing/index.d.ts +29 -0
  145. package/batteries/tools/string_processing.cjs +154 -0
  146. package/batteries/tools/string_processing.cjs.map +1 -0
  147. package/batteries/tools/string_processing.mjs +151 -0
  148. package/batteries/tools/string_processing.mjs.map +1 -0
  149. package/batteries/tools/structured_data/index.d.ts +34 -0
  150. package/batteries/tools/structured_data.cjs +189 -0
  151. package/batteries/tools/structured_data.cjs.map +1 -0
  152. package/batteries/tools/structured_data.mjs +185 -0
  153. package/batteries/tools/structured_data.mjs.map +1 -0
  154. package/batteries/tools/text_analysis/index.d.ts +31 -0
  155. package/batteries/tools/text_analysis.cjs +120 -0
  156. package/batteries/tools/text_analysis.cjs.map +1 -0
  157. package/batteries/tools/text_analysis.mjs +117 -0
  158. package/batteries/tools/text_analysis.mjs.map +1 -0
  159. package/batteries/tools/text_comparison/index.d.ts +28 -0
  160. package/batteries/tools/text_comparison.cjs +96 -0
  161. package/batteries/tools/text_comparison.cjs.map +1 -0
  162. package/batteries/tools/text_comparison.mjs +93 -0
  163. package/batteries/tools/text_comparison.mjs.map +1 -0
  164. package/batteries/tools/time/index.d.ts +27 -0
  165. package/batteries/tools/time.cjs +63 -0
  166. package/batteries/tools/time.cjs.map +1 -0
  167. package/batteries/tools/time.mjs +60 -0
  168. package/batteries/tools/time.mjs.map +1 -0
  169. package/batteries/tools/unit_conversion/index.d.ts +19 -0
  170. package/batteries/tools/unit_conversion.cjs +452 -0
  171. package/batteries/tools/unit_conversion.cjs.map +1 -0
  172. package/batteries/tools/unit_conversion.mjs +450 -0
  173. package/batteries/tools/unit_conversion.mjs.map +1 -0
  174. package/batteries/tools.cjs +80 -0
  175. package/batteries/tools.mjs +21 -0
  176. package/batteries.cjs +142 -0
  177. package/batteries.mjs +30 -0
  178. package/chunk-KmRHZBOW.js +35 -0
  179. package/common-DeZaonK1.mjs +208 -0
  180. package/common-DeZaonK1.mjs.map +1 -0
  181. package/common-Od8edUXU.js +232 -0
  182. package/common-Od8edUXU.js.map +1 -0
  183. package/common.cjs +31 -0
  184. package/common.d.ts +108 -0
  185. package/common.mjs +8 -0
  186. package/dispatch_runner-9j6bXHL3.mjs +1609 -0
  187. package/dispatch_runner-9j6bXHL3.mjs.map +1 -0
  188. package/dispatch_runner-CsoH0nld.js +1627 -0
  189. package/dispatch_runner-CsoH0nld.js.map +1 -0
  190. package/dispatch_runner.cjs +3 -0
  191. package/dispatch_runner.d.ts +17 -0
  192. package/dispatch_runner.mjs +2 -0
  193. package/exceptions-D5YrO9Vm.js +280 -0
  194. package/exceptions-D5YrO9Vm.js.map +1 -0
  195. package/exceptions-NrzIHw_R.mjs +244 -0
  196. package/exceptions-NrzIHw_R.mjs.map +1 -0
  197. package/exceptions.cjs +33 -0
  198. package/exceptions.d.ts +52 -0
  199. package/exceptions.mjs +3 -0
  200. package/factories.cjs +4 -0
  201. package/factories.d.ts +39 -0
  202. package/factories.mjs +2 -0
  203. package/forge.cjs +9 -0
  204. package/forge.d.ts +49 -0
  205. package/forge.mjs +5 -0
  206. package/guards.cjs +96 -0
  207. package/guards.cjs.map +1 -0
  208. package/guards.d.ts +83 -0
  209. package/guards.mjs +72 -0
  210. package/guards.mjs.map +1 -0
  211. package/index.cjs +107 -0
  212. package/index.cjs.map +1 -0
  213. package/index.d.ts +18 -0
  214. package/index.mjs +31 -0
  215. package/index.mjs.map +1 -0
  216. package/lib/classes/artifact_tool.d.ts +129 -0
  217. package/lib/classes/base_exception.d.ts +83 -0
  218. package/lib/classes/identity.d.ts +71 -0
  219. package/lib/classes/media.d.ts +326 -0
  220. package/lib/classes/memory.d.ts +72 -0
  221. package/lib/classes/message.d.ts +137 -0
  222. package/lib/classes/registry.d.ts +79 -0
  223. package/lib/classes/retrievable.d.ts +100 -0
  224. package/lib/classes/spooled_artifact.d.ts +296 -0
  225. package/lib/classes/spooled_json_artifact.d.ts +158 -0
  226. package/lib/classes/spooled_markdown_artifact.d.ts +202 -0
  227. package/lib/classes/thought.d.ts +142 -0
  228. package/lib/classes/tokenizable.d.ts +124 -0
  229. package/lib/classes/tool.d.ts +228 -0
  230. package/lib/classes/tool_call.d.ts +190 -0
  231. package/lib/classes/tool_registry.d.ts +159 -0
  232. package/lib/classes/turn_gate.d.ts +109 -0
  233. package/lib/contracts/dispatch_context.d.ts +345 -0
  234. package/lib/contracts/media_reader.d.ts +60 -0
  235. package/lib/contracts/spool_reader.d.ts +80 -0
  236. package/lib/contracts/spooled_artifact_constructor.d.ts +38 -0
  237. package/lib/contracts/turn_runner_config.d.ts +101 -0
  238. package/lib/contracts/turn_runner_context.d.ts +267 -0
  239. package/lib/dispatch_runner.d.ts +98 -0
  240. package/lib/exceptions/runtime.d.ts +370 -0
  241. package/lib/helpers/media_readers.d.ts +39 -0
  242. package/lib/turn_runner.d.ts +144 -0
  243. package/lib/types/dispatch_context.d.ts +233 -0
  244. package/lib/types/dispatch_runner.d.ts +387 -0
  245. package/lib/types/turn_runner.d.ts +322 -0
  246. package/lib/utils/canonical_json.d.ts +18 -0
  247. package/lib/utils/exceptions.d.ts +78 -0
  248. package/lib/utils/guards.d.ts +32 -0
  249. package/lib/utils/validation.d.ts +77 -0
  250. package/package.json +334 -0
  251. package/runtime-BJVkrGQe.js +519 -0
  252. package/runtime-BJVkrGQe.js.map +1 -0
  253. package/runtime-CrEPIFgr.mjs +346 -0
  254. package/runtime-CrEPIFgr.mjs.map +1 -0
  255. package/skills/adk-assembly/SKILL.md +109 -0
  256. package/skills/adk-assembly/references/assembly-contract.md +66 -0
  257. package/skills/adk-assembly/references/executors-tools-pipelines-events.md +113 -0
  258. package/skills/adk-assembly/references/first-integration.md +93 -0
  259. package/skills/adk-assembly/references/storage-and-context.md +102 -0
  260. package/spooled_artifact-C5ZtGxuJ.mjs +544 -0
  261. package/spooled_artifact-C5ZtGxuJ.mjs.map +1 -0
  262. package/spooled_artifact-Cm9Te22K.js +568 -0
  263. package/spooled_artifact-Cm9Te22K.js.map +1 -0
  264. package/spooled_artifact.cjs +7 -0
  265. package/spooled_artifact.d.ts +40 -0
  266. package/spooled_artifact.mjs +3 -0
  267. package/spooled_markdown_artifact-BpUJol0W.mjs +771 -0
  268. package/spooled_markdown_artifact-BpUJol0W.mjs.map +1 -0
  269. package/spooled_markdown_artifact-RRB113sy.js +786 -0
  270. package/spooled_markdown_artifact-RRB113sy.js.map +1 -0
  271. package/thought-CDb457b4.mjs +470 -0
  272. package/thought-CDb457b4.mjs.map +1 -0
  273. package/thought-DuN2PgdO.js +494 -0
  274. package/thought-DuN2PgdO.js.map +1 -0
  275. package/tool-COSeH8I6.js +302 -0
  276. package/tool-COSeH8I6.js.map +1 -0
  277. package/tool-D2WB1EA1.mjs +296 -0
  278. package/tool-D2WB1EA1.mjs.map +1 -0
  279. package/tool_call-BKyyxGaZ.mjs +578 -0
  280. package/tool_call-BKyyxGaZ.mjs.map +1 -0
  281. package/tool_call-DFgzcVcU.js +608 -0
  282. package/tool_call-DFgzcVcU.js.map +1 -0
  283. package/tool_registry-Dkfprsck.js +641 -0
  284. package/tool_registry-Dkfprsck.js.map +1 -0
  285. package/tool_registry-DqLOyGyG.mjs +592 -0
  286. package/tool_registry-DqLOyGyG.mjs.map +1 -0
  287. package/turn_runner-CMm2BHdX.js +615 -0
  288. package/turn_runner-CMm2BHdX.js.map +1 -0
  289. package/turn_runner-y7eyEcJH.mjs +603 -0
  290. package/turn_runner-y7eyEcJH.mjs.map +1 -0
  291. package/turn_runner.cjs +3 -0
  292. package/turn_runner.d.ts +21 -0
  293. package/turn_runner.mjs +2 -0
  294. package/types.cjs +1 -0
  295. package/types.d.ts +56 -0
  296. package/types.mjs +0 -0
  297. package/vite-env.d.ts +23 -0
@@ -0,0 +1,1609 @@
1
+ import { a as validateOrThrow } from "./exceptions-NrzIHw_R.mjs";
2
+ import { a as Tokenizable, n as canonicalStringify, o as isError, r as Registry, s as isInstanceOf, t as ToolRegistry } from "./tool_registry-DqLOyGyG.mjs";
3
+ import { T as E_PIPELINE_SHORT_CIRCUITED, b as E_LLM_EXECUTION_EXECUTOR_ERROR, g as E_INVALID_TURN_CONTEXT, m as E_INVALID_LLM_EXECUTION_CONTEXT, p as E_INVALID_LLM_DISPATCH_INPUT, t as E_DISPATCH_PIPELINE_ERROR, x as E_LLM_EXECUTION_GATE_NOT_SUPPORTED, y as E_LLM_EXECUTION_ALREADY_SIGNALLED } from "./runtime-CrEPIFgr.mjs";
4
+ import { validator } from "@nhtio/validation";
5
+ import { v6 } from "uuid";
6
+ import { DateTime } from "luxon";
7
+ import { sha256 } from "js-sha256";
8
+ import { Hooks } from "@nhtio/hooks";
9
+ import { Middleware } from "@nhtio/middleware";
10
+ //#region src/lib/contracts/turn_runner_context.ts
11
+ /**
12
+ * Validator schema used to validate a {@link RawTurnContext} before constructing a {@link TurnContext}.
13
+ *
14
+ * @remarks
15
+ * Validates all four fields of {@link RawTurnContext}:
16
+ * - `turnAbortController` — required `AbortController` instance.
17
+ * - `stash` — optional string-keyed object; defaults to `{}`.
18
+ * - `systemPrompt` — required string or {@link @nhtio/adk!Tokenizable}, via {@link @nhtio/adk!Tokenizable.schema}.
19
+ * - `standingInstructions` — optional array of strings or {@link @nhtio/adk!Tokenizable} instances, each
20
+ * validated via {@link @nhtio/adk!Tokenizable.schema}; defaults to `[]`.
21
+ *
22
+ * Throws a `ValidationException` (via {@link validateOrThrow}) when validation fails.
23
+ */
24
+ var turnContextSchema = validator.object({
25
+ turnAbortController: validator.alternatives(validator.object().instance(AbortController), validator.function().instance(AbortController)).required(),
26
+ stash: validator.object().pattern(validator.string(), validator.any()).default({}),
27
+ systemPrompt: Tokenizable.schema.required(),
28
+ standingInstructions: validator.array().items(Tokenizable.schema).default([])
29
+ }).required();
30
+ /**
31
+ * The validated, strongly-typed context object threaded through every middleware step in a
32
+ * single agent turn.
33
+ *
34
+ * @remarks
35
+ * Constructed from a {@link RawTurnContext} by {@link @nhtio/adk!TurnRunner.run}. Middleware functions
36
+ * receive this object and use it to read and share state across pipeline steps.
37
+ */
38
+ var TurnContext = class TurnContext {
39
+ /**
40
+ * Returns `true` if `value` is a {@link TurnContext} instance.
41
+ *
42
+ * @remarks
43
+ * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety. The ADK does not export the
44
+ * `TurnContext` class itself as a constructable value — use this guard plus the
45
+ * {@link TurnContext} type for runtime detection and TypeScript narrowing.
46
+ *
47
+ * @param value - The value to test.
48
+ * @returns `true` when `value` is a {@link TurnContext} instance.
49
+ */
50
+ static isTurnContext(value) {
51
+ return isInstanceOf(value, "TurnContext", TurnContext);
52
+ }
53
+ #id;
54
+ #turnAbortController;
55
+ #stash;
56
+ #systemPrompt;
57
+ #standingInstructions;
58
+ #turnMemories;
59
+ #turnRetrievables;
60
+ #turnMessages;
61
+ #turnThoughts;
62
+ #turnToolCalls;
63
+ /**
64
+ * @param raw - The raw context input validated against {@link turnContextSchema}.
65
+ * @param injected - Runtime callbacks supplied by `TurnRunner`; bound as instance methods so
66
+ * middleware can call fetch and emit methods directly on the context.
67
+ * @throws {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} when `raw` does not satisfy the schema.
68
+ *
69
+ * @internal
70
+ */
71
+ constructor(raw, injected) {
72
+ try {
73
+ raw = validateOrThrow(turnContextSchema, raw, true);
74
+ } catch (err) {
75
+ throw new E_INVALID_TURN_CONTEXT({ cause: isError(err) ? err : void 0 });
76
+ }
77
+ this.#id = v6();
78
+ this.#turnAbortController = raw.turnAbortController;
79
+ this.#stash = new Registry(raw.stash);
80
+ this.#systemPrompt = Tokenizable.isTokenizable(raw.systemPrompt) ? raw.systemPrompt : new Tokenizable(raw.systemPrompt);
81
+ this.#standingInstructions = new Set((raw.standingInstructions || []).map((instr) => Tokenizable.isTokenizable(instr) ? instr : new Tokenizable(instr)));
82
+ this.#turnMemories = /* @__PURE__ */ new Set();
83
+ this.#turnRetrievables = /* @__PURE__ */ new Set();
84
+ this.#turnMessages = /* @__PURE__ */ new Set();
85
+ this.#turnThoughts = /* @__PURE__ */ new Set();
86
+ this.#turnToolCalls = /* @__PURE__ */ new Set();
87
+ Object.defineProperties(this, {
88
+ id: {
89
+ get: () => this.#id,
90
+ enumerable: true,
91
+ configurable: false
92
+ },
93
+ aborted: {
94
+ get: () => Boolean(this.#turnAbortController.signal.aborted),
95
+ enumerable: true,
96
+ configurable: false
97
+ },
98
+ abortSignal: {
99
+ get: () => this.#turnAbortController.signal,
100
+ enumerable: true,
101
+ configurable: false
102
+ },
103
+ abort: {
104
+ value: (reason) => this.#turnAbortController.abort(reason),
105
+ enumerable: true,
106
+ configurable: false,
107
+ writable: false
108
+ },
109
+ stash: {
110
+ get: () => this.#stash,
111
+ enumerable: true,
112
+ configurable: false
113
+ },
114
+ systemPrompt: {
115
+ get: () => this.#systemPrompt,
116
+ enumerable: true,
117
+ configurable: false
118
+ },
119
+ standingInstructions: {
120
+ get: () => this.#standingInstructions,
121
+ enumerable: true,
122
+ configurable: false
123
+ },
124
+ turnMemories: {
125
+ get: () => this.#turnMemories,
126
+ enumerable: true,
127
+ configurable: false
128
+ },
129
+ turnRetrievables: {
130
+ get: () => this.#turnRetrievables,
131
+ enumerable: true,
132
+ configurable: false
133
+ },
134
+ turnMessages: {
135
+ get: () => this.#turnMessages,
136
+ enumerable: true,
137
+ configurable: false
138
+ },
139
+ turnThoughts: {
140
+ get: () => this.#turnThoughts,
141
+ enumerable: true,
142
+ configurable: false
143
+ },
144
+ turnToolCalls: {
145
+ get: () => this.#turnToolCalls,
146
+ enumerable: true,
147
+ configurable: false
148
+ }
149
+ });
150
+ Object.defineProperties(this, {
151
+ fetchMemories: {
152
+ value: () => injected.fetchMemories(this),
153
+ enumerable: true,
154
+ configurable: false,
155
+ writable: false
156
+ },
157
+ fetchMessages: {
158
+ value: () => injected.fetchMessages(this),
159
+ enumerable: true,
160
+ configurable: false,
161
+ writable: false
162
+ },
163
+ fetchThoughts: {
164
+ value: () => injected.fetchThoughts(this),
165
+ enumerable: true,
166
+ configurable: false,
167
+ writable: false
168
+ },
169
+ fetchToolCalls: {
170
+ value: () => injected.fetchToolCalls(this),
171
+ enumerable: true,
172
+ configurable: false,
173
+ writable: false
174
+ },
175
+ fetchTools: {
176
+ value: () => injected.fetchTools(this),
177
+ enumerable: true,
178
+ configurable: false,
179
+ writable: false
180
+ },
181
+ refreshStandingInstructions: {
182
+ value: () => injected.refreshStandingInstructions(this),
183
+ enumerable: true,
184
+ configurable: false,
185
+ writable: false
186
+ },
187
+ storeStandingInstruction: {
188
+ value: (v) => injected.storeStandingInstruction(this, v),
189
+ enumerable: true,
190
+ configurable: false,
191
+ writable: false
192
+ },
193
+ mutateStandingInstruction: {
194
+ value: (v) => injected.mutateStandingInstruction(this, v),
195
+ enumerable: true,
196
+ configurable: false,
197
+ writable: false
198
+ },
199
+ deleteStandingInstruction: {
200
+ value: (v) => injected.deleteStandingInstruction(this, v),
201
+ enumerable: true,
202
+ configurable: false,
203
+ writable: false
204
+ },
205
+ storeMemory: {
206
+ value: (v) => injected.storeMemory(this, v),
207
+ enumerable: true,
208
+ configurable: false,
209
+ writable: false
210
+ },
211
+ mutateMemory: {
212
+ value: (v) => injected.mutateMemory(this, v),
213
+ enumerable: true,
214
+ configurable: false,
215
+ writable: false
216
+ },
217
+ deleteMemory: {
218
+ value: (id) => injected.deleteMemory(this, id),
219
+ enumerable: true,
220
+ configurable: false,
221
+ writable: false
222
+ },
223
+ fetchRetrievables: {
224
+ value: () => injected.fetchRetrievables(this),
225
+ enumerable: true,
226
+ configurable: false,
227
+ writable: false
228
+ },
229
+ storeRetrievable: {
230
+ value: (v) => injected.storeRetrievable(this, v),
231
+ enumerable: true,
232
+ configurable: false,
233
+ writable: false
234
+ },
235
+ mutateRetrievable: {
236
+ value: (v) => injected.mutateRetrievable(this, v),
237
+ enumerable: true,
238
+ configurable: false,
239
+ writable: false
240
+ },
241
+ deleteRetrievable: {
242
+ value: (id) => injected.deleteRetrievable(this, id),
243
+ enumerable: true,
244
+ configurable: false,
245
+ writable: false
246
+ },
247
+ storeMessage: {
248
+ value: (v) => injected.storeMessage(this, v),
249
+ enumerable: true,
250
+ configurable: false,
251
+ writable: false
252
+ },
253
+ mutateMessage: {
254
+ value: (v) => injected.mutateMessage(this, v),
255
+ enumerable: true,
256
+ configurable: false,
257
+ writable: false
258
+ },
259
+ deleteMessage: {
260
+ value: (id) => injected.deleteMessage(this, id),
261
+ enumerable: true,
262
+ configurable: false,
263
+ writable: false
264
+ },
265
+ storeThought: {
266
+ value: (v) => injected.storeThought(this, v),
267
+ enumerable: true,
268
+ configurable: false,
269
+ writable: false
270
+ },
271
+ mutateThought: {
272
+ value: (v) => injected.mutateThought(this, v),
273
+ enumerable: true,
274
+ configurable: false,
275
+ writable: false
276
+ },
277
+ deleteThought: {
278
+ value: (id) => injected.deleteThought(this, id),
279
+ enumerable: true,
280
+ configurable: false,
281
+ writable: false
282
+ },
283
+ storeToolCall: {
284
+ value: (v) => injected.storeToolCall(this, v),
285
+ enumerable: true,
286
+ configurable: false,
287
+ writable: false
288
+ },
289
+ mutateToolCall: {
290
+ value: (v) => injected.mutateToolCall(this, v),
291
+ enumerable: true,
292
+ configurable: false,
293
+ writable: false
294
+ },
295
+ deleteToolCall: {
296
+ value: (id) => injected.deleteToolCall(this, id),
297
+ enumerable: true,
298
+ configurable: false,
299
+ writable: false
300
+ },
301
+ emitMessage: {
302
+ value: injected.emitMessage,
303
+ enumerable: true,
304
+ configurable: false,
305
+ writable: false
306
+ },
307
+ emitThought: {
308
+ value: injected.emitThought,
309
+ enumerable: true,
310
+ configurable: false,
311
+ writable: false
312
+ },
313
+ emitToolCall: {
314
+ value: injected.emitToolCall,
315
+ enumerable: true,
316
+ configurable: false,
317
+ writable: false
318
+ },
319
+ emitToolExecutionStart: {
320
+ value: injected.emitToolExecutionStart,
321
+ enumerable: true,
322
+ configurable: false,
323
+ writable: false
324
+ },
325
+ emitToolExecutionEnd: {
326
+ value: injected.emitToolExecutionEnd,
327
+ enumerable: true,
328
+ configurable: false,
329
+ writable: false
330
+ },
331
+ waitFor: {
332
+ value: injected.openGate,
333
+ enumerable: true,
334
+ configurable: false,
335
+ writable: false
336
+ },
337
+ tools: {
338
+ get: () => injected.tools,
339
+ enumerable: true,
340
+ configurable: false
341
+ }
342
+ });
343
+ }
344
+ };
345
+ //#endregion
346
+ //#region src/lib/contracts/dispatch_context.ts
347
+ var rawDispatchContextSchema = validator.object({
348
+ turnAbortController: validator.alternatives(validator.object().instance(AbortController), validator.function().instance(AbortController)).optional(),
349
+ stash: validator.object().pattern(validator.string(), validator.any()).default({}),
350
+ systemPrompt: Tokenizable.schema.required(),
351
+ standingInstructions: validator.array().items(Tokenizable.schema).default([]),
352
+ memories: validator.array().default([]),
353
+ retrievables: validator.array().default([]),
354
+ messages: validator.array().default([]),
355
+ thoughts: validator.array().default([]),
356
+ toolCalls: validator.array().default([]),
357
+ tools: validator.array().default([]),
358
+ fetchMemories: validator.function().required(),
359
+ fetchRetrievables: validator.function().required(),
360
+ fetchMessages: validator.function().required(),
361
+ fetchThoughts: validator.function().required(),
362
+ fetchToolCalls: validator.function().required(),
363
+ fetchTools: validator.function().required(),
364
+ refreshStandingInstructions: validator.function().required(),
365
+ storeStandingInstruction: validator.function().required(),
366
+ mutateStandingInstruction: validator.function().required(),
367
+ deleteStandingInstruction: validator.function().required(),
368
+ storeMemory: validator.function().required(),
369
+ mutateMemory: validator.function().required(),
370
+ deleteMemory: validator.function().required(),
371
+ storeRetrievable: validator.function().required(),
372
+ mutateRetrievable: validator.function().required(),
373
+ deleteRetrievable: validator.function().required(),
374
+ storeMessage: validator.function().required(),
375
+ mutateMessage: validator.function().required(),
376
+ deleteMessage: validator.function().required(),
377
+ storeThought: validator.function().required(),
378
+ mutateThought: validator.function().required(),
379
+ deleteThought: validator.function().required(),
380
+ storeToolCall: validator.function().required(),
381
+ mutateToolCall: validator.function().required(),
382
+ deleteToolCall: validator.function().required(),
383
+ hooks: validator.object().optional(),
384
+ waitFor: validator.function().optional()
385
+ });
386
+ /**
387
+ * Context object for a single LLM execution call.
388
+ *
389
+ * @remarks
390
+ * Mirrors the surface of {@link @nhtio/adk!TurnContext} but is path-agnostic — it knows nothing about a
391
+ * parent context. Mutations apply to local Sets immediately, call persistence callbacks
392
+ * immediately, and fire the corresponding mutation hook (`storedMemory`, `mutatedMemory`,
393
+ * `deletedMemory`, etc.) in both standalone and derived dispatches.
394
+ *
395
+ * The {@link @nhtio/adk!DispatchRunner} is the only thing that creates a context with a parent
396
+ * relationship: when dispatched with a `source: TurnContext`, the runner subscribes to the
397
+ * mutation hooks, queues deltas internally, and flushes them to the parent's Sets at the end of
398
+ * each iteration. The context itself remains unaware of the parent.
399
+ *
400
+ * Middleware/executor signals termination via {@link DispatchContext.ack} (clean completion)
401
+ * or {@link DispatchContext.nack} (failure). Both set an internal flag the runner reads at
402
+ * end-of-iteration to decide whether to loop or exit. {@link DispatchContext.isSignalled},
403
+ * {@link DispatchContext.isAcked}, and {@link DispatchContext.nackError} are publicly
404
+ * readable getters so middleware can inspect signal state and bail early.
405
+ */
406
+ var DispatchContext = class DispatchContext {
407
+ #id;
408
+ #dispatchId;
409
+ #iteration;
410
+ #turnAbortController;
411
+ #stash;
412
+ #systemPrompt;
413
+ #standingInstructions;
414
+ #turnMemories;
415
+ #turnRetrievables;
416
+ #turnMessages;
417
+ #turnThoughts;
418
+ #turnToolCalls;
419
+ #tools;
420
+ #hooks;
421
+ #ackHandlers;
422
+ #fetchMemories;
423
+ #fetchRetrievables;
424
+ #fetchMessages;
425
+ #fetchThoughts;
426
+ #fetchToolCalls;
427
+ #fetchTools;
428
+ #refreshStandingInstructions;
429
+ #storeStandingInstruction;
430
+ #mutateStandingInstruction;
431
+ #deleteStandingInstruction;
432
+ #storeMemory;
433
+ #mutateMemory;
434
+ #deleteMemory;
435
+ #storeRetrievable;
436
+ #mutateRetrievable;
437
+ #deleteRetrievable;
438
+ #storeMessage;
439
+ #mutateMessage;
440
+ #deleteMessage;
441
+ #storeThought;
442
+ #mutateThought;
443
+ #deleteThought;
444
+ #storeToolCall;
445
+ #mutateToolCall;
446
+ #deleteToolCall;
447
+ #waitFor;
448
+ #toolCallChecksums;
449
+ #signalled;
450
+ #nackError;
451
+ /**
452
+ * @param raw - Raw input validated against the schema.
453
+ * @throws {@link @nhtio/adk!E_INVALID_LLM_EXECUTION_CONTEXT} when `raw` does not satisfy the schema.
454
+ */
455
+ constructor(raw) {
456
+ let resolved;
457
+ try {
458
+ resolved = validateOrThrow(rawDispatchContextSchema, raw, true);
459
+ } catch (err) {
460
+ throw new E_INVALID_LLM_EXECUTION_CONTEXT({ cause: isError(err) ? err : void 0 });
461
+ }
462
+ this.#id = v6();
463
+ this.#dispatchId = "";
464
+ this.#iteration = 0;
465
+ this.#turnAbortController = resolved.turnAbortController ?? new AbortController();
466
+ this.#stash = new Registry(resolved.stash);
467
+ this.#systemPrompt = Tokenizable.isTokenizable(resolved.systemPrompt) ? resolved.systemPrompt : new Tokenizable(resolved.systemPrompt);
468
+ this.#standingInstructions = new Set(resolved.standingInstructions.map((i) => Tokenizable.isTokenizable(i) ? i : new Tokenizable(i)));
469
+ this.#turnMemories = new Set(resolved.memories);
470
+ this.#turnRetrievables = new Set(resolved.retrievables);
471
+ this.#turnMessages = new Set(resolved.messages);
472
+ this.#turnThoughts = new Set(resolved.thoughts);
473
+ this.#turnToolCalls = new Set(resolved.toolCalls);
474
+ this.#tools = new ToolRegistry(resolved.tools);
475
+ this.#toolCallChecksums = /* @__PURE__ */ new Map();
476
+ for (const tc of resolved.toolCalls) {
477
+ const prev = this.#toolCallChecksums.get(tc.checksum) ?? 0;
478
+ this.#toolCallChecksums.set(tc.checksum, prev + 1);
479
+ }
480
+ this.#fetchMemories = resolved.fetchMemories;
481
+ this.#fetchRetrievables = resolved.fetchRetrievables;
482
+ this.#fetchMessages = resolved.fetchMessages;
483
+ this.#fetchThoughts = resolved.fetchThoughts;
484
+ this.#fetchToolCalls = resolved.fetchToolCalls;
485
+ this.#fetchTools = resolved.fetchTools;
486
+ this.#refreshStandingInstructions = resolved.refreshStandingInstructions;
487
+ this.#storeStandingInstruction = resolved.storeStandingInstruction;
488
+ this.#mutateStandingInstruction = resolved.mutateStandingInstruction;
489
+ this.#deleteStandingInstruction = resolved.deleteStandingInstruction;
490
+ this.#storeMemory = resolved.storeMemory;
491
+ this.#mutateMemory = resolved.mutateMemory;
492
+ this.#deleteMemory = resolved.deleteMemory;
493
+ this.#storeRetrievable = resolved.storeRetrievable;
494
+ this.#mutateRetrievable = resolved.mutateRetrievable;
495
+ this.#deleteRetrievable = resolved.deleteRetrievable;
496
+ this.#storeMessage = resolved.storeMessage;
497
+ this.#mutateMessage = resolved.mutateMessage;
498
+ this.#deleteMessage = resolved.deleteMessage;
499
+ this.#storeThought = resolved.storeThought;
500
+ this.#mutateThought = resolved.mutateThought;
501
+ this.#deleteThought = resolved.deleteThought;
502
+ this.#storeToolCall = resolved.storeToolCall;
503
+ this.#mutateToolCall = resolved.mutateToolCall;
504
+ this.#deleteToolCall = resolved.deleteToolCall;
505
+ this.#waitFor = resolved.waitFor;
506
+ this.#signalled = void 0;
507
+ this.#nackError = void 0;
508
+ this.#hooks = new Hooks();
509
+ this.#ackHandlers = /* @__PURE__ */ new Set();
510
+ if (resolved.hooks) {
511
+ const regs = resolved.hooks;
512
+ for (const key of Object.keys(regs)) {
513
+ const entry = regs[key];
514
+ if (!entry) continue;
515
+ const handlers = Array.isArray(entry) ? entry : [entry];
516
+ for (const h of handlers) this.#hooks.add(key, h);
517
+ }
518
+ }
519
+ Object.defineProperties(this, {
520
+ id: {
521
+ get: () => this.#id,
522
+ enumerable: true,
523
+ configurable: false
524
+ },
525
+ dispatchId: {
526
+ get: () => this.#dispatchId,
527
+ enumerable: true,
528
+ configurable: false
529
+ },
530
+ iteration: {
531
+ get: () => this.#iteration,
532
+ enumerable: true,
533
+ configurable: false
534
+ },
535
+ aborted: {
536
+ get: () => Boolean(this.#turnAbortController.signal.aborted),
537
+ enumerable: true,
538
+ configurable: false
539
+ },
540
+ abortSignal: {
541
+ get: () => this.#turnAbortController.signal,
542
+ enumerable: true,
543
+ configurable: false
544
+ },
545
+ abort: {
546
+ value: (reason) => this.#turnAbortController.abort(reason),
547
+ enumerable: true,
548
+ configurable: false,
549
+ writable: false
550
+ },
551
+ isSignalled: {
552
+ get: () => this.#signalled !== void 0,
553
+ enumerable: true,
554
+ configurable: false
555
+ },
556
+ isAcked: {
557
+ get: () => this.#signalled === "ack",
558
+ enumerable: true,
559
+ configurable: false
560
+ },
561
+ nackError: {
562
+ get: () => this.#nackError,
563
+ enumerable: true,
564
+ configurable: false
565
+ },
566
+ stash: {
567
+ get: () => this.#stash,
568
+ enumerable: true,
569
+ configurable: false
570
+ },
571
+ systemPrompt: {
572
+ get: () => this.#systemPrompt,
573
+ enumerable: true,
574
+ configurable: false
575
+ },
576
+ standingInstructions: {
577
+ get: () => this.#standingInstructions,
578
+ enumerable: true,
579
+ configurable: false
580
+ },
581
+ turnMemories: {
582
+ get: () => this.#turnMemories,
583
+ enumerable: true,
584
+ configurable: false
585
+ },
586
+ turnRetrievables: {
587
+ get: () => this.#turnRetrievables,
588
+ enumerable: true,
589
+ configurable: false
590
+ },
591
+ turnMessages: {
592
+ get: () => this.#turnMessages,
593
+ enumerable: true,
594
+ configurable: false
595
+ },
596
+ turnThoughts: {
597
+ get: () => this.#turnThoughts,
598
+ enumerable: true,
599
+ configurable: false
600
+ },
601
+ turnToolCalls: {
602
+ get: () => this.#turnToolCalls,
603
+ enumerable: true,
604
+ configurable: false
605
+ },
606
+ tools: {
607
+ get: () => this.#tools,
608
+ enumerable: true,
609
+ configurable: false
610
+ },
611
+ fetchMemories: {
612
+ value: () => this.#fetchMemories(this),
613
+ enumerable: true,
614
+ configurable: false,
615
+ writable: false
616
+ },
617
+ fetchRetrievables: {
618
+ value: () => this.#fetchRetrievables(this),
619
+ enumerable: true,
620
+ configurable: false,
621
+ writable: false
622
+ },
623
+ fetchMessages: {
624
+ value: () => this.#fetchMessages(this),
625
+ enumerable: true,
626
+ configurable: false,
627
+ writable: false
628
+ },
629
+ fetchThoughts: {
630
+ value: () => this.#fetchThoughts(this),
631
+ enumerable: true,
632
+ configurable: false,
633
+ writable: false
634
+ },
635
+ fetchToolCalls: {
636
+ value: () => this.#fetchToolCalls(this),
637
+ enumerable: true,
638
+ configurable: false,
639
+ writable: false
640
+ },
641
+ fetchTools: {
642
+ value: () => this.#fetchTools(this),
643
+ enumerable: true,
644
+ configurable: false,
645
+ writable: false
646
+ },
647
+ refreshStandingInstructions: {
648
+ value: () => this.#refreshStandingInstructions(this),
649
+ enumerable: true,
650
+ configurable: false,
651
+ writable: false
652
+ },
653
+ storeStandingInstruction: {
654
+ value: (v) => this.#doStoreStandingInstruction(v),
655
+ enumerable: true,
656
+ configurable: false,
657
+ writable: false
658
+ },
659
+ mutateStandingInstruction: {
660
+ value: (v) => this.#doMutateStandingInstruction(v),
661
+ enumerable: true,
662
+ configurable: false,
663
+ writable: false
664
+ },
665
+ deleteStandingInstruction: {
666
+ value: (v) => this.#doDeleteStandingInstruction(v),
667
+ enumerable: true,
668
+ configurable: false,
669
+ writable: false
670
+ },
671
+ storeMemory: {
672
+ value: (v) => this.#doStoreMemory(v),
673
+ enumerable: true,
674
+ configurable: false,
675
+ writable: false
676
+ },
677
+ mutateMemory: {
678
+ value: (v) => this.#doMutateMemory(v),
679
+ enumerable: true,
680
+ configurable: false,
681
+ writable: false
682
+ },
683
+ deleteMemory: {
684
+ value: (id) => this.#doDeleteMemory(id),
685
+ enumerable: true,
686
+ configurable: false,
687
+ writable: false
688
+ },
689
+ storeRetrievable: {
690
+ value: (v) => this.#doStoreRetrievable(v),
691
+ enumerable: true,
692
+ configurable: false,
693
+ writable: false
694
+ },
695
+ mutateRetrievable: {
696
+ value: (v) => this.#doMutateRetrievable(v),
697
+ enumerable: true,
698
+ configurable: false,
699
+ writable: false
700
+ },
701
+ deleteRetrievable: {
702
+ value: (id) => this.#doDeleteRetrievable(id),
703
+ enumerable: true,
704
+ configurable: false,
705
+ writable: false
706
+ },
707
+ storeMessage: {
708
+ value: (v) => this.#doStoreMessage(v),
709
+ enumerable: true,
710
+ configurable: false,
711
+ writable: false
712
+ },
713
+ mutateMessage: {
714
+ value: (v) => this.#doMutateMessage(v),
715
+ enumerable: true,
716
+ configurable: false,
717
+ writable: false
718
+ },
719
+ deleteMessage: {
720
+ value: (id) => this.#doDeleteMessage(id),
721
+ enumerable: true,
722
+ configurable: false,
723
+ writable: false
724
+ },
725
+ storeThought: {
726
+ value: (v) => this.#doStoreThought(v),
727
+ enumerable: true,
728
+ configurable: false,
729
+ writable: false
730
+ },
731
+ mutateThought: {
732
+ value: (v) => this.#doMutateThought(v),
733
+ enumerable: true,
734
+ configurable: false,
735
+ writable: false
736
+ },
737
+ deleteThought: {
738
+ value: (id) => this.#doDeleteThought(id),
739
+ enumerable: true,
740
+ configurable: false,
741
+ writable: false
742
+ },
743
+ storeToolCall: {
744
+ value: (v) => this.#doStoreToolCall(v),
745
+ enumerable: true,
746
+ configurable: false,
747
+ writable: false
748
+ },
749
+ mutateToolCall: {
750
+ value: (v) => this.#doMutateToolCall(v),
751
+ enumerable: true,
752
+ configurable: false,
753
+ writable: false
754
+ },
755
+ deleteToolCall: {
756
+ value: (id) => this.#doDeleteToolCall(id),
757
+ enumerable: true,
758
+ configurable: false,
759
+ writable: false
760
+ },
761
+ emitMessage: {
762
+ value: (content) => {
763
+ this.#hooks.runner("message").run(content);
764
+ },
765
+ enumerable: true,
766
+ configurable: false,
767
+ writable: false
768
+ },
769
+ emitThought: {
770
+ value: (content) => {
771
+ this.#hooks.runner("thought").run(content);
772
+ },
773
+ enumerable: true,
774
+ configurable: false,
775
+ writable: false
776
+ },
777
+ emitToolCall: {
778
+ value: (content) => {
779
+ this.#hooks.runner("toolCall").run(content);
780
+ },
781
+ enumerable: true,
782
+ configurable: false,
783
+ writable: false
784
+ },
785
+ emitToolExecutionStart: {
786
+ value: (event) => {
787
+ this.#hooks.runner("toolExecutionStart").run(event);
788
+ },
789
+ enumerable: true,
790
+ configurable: false,
791
+ writable: false
792
+ },
793
+ emitToolExecutionEnd: {
794
+ value: (event) => {
795
+ this.#hooks.runner("toolExecutionEnd").run(event);
796
+ },
797
+ enumerable: true,
798
+ configurable: false,
799
+ writable: false
800
+ },
801
+ waitFor: {
802
+ value: (gateRaw) => {
803
+ if (!this.#waitFor) return Promise.reject(new E_LLM_EXECUTION_GATE_NOT_SUPPORTED());
804
+ return this.#waitFor(gateRaw);
805
+ },
806
+ enumerable: true,
807
+ configurable: false,
808
+ writable: false
809
+ }
810
+ });
811
+ }
812
+ async #doStoreStandingInstruction(v) {
813
+ const t = Tokenizable.isTokenizable(v) ? v : new Tokenizable(v);
814
+ this.#standingInstructions.add(t);
815
+ await this.#storeStandingInstruction(this, v);
816
+ this.#hooks.runner("storedStandingInstruction").run(t);
817
+ }
818
+ async #doMutateStandingInstruction(v) {
819
+ const t = Tokenizable.isTokenizable(v) ? v : new Tokenizable(v);
820
+ this.#standingInstructions.add(t);
821
+ await this.#mutateStandingInstruction(this, v);
822
+ this.#hooks.runner("mutatedStandingInstruction").run(t);
823
+ }
824
+ async #doDeleteStandingInstruction(v) {
825
+ const t = Tokenizable.isTokenizable(v) ? v : new Tokenizable(v);
826
+ this.#standingInstructions.delete(t);
827
+ await this.#deleteStandingInstruction(this, v);
828
+ this.#hooks.runner("deletedStandingInstruction").run(t);
829
+ }
830
+ async #doStoreMemory(v) {
831
+ this.#turnMemories.add(v);
832
+ await this.#storeMemory(this, v);
833
+ this.#hooks.runner("storedMemory").run(v);
834
+ }
835
+ async #doMutateMemory(v) {
836
+ this.#turnMemories.add(v);
837
+ await this.#mutateMemory(this, v);
838
+ this.#hooks.runner("mutatedMemory").run(v);
839
+ }
840
+ async #doDeleteMemory(id) {
841
+ for (const m of this.#turnMemories) if (m.id === id) {
842
+ this.#turnMemories.delete(m);
843
+ break;
844
+ }
845
+ await this.#deleteMemory(this, id);
846
+ this.#hooks.runner("deletedMemory").run(id);
847
+ }
848
+ async #doStoreRetrievable(v) {
849
+ this.#turnRetrievables.add(v);
850
+ await this.#storeRetrievable(this, v);
851
+ this.#hooks.runner("storedRetrievable").run(v);
852
+ }
853
+ async #doMutateRetrievable(v) {
854
+ this.#turnRetrievables.add(v);
855
+ await this.#mutateRetrievable(this, v);
856
+ this.#hooks.runner("mutatedRetrievable").run(v);
857
+ }
858
+ async #doDeleteRetrievable(id) {
859
+ for (const r of this.#turnRetrievables) if (r.id === id) {
860
+ this.#turnRetrievables.delete(r);
861
+ break;
862
+ }
863
+ await this.#deleteRetrievable(this, id);
864
+ this.#hooks.runner("deletedRetrievable").run(id);
865
+ }
866
+ async #doStoreMessage(v) {
867
+ this.#turnMessages.add(v);
868
+ await this.#storeMessage(this, v);
869
+ this.#hooks.runner("storedMessage").run(v);
870
+ }
871
+ async #doMutateMessage(v) {
872
+ this.#turnMessages.add(v);
873
+ await this.#mutateMessage(this, v);
874
+ this.#hooks.runner("mutatedMessage").run(v);
875
+ }
876
+ async #doDeleteMessage(id) {
877
+ for (const m of this.#turnMessages) if (m.id === id) {
878
+ this.#turnMessages.delete(m);
879
+ break;
880
+ }
881
+ await this.#deleteMessage(this, id);
882
+ this.#hooks.runner("deletedMessage").run(id);
883
+ }
884
+ async #doStoreThought(v) {
885
+ this.#turnThoughts.add(v);
886
+ await this.#storeThought(this, v);
887
+ this.#hooks.runner("storedThought").run(v);
888
+ }
889
+ async #doMutateThought(v) {
890
+ this.#turnThoughts.add(v);
891
+ await this.#mutateThought(this, v);
892
+ this.#hooks.runner("mutatedThought").run(v);
893
+ }
894
+ async #doDeleteThought(id) {
895
+ for (const t of this.#turnThoughts) if (t.id === id) {
896
+ this.#turnThoughts.delete(t);
897
+ break;
898
+ }
899
+ await this.#deleteThought(this, id);
900
+ this.#hooks.runner("deletedThought").run(id);
901
+ }
902
+ async #doStoreToolCall(v) {
903
+ this.#turnToolCalls.add(v);
904
+ const prev = this.#toolCallChecksums.get(v.checksum) ?? 0;
905
+ this.#toolCallChecksums.set(v.checksum, prev + 1);
906
+ await this.#storeToolCall(this, v);
907
+ this.#hooks.runner("storedToolCall").run(v);
908
+ }
909
+ async #doMutateToolCall(v) {
910
+ this.#turnToolCalls.add(v);
911
+ await this.#mutateToolCall(this, v);
912
+ this.#hooks.runner("mutatedToolCall").run(v);
913
+ }
914
+ async #doDeleteToolCall(id) {
915
+ for (const tc of this.#turnToolCalls) if (tc.id === id) {
916
+ this.#turnToolCalls.delete(tc);
917
+ const count = this.#toolCallChecksums.get(tc.checksum) ?? 1;
918
+ if (count <= 1) this.#toolCallChecksums.delete(tc.checksum);
919
+ else this.#toolCallChecksums.set(tc.checksum, count - 1);
920
+ break;
921
+ }
922
+ await this.#deleteToolCall(this, id);
923
+ this.#hooks.runner("deletedToolCall").run(id);
924
+ }
925
+ /** @internal Set by {@link @nhtio/adk!DispatchRunner} after construction. */
926
+ _setDispatchId(id) {
927
+ this.#dispatchId = id;
928
+ }
929
+ /** @internal Updated by {@link @nhtio/adk!DispatchRunner} on each iteration. */
930
+ _setIteration(n) {
931
+ this.#iteration = n;
932
+ }
933
+ /** @internal Accessor used by {@link @nhtio/adk!DispatchRunner} to register forwarding handlers. */
934
+ _getHooks() {
935
+ return this.#hooks;
936
+ }
937
+ /**
938
+ * Returns how many times a tool call with the given checksum has been stored in this execution.
939
+ *
940
+ * @remarks
941
+ * Checksums are computed over `tool + args` (see {@link @nhtio/adk!ToolCall.checksum}). This count lets
942
+ * the executor detect repeat invocations of the same call without scanning the full Set.
943
+ * Returns `0` when the checksum has not been seen.
944
+ *
945
+ * @param checksum - The `ToolCall.checksum` value to look up.
946
+ */
947
+ toolCallCount(checksum) {
948
+ return this.#toolCallChecksums.get(checksum) ?? 0;
949
+ }
950
+ /**
951
+ * Signals successful completion of this execution.
952
+ *
953
+ * @remarks
954
+ * Sets the context's internal signal flag. The {@link @nhtio/adk!DispatchRunner} reads the flag at the
955
+ * end of each iteration to decide whether to loop or exit. Calling `ack()` does NOT abort the
956
+ * current iteration — the current pipeline and flush complete first.
957
+ *
958
+ * @throws {@link @nhtio/adk!E_LLM_EXECUTION_ALREADY_SIGNALLED} when the context has already been signalled
959
+ * (whether via `ack()` or `nack()`).
960
+ */
961
+ ack() {
962
+ if (this.#signalled !== void 0) throw new E_LLM_EXECUTION_ALREADY_SIGNALLED();
963
+ this.#signalled = "ack";
964
+ for (const handler of this.#ackHandlers) try {
965
+ handler();
966
+ } catch {}
967
+ }
968
+ /**
969
+ * Registers a handler to run when this context completes successfully via {@link ack}.
970
+ *
971
+ * @remarks
972
+ * The handler does NOT fire on {@link nack} — failed executor runs should leave any
973
+ * ack-tied subscriptions alone so the consumer can inspect what was registered when
974
+ * debugging the failure. Returns an unsubscribe function; subscriptions are short-lived
975
+ * and die with the context regardless.
976
+ *
977
+ * The canonical consumer is `ToolRegistry.bindContext(ctx)`, which uses this hook to drop
978
+ * ephemeral tools (notably forged artifact-query tools from `SpooledArtifact.forgeTools(ctx)`)
979
+ * at ctx-completion. Consumers may also register custom handlers here for any per-executor
980
+ * cleanup.
981
+ *
982
+ * @param handler - Callback invoked when `ack()` is called.
983
+ * @returns An unsubscribe function that removes the handler.
984
+ *
985
+ * @see {@link @nhtio/adk!ToolRegistry.bindContext}
986
+ * @see {@link @nhtio/adk!SpooledArtifact.forgeTools}
987
+ */
988
+ onAck(handler) {
989
+ this.#ackHandlers.add(handler);
990
+ return () => {
991
+ this.#ackHandlers.delete(handler);
992
+ };
993
+ }
994
+ /**
995
+ * Signals failed completion of this execution, optionally with an error.
996
+ *
997
+ * @remarks
998
+ * Sets the context's internal signal flag and stores the error. The {@link @nhtio/adk!DispatchRunner}
999
+ * reads the flag at the end of each iteration and surfaces the error via the `dispatchEnd`
1000
+ * observability payload and as the rejection reason of `dispatch()`. Calling `nack()` does NOT
1001
+ * abort the current iteration — the current pipeline and flush complete first.
1002
+ *
1003
+ * @param error - Optional error describing the failure. If omitted, a generic Error is used.
1004
+ * @throws {@link @nhtio/adk!E_LLM_EXECUTION_ALREADY_SIGNALLED} when the context has already been signalled.
1005
+ */
1006
+ nack(error) {
1007
+ if (this.#signalled !== void 0) throw new E_LLM_EXECUTION_ALREADY_SIGNALLED();
1008
+ this.#signalled = "nack";
1009
+ this.#nackError = error ?? /* @__PURE__ */ new Error("LLM execution was nacked without an explicit error.");
1010
+ }
1011
+ /**
1012
+ * Returns `true` if `value` is a {@link DispatchContext} instance.
1013
+ *
1014
+ * @remarks
1015
+ * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety. The ADK does not export the
1016
+ * `DispatchContext` class itself as a constructable value — use this guard plus the
1017
+ * {@link DispatchContext} type for runtime detection and TypeScript narrowing.
1018
+ *
1019
+ * @param value - The value to test.
1020
+ * @returns `true` when `value` is a {@link DispatchContext} instance.
1021
+ */
1022
+ static isDispatchContext(value) {
1023
+ return isInstanceOf(value, "DispatchContext", DispatchContext);
1024
+ }
1025
+ };
1026
+ //#endregion
1027
+ //#region src/lib/dispatch_runner.ts
1028
+ var dispatchInputSchema = validator.object({
1029
+ source: validator.any().custom((value, helpers) => {
1030
+ if (value === void 0) return value;
1031
+ if (isInstanceOf(value, "TurnContext", TurnContext)) return value;
1032
+ return helpers.error("any.invalid");
1033
+ }).optional(),
1034
+ raw: validator.object().unknown(true).optional(),
1035
+ executor: validator.function().required(),
1036
+ turnInputPipeline: validator.array().items(validator.function()).default([]),
1037
+ turnOutputPipeline: validator.array().items(validator.function()).default([]),
1038
+ hooks: validator.object().optional(),
1039
+ observers: validator.object().optional()
1040
+ });
1041
+ /**
1042
+ * Orchestrates a single LLM execution dispatch — input pipeline → executor → output pipeline —
1043
+ * looped until middleware/executor signals completion via {@link @nhtio/adk!DispatchContext.ack} /
1044
+ * {@link @nhtio/adk!DispatchContext.nack} or the abort signal fires.
1045
+ *
1046
+ * @remarks
1047
+ * `DispatchRunner` has a private constructor and is invoked via the static `dispatch()`
1048
+ * method. Each dispatch creates a fresh single-use runner that is garbage-collected after the
1049
+ * call completes — matching the `@nhtio/hooks` GC rationale already baked into the context.
1050
+ *
1051
+ * The runner owns the relationship between an {@link @nhtio/adk!DispatchContext} and its parent
1052
+ * {@link @nhtio/adk!TurnContext} (when given a source). It subscribes to the context's mutation hooks,
1053
+ * queues `ContextDelta` entries, and flushes them to the parent's Sets at the end of every
1054
+ * iteration. Emits propagate from the context's hooks → the runner's hooks → (optionally) the
1055
+ * parent `TurnContext`'s emit methods → the `TurnRunner`'s buses.
1056
+ *
1057
+ * Two hook buses, mirroring `TurnRunner`'s pattern:
1058
+ *
1059
+ * - **Functional** (`hooks`): `message`, `thought`, `toolCall` — pipeline-affecting events
1060
+ * - **Observability** (`observers`): `iterationStart`, `iterationEnd`, `dispatchStart`,
1061
+ * `dispatchEnd`, `error`, `toolExecutionStart`, `toolExecutionEnd` — instrumentation only
1062
+ *
1063
+ * The runner has no `maxIterations`, no `maxToolCallChecksumRepeats`. Implementers use the
1064
+ * primitives — `ctx.iteration`, `ctx.toolCallCount(checksum)`, `ctx.ack()`, `ctx.nack()`,
1065
+ * `ctx.abortSignal` — to build any termination bounds they need in their own middleware.
1066
+ */
1067
+ /**
1068
+ * Module-private token gating direct construction of {@link DispatchRunner}. Callers must use
1069
+ * {@link DispatchRunner.dispatch}; the symbol is not exported, so external code cannot satisfy
1070
+ * the guard at runtime.
1071
+ */
1072
+ var CONSTRUCT_TOKEN = Symbol("DispatchRunner.construct");
1073
+ var DispatchRunner = class DispatchRunner {
1074
+ #functionalHooks;
1075
+ #observabilityHooks;
1076
+ #inputPipeline;
1077
+ #outputPipeline;
1078
+ #sourceCtx;
1079
+ #deltaQueue;
1080
+ constructor(token, sourceCtx, turnInputPipeline, turnOutputPipeline, hooks, observers) {
1081
+ if (token !== CONSTRUCT_TOKEN) throw new E_INVALID_LLM_DISPATCH_INPUT();
1082
+ this.#sourceCtx = sourceCtx;
1083
+ this.#deltaQueue = [];
1084
+ this.#functionalHooks = new Hooks();
1085
+ this.#observabilityHooks = new Hooks();
1086
+ const inputPipeline = new Middleware();
1087
+ const outputPipeline = new Middleware();
1088
+ const wrap = (fn) => (ctx, next) => {
1089
+ if (ctx.aborted) return next();
1090
+ return fn(ctx, next);
1091
+ };
1092
+ for (const fn of turnInputPipeline) inputPipeline.add(wrap(fn));
1093
+ for (const fn of turnOutputPipeline) outputPipeline.add(wrap(fn));
1094
+ this.#inputPipeline = inputPipeline;
1095
+ this.#outputPipeline = outputPipeline;
1096
+ if (hooks) for (const key of Object.keys(hooks)) {
1097
+ const entry = hooks[key];
1098
+ if (!entry) continue;
1099
+ const handlers = Array.isArray(entry) ? entry : [entry];
1100
+ for (const h of handlers) this.#functionalHooks.add(key, h);
1101
+ }
1102
+ if (observers) for (const key of Object.keys(observers)) {
1103
+ const entry = observers[key];
1104
+ if (!entry) continue;
1105
+ const handlers = Array.isArray(entry) ? entry : [entry];
1106
+ for (const h of handlers) this.#observabilityHooks.add(key, h);
1107
+ }
1108
+ }
1109
+ /**
1110
+ * Returns `true` if `value` is a {@link DispatchRunner} instance.
1111
+ *
1112
+ * @remarks
1113
+ * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.
1114
+ *
1115
+ * @param value - The value to test.
1116
+ * @returns `true` when `value` is a {@link DispatchRunner} instance.
1117
+ */
1118
+ static isDispatchRunner(value) {
1119
+ return isInstanceOf(value, "DispatchRunner", DispatchRunner);
1120
+ }
1121
+ /**
1122
+ * Dispatches a single LLM execution.
1123
+ *
1124
+ * @remarks
1125
+ * Constructs an {@link @nhtio/adk!DispatchContext} (derived from `source` or from `raw`), runs the
1126
+ * iteration loop, and resolves when middleware/executor signals completion via `ctx.ack()` or
1127
+ * the abort signal fires. Rejects with the nack error when middleware/executor calls
1128
+ * `ctx.nack(err)`. Pipeline and executor errors are wrapped, surfaced on the observability
1129
+ * `error` hook, and re-thrown.
1130
+ *
1131
+ * @param input - The dispatch input. Provide either `source` (derived path) or `raw` (standalone).
1132
+ * @throws {@link @nhtio/adk!E_INVALID_LLM_DISPATCH_INPUT} when the input does not satisfy validation, or
1133
+ * when neither `source` nor `raw` is provided, or when both are provided.
1134
+ */
1135
+ static async dispatch(input) {
1136
+ let resolved;
1137
+ try {
1138
+ resolved = validateOrThrow(dispatchInputSchema, input, true);
1139
+ } catch (err) {
1140
+ throw new E_INVALID_LLM_DISPATCH_INPUT({ cause: isError(err) ? err : void 0 });
1141
+ }
1142
+ if (!resolved.source && !resolved.raw) throw new E_INVALID_LLM_DISPATCH_INPUT();
1143
+ if (resolved.source && resolved.raw) throw new E_INVALID_LLM_DISPATCH_INPUT();
1144
+ const runner = new DispatchRunner(CONSTRUCT_TOKEN, resolved.source, resolved.turnInputPipeline, resolved.turnOutputPipeline, resolved.hooks, resolved.observers);
1145
+ const llmCtx = runner.#buildContext(resolved.source, resolved.raw);
1146
+ runner.#wireContextHooks(llmCtx);
1147
+ await runner.#runDispatch(llmCtx, resolved.executor);
1148
+ }
1149
+ #buildContext(source, raw) {
1150
+ if (source) {
1151
+ const ac = new AbortController();
1152
+ source.abortSignal.addEventListener("abort", () => ac.abort(), { once: true });
1153
+ return new DispatchContext({
1154
+ turnAbortController: ac,
1155
+ stash: source.stash.all(),
1156
+ systemPrompt: source.systemPrompt,
1157
+ standingInstructions: [...source.standingInstructions],
1158
+ memories: [...source.turnMemories],
1159
+ retrievables: [...source.turnRetrievables],
1160
+ messages: [...source.turnMessages],
1161
+ thoughts: [...source.turnThoughts],
1162
+ toolCalls: [...source.turnToolCalls],
1163
+ tools: source.tools.all(),
1164
+ fetchMemories: () => source.fetchMemories(),
1165
+ fetchRetrievables: () => source.fetchRetrievables(),
1166
+ fetchMessages: () => source.fetchMessages(),
1167
+ fetchThoughts: () => source.fetchThoughts(),
1168
+ fetchToolCalls: () => source.fetchToolCalls(),
1169
+ fetchTools: () => source.fetchTools(),
1170
+ refreshStandingInstructions: () => source.refreshStandingInstructions(),
1171
+ storeStandingInstruction: (_c, v) => source.storeStandingInstruction(v),
1172
+ mutateStandingInstruction: (_c, v) => source.mutateStandingInstruction(v),
1173
+ deleteStandingInstruction: (_c, v) => source.deleteStandingInstruction(v),
1174
+ storeMemory: (_c, v) => source.storeMemory(v),
1175
+ mutateMemory: (_c, v) => source.mutateMemory(v),
1176
+ deleteMemory: (_c, id) => source.deleteMemory(id),
1177
+ storeRetrievable: (_c, v) => source.storeRetrievable(v),
1178
+ mutateRetrievable: (_c, v) => source.mutateRetrievable(v),
1179
+ deleteRetrievable: (_c, id) => source.deleteRetrievable(id),
1180
+ storeMessage: (_c, v) => source.storeMessage(v),
1181
+ mutateMessage: (_c, v) => source.mutateMessage(v),
1182
+ deleteMessage: (_c, id) => source.deleteMessage(id),
1183
+ storeThought: (_c, v) => source.storeThought(v),
1184
+ mutateThought: (_c, v) => source.mutateThought(v),
1185
+ deleteThought: (_c, id) => source.deleteThought(id),
1186
+ storeToolCall: (_c, v) => source.storeToolCall(v),
1187
+ mutateToolCall: (_c, v) => source.mutateToolCall(v),
1188
+ deleteToolCall: (_c, id) => source.deleteToolCall(id),
1189
+ waitFor: source.waitFor
1190
+ });
1191
+ }
1192
+ return new DispatchContext(raw);
1193
+ }
1194
+ #wireContextHooks(llmCtx) {
1195
+ const ctxHooks = llmCtx._getHooks();
1196
+ ctxHooks.add("message", (c) => {
1197
+ this.#functionalHooks.runner("message").run(c);
1198
+ if (this.#sourceCtx) this.#sourceCtx.emitMessage(c);
1199
+ });
1200
+ ctxHooks.add("thought", (c) => {
1201
+ this.#functionalHooks.runner("thought").run(c);
1202
+ if (this.#sourceCtx) this.#sourceCtx.emitThought(c);
1203
+ });
1204
+ ctxHooks.add("toolCall", (c) => {
1205
+ this.#functionalHooks.runner("toolCall").run(c);
1206
+ if (this.#sourceCtx) this.#sourceCtx.emitToolCall(c);
1207
+ });
1208
+ ctxHooks.add("toolExecutionStart", (e) => {
1209
+ this.#observabilityHooks.runner("toolExecutionStart").run(e);
1210
+ if (this.#sourceCtx) this.#sourceCtx.emitToolExecutionStart(e);
1211
+ });
1212
+ ctxHooks.add("toolExecutionEnd", (e) => {
1213
+ this.#observabilityHooks.runner("toolExecutionEnd").run(e);
1214
+ if (this.#sourceCtx) this.#sourceCtx.emitToolExecutionEnd(e);
1215
+ });
1216
+ ctxHooks.add("storedStandingInstruction", (v) => {
1217
+ this.#deltaQueue.push({
1218
+ op: "store",
1219
+ type: "standingInstruction",
1220
+ value: v
1221
+ });
1222
+ });
1223
+ ctxHooks.add("mutatedStandingInstruction", (v) => {
1224
+ this.#deltaQueue.push({
1225
+ op: "mutate",
1226
+ type: "standingInstruction",
1227
+ value: v
1228
+ });
1229
+ });
1230
+ ctxHooks.add("deletedStandingInstruction", (v) => {
1231
+ this.#deltaQueue.push({
1232
+ op: "delete",
1233
+ type: "standingInstruction",
1234
+ value: v
1235
+ });
1236
+ });
1237
+ ctxHooks.add("storedMemory", (v) => {
1238
+ this.#deltaQueue.push({
1239
+ op: "store",
1240
+ type: "memory",
1241
+ value: v
1242
+ });
1243
+ });
1244
+ ctxHooks.add("mutatedMemory", (v) => {
1245
+ this.#deltaQueue.push({
1246
+ op: "mutate",
1247
+ type: "memory",
1248
+ value: v
1249
+ });
1250
+ });
1251
+ ctxHooks.add("deletedMemory", (id) => {
1252
+ this.#deltaQueue.push({
1253
+ op: "delete",
1254
+ type: "memory",
1255
+ value: id
1256
+ });
1257
+ });
1258
+ ctxHooks.add("storedRetrievable", (v) => {
1259
+ this.#deltaQueue.push({
1260
+ op: "store",
1261
+ type: "retrievable",
1262
+ value: v
1263
+ });
1264
+ });
1265
+ ctxHooks.add("mutatedRetrievable", (v) => {
1266
+ this.#deltaQueue.push({
1267
+ op: "mutate",
1268
+ type: "retrievable",
1269
+ value: v
1270
+ });
1271
+ });
1272
+ ctxHooks.add("deletedRetrievable", (id) => {
1273
+ this.#deltaQueue.push({
1274
+ op: "delete",
1275
+ type: "retrievable",
1276
+ value: id
1277
+ });
1278
+ });
1279
+ ctxHooks.add("storedMessage", (v) => {
1280
+ this.#deltaQueue.push({
1281
+ op: "store",
1282
+ type: "message",
1283
+ value: v
1284
+ });
1285
+ });
1286
+ ctxHooks.add("mutatedMessage", (v) => {
1287
+ this.#deltaQueue.push({
1288
+ op: "mutate",
1289
+ type: "message",
1290
+ value: v
1291
+ });
1292
+ });
1293
+ ctxHooks.add("deletedMessage", (id) => {
1294
+ this.#deltaQueue.push({
1295
+ op: "delete",
1296
+ type: "message",
1297
+ value: id
1298
+ });
1299
+ });
1300
+ ctxHooks.add("storedThought", (v) => {
1301
+ this.#deltaQueue.push({
1302
+ op: "store",
1303
+ type: "thought",
1304
+ value: v
1305
+ });
1306
+ });
1307
+ ctxHooks.add("mutatedThought", (v) => {
1308
+ this.#deltaQueue.push({
1309
+ op: "mutate",
1310
+ type: "thought",
1311
+ value: v
1312
+ });
1313
+ });
1314
+ ctxHooks.add("deletedThought", (id) => {
1315
+ this.#deltaQueue.push({
1316
+ op: "delete",
1317
+ type: "thought",
1318
+ value: id
1319
+ });
1320
+ });
1321
+ ctxHooks.add("storedToolCall", (v) => {
1322
+ this.#deltaQueue.push({
1323
+ op: "store",
1324
+ type: "toolCall",
1325
+ value: v
1326
+ });
1327
+ });
1328
+ ctxHooks.add("mutatedToolCall", (v) => {
1329
+ this.#deltaQueue.push({
1330
+ op: "mutate",
1331
+ type: "toolCall",
1332
+ value: v
1333
+ });
1334
+ });
1335
+ ctxHooks.add("deletedToolCall", (id) => {
1336
+ this.#deltaQueue.push({
1337
+ op: "delete",
1338
+ type: "toolCall",
1339
+ value: id
1340
+ });
1341
+ });
1342
+ }
1343
+ /**
1344
+ * Constructs an {@link @nhtio/adk!DispatchExecutorHelpers} instance bound to a single dispatch.
1345
+ *
1346
+ * @remarks
1347
+ * Per-id stream state lives on closure-captured `Map`s, so it persists across iterations of
1348
+ * the dispatch but cannot leak between dispatches (the runner itself is single-use and
1349
+ * garbage-collected after `dispatch()` returns).
1350
+ */
1351
+ #buildHelpers(ctx) {
1352
+ const observabilityHooks = this.#observabilityHooks;
1353
+ const makeLogEmitter = (level) => (entry) => {
1354
+ const event = {
1355
+ dispatchId: ctx.dispatchId,
1356
+ iteration: ctx.iteration,
1357
+ emittedAt: DateTime.now(),
1358
+ level,
1359
+ kind: entry.kind,
1360
+ message: entry.message,
1361
+ ...entry.payload !== void 0 ? { payload: entry.payload } : {}
1362
+ };
1363
+ observabilityHooks.runner("log").run(event);
1364
+ };
1365
+ const log = {
1366
+ trace: makeLogEmitter("trace"),
1367
+ debug: makeLogEmitter("debug"),
1368
+ info: makeLogEmitter("info"),
1369
+ warn: makeLogEmitter("warn"),
1370
+ error: makeLogEmitter("error")
1371
+ };
1372
+ const messageStreams = /* @__PURE__ */ new Map();
1373
+ const thoughtStreams = /* @__PURE__ */ new Map();
1374
+ const toolCallStreams = /* @__PURE__ */ new Map();
1375
+ const buildStream = (store, id, deltaText, isComplete) => {
1376
+ let entry = store.get(id);
1377
+ const now = DateTime.now();
1378
+ if (!entry) {
1379
+ entry = {
1380
+ full: "",
1381
+ createdAt: now,
1382
+ isComplete: false
1383
+ };
1384
+ store.set(id, entry);
1385
+ }
1386
+ if (entry.isComplete) throw new Error(`stream "${id}" is already complete; further chunks are not accepted`);
1387
+ entry.full = entry.full + deltaText;
1388
+ entry.isComplete = isComplete;
1389
+ return {
1390
+ id,
1391
+ createdAt: entry.createdAt,
1392
+ updatedAt: now,
1393
+ full: entry.full,
1394
+ aDelta: deltaText,
1395
+ isComplete,
1396
+ ...isComplete ? { completedAt: now } : {}
1397
+ };
1398
+ };
1399
+ return {
1400
+ reportMessage: (id, deltaText, opts) => {
1401
+ const isComplete = opts?.isComplete ?? false;
1402
+ ctx.emitMessage(buildStream(messageStreams, id, deltaText, isComplete));
1403
+ },
1404
+ reportThought: (id, deltaText, opts) => {
1405
+ const isComplete = opts?.isComplete ?? false;
1406
+ ctx.emitThought(buildStream(thoughtStreams, id, deltaText, isComplete));
1407
+ },
1408
+ reportToolCall: (id, partial) => {
1409
+ let entry = toolCallStreams.get(id);
1410
+ const now = DateTime.now();
1411
+ if (!entry) {
1412
+ entry = {
1413
+ isError: false,
1414
+ isComplete: false,
1415
+ createdAt: now
1416
+ };
1417
+ toolCallStreams.set(id, entry);
1418
+ }
1419
+ if (entry.isComplete) throw new Error(`tool call "${id}" is already complete; further updates are not accepted`);
1420
+ if (partial.tool !== void 0) entry.tool = partial.tool;
1421
+ if (partial.args !== void 0) entry.args = partial.args;
1422
+ if (partial.results !== void 0) entry.results = partial.results;
1423
+ if (partial.isError !== void 0) entry.isError = partial.isError;
1424
+ if (partial.isComplete !== void 0) entry.isComplete = partial.isComplete;
1425
+ if (entry.tool !== void 0 && entry.args !== void 0) entry.checksum = sha256(canonicalStringify({
1426
+ tool: entry.tool,
1427
+ args: entry.args
1428
+ }));
1429
+ const content = {
1430
+ id,
1431
+ tool: entry.tool ?? "",
1432
+ args: entry.args,
1433
+ checksum: entry.checksum ?? "",
1434
+ createdAt: entry.createdAt,
1435
+ updatedAt: now,
1436
+ isComplete: entry.isComplete,
1437
+ isError: entry.isError,
1438
+ ...entry.results !== void 0 ? { results: entry.results } : {},
1439
+ ...entry.isComplete ? { completedAt: now } : {}
1440
+ };
1441
+ ctx.emitToolCall(content);
1442
+ },
1443
+ log
1444
+ };
1445
+ }
1446
+ async #runDispatch(llmCtx, executor) {
1447
+ const dispatchId = v6();
1448
+ llmCtx._setDispatchId(dispatchId);
1449
+ const dispatchStartedAt = DateTime.now();
1450
+ this.#observabilityHooks.runner("dispatchStart").run({
1451
+ dispatchId,
1452
+ startedAt: dispatchStartedAt
1453
+ });
1454
+ const helpers = this.#buildHelpers(llmCtx);
1455
+ let iteration = 0;
1456
+ let dispatchError;
1457
+ try {
1458
+ while (!llmCtx.aborted && !llmCtx.isSignalled) {
1459
+ llmCtx._setIteration(iteration);
1460
+ const iterationStartedAt = DateTime.now();
1461
+ this.#observabilityHooks.runner("iterationStart").run({
1462
+ dispatchId,
1463
+ iteration,
1464
+ startedAt: iterationStartedAt
1465
+ });
1466
+ await this.#runPipeline(this.#inputPipeline.runner(), llmCtx, "input");
1467
+ if (llmCtx.aborted || llmCtx.isSignalled) {
1468
+ if (llmCtx.isAcked && !llmCtx.aborted) await this.#flush();
1469
+ else this.#deltaQueue.length = 0;
1470
+ break;
1471
+ }
1472
+ try {
1473
+ await executor(llmCtx, helpers);
1474
+ } catch (err) {
1475
+ if (this.#isAbortError(err)) {
1476
+ this.#deltaQueue.length = 0;
1477
+ break;
1478
+ }
1479
+ const wrapped = new E_LLM_EXECUTION_EXECUTOR_ERROR({ cause: isError(err) ? err : void 0 });
1480
+ this.#observabilityHooks.runner("error").run(wrapped);
1481
+ this.#deltaQueue.length = 0;
1482
+ throw wrapped;
1483
+ }
1484
+ if (llmCtx.aborted || llmCtx.isSignalled) {
1485
+ if (llmCtx.isAcked && !llmCtx.aborted) await this.#flush();
1486
+ else this.#deltaQueue.length = 0;
1487
+ break;
1488
+ }
1489
+ await this.#runPipeline(this.#outputPipeline.runner(), llmCtx, "output");
1490
+ await this.#flush();
1491
+ const iterationEndedAt = DateTime.now();
1492
+ this.#observabilityHooks.runner("iterationEnd").run({
1493
+ dispatchId,
1494
+ iteration,
1495
+ startedAt: iterationStartedAt,
1496
+ endedAt: iterationEndedAt,
1497
+ durationMs: iterationEndedAt.diff(iterationStartedAt).milliseconds
1498
+ });
1499
+ iteration++;
1500
+ }
1501
+ } catch (err) {
1502
+ dispatchError = isError(err) ? err : new Error(String(err));
1503
+ }
1504
+ const status = dispatchError ? "nack" : llmCtx.nackError ? "nack" : llmCtx.isAcked ? "ack" : "aborted";
1505
+ const finalError = dispatchError ?? llmCtx.nackError;
1506
+ if (!dispatchError && llmCtx.nackError) {
1507
+ const nackErr = llmCtx.nackError;
1508
+ const wrapped = isInstanceOf(nackErr, "BaseException") ? nackErr : new E_LLM_EXECUTION_EXECUTOR_ERROR({ cause: isError(nackErr) ? nackErr : void 0 });
1509
+ this.#observabilityHooks.runner("error").run(wrapped);
1510
+ }
1511
+ const dispatchEndedAt = DateTime.now();
1512
+ this.#observabilityHooks.runner("dispatchEnd").run({
1513
+ dispatchId,
1514
+ status,
1515
+ error: finalError,
1516
+ iterations: iteration,
1517
+ startedAt: dispatchStartedAt,
1518
+ endedAt: dispatchEndedAt,
1519
+ durationMs: dispatchEndedAt.diff(dispatchStartedAt).milliseconds
1520
+ });
1521
+ if (finalError) throw finalError;
1522
+ }
1523
+ async #runPipeline(pipeline, llmCtx, label) {
1524
+ let pipelineError;
1525
+ let reached = false;
1526
+ await pipeline.errorHandler(async (error) => {
1527
+ if (this.#isAbortError(error)) return;
1528
+ pipelineError = new E_DISPATCH_PIPELINE_ERROR({ cause: isError(error) ? error : void 0 });
1529
+ }).finalHandler(async () => {
1530
+ reached = true;
1531
+ }).run((fn, next) => Promise.resolve(fn(llmCtx, next)));
1532
+ if (pipelineError) {
1533
+ this.#observabilityHooks.runner("error").run(pipelineError);
1534
+ throw pipelineError;
1535
+ }
1536
+ if (!reached && !llmCtx.aborted && !llmCtx.isSignalled) {
1537
+ const shortCircuitError = new E_PIPELINE_SHORT_CIRCUITED([`dispatch-${label}`]);
1538
+ this.#observabilityHooks.runner("error").run(shortCircuitError);
1539
+ throw shortCircuitError;
1540
+ }
1541
+ }
1542
+ #isAbortError(err) {
1543
+ return isError(err) && isInstanceOf(err, "AbortError");
1544
+ }
1545
+ async #flush() {
1546
+ if (!this.#sourceCtx) {
1547
+ this.#deltaQueue.length = 0;
1548
+ return;
1549
+ }
1550
+ while (this.#deltaQueue.length > 0) {
1551
+ const delta = this.#deltaQueue.shift();
1552
+ this.#applyDeltaToParent(delta);
1553
+ }
1554
+ }
1555
+ #applyDeltaToParent(delta) {
1556
+ const ctx = this.#sourceCtx;
1557
+ const { op, type, value } = delta;
1558
+ if (type === "standingInstruction") {
1559
+ const t = value;
1560
+ if (op === "store" || op === "mutate") ctx.standingInstructions.add(t);
1561
+ else ctx.standingInstructions.delete(t);
1562
+ return;
1563
+ }
1564
+ if (type === "memory") {
1565
+ if (op === "store" || op === "mutate") ctx.turnMemories.add(value);
1566
+ else for (const m of ctx.turnMemories) if (m.id === value) {
1567
+ ctx.turnMemories.delete(m);
1568
+ break;
1569
+ }
1570
+ return;
1571
+ }
1572
+ if (type === "retrievable") {
1573
+ if (op === "store" || op === "mutate") ctx.turnRetrievables.add(value);
1574
+ else for (const r of ctx.turnRetrievables) if (r.id === value) {
1575
+ ctx.turnRetrievables.delete(r);
1576
+ break;
1577
+ }
1578
+ return;
1579
+ }
1580
+ if (type === "message") {
1581
+ if (op === "store" || op === "mutate") ctx.turnMessages.add(value);
1582
+ else for (const m of ctx.turnMessages) if (m.id === value) {
1583
+ ctx.turnMessages.delete(m);
1584
+ break;
1585
+ }
1586
+ return;
1587
+ }
1588
+ if (type === "thought") {
1589
+ if (op === "store" || op === "mutate") ctx.turnThoughts.add(value);
1590
+ else for (const t of ctx.turnThoughts) if (t.id === value) {
1591
+ ctx.turnThoughts.delete(t);
1592
+ break;
1593
+ }
1594
+ return;
1595
+ }
1596
+ if (type === "toolCall") {
1597
+ if (op === "store" || op === "mutate") ctx.turnToolCalls.add(value);
1598
+ else for (const tc of ctx.turnToolCalls) if (tc.id === value) {
1599
+ ctx.turnToolCalls.delete(tc);
1600
+ break;
1601
+ }
1602
+ return;
1603
+ }
1604
+ }
1605
+ };
1606
+ //#endregion
1607
+ export { DispatchContext as n, TurnContext as r, DispatchRunner as t };
1608
+
1609
+ //# sourceMappingURL=dispatch_runner-9j6bXHL3.mjs.map