@nhtio/adk 0.1.0-master-e04b0eba → 0.1.0-master-d3e80e7a

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 (184) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/batteries/embeddings/index.d.ts +25 -0
  3. package/batteries/embeddings/openai/adapter.cjs +185 -0
  4. package/batteries/embeddings/openai/adapter.cjs.map +1 -0
  5. package/batteries/embeddings/openai/adapter.d.ts +74 -0
  6. package/batteries/embeddings/openai/adapter.mjs +183 -0
  7. package/batteries/embeddings/openai/adapter.mjs.map +1 -0
  8. package/batteries/embeddings/openai/exceptions.cjs +48 -0
  9. package/batteries/embeddings/openai/exceptions.cjs.map +1 -0
  10. package/batteries/embeddings/openai/exceptions.d.ts +45 -0
  11. package/batteries/embeddings/openai/exceptions.mjs +43 -0
  12. package/batteries/embeddings/openai/exceptions.mjs.map +1 -0
  13. package/batteries/embeddings/openai/helpers.cjs +25 -0
  14. package/batteries/embeddings/openai/helpers.cjs.map +1 -0
  15. package/batteries/embeddings/openai/helpers.d.ts +25 -0
  16. package/batteries/embeddings/openai/helpers.mjs +23 -0
  17. package/batteries/embeddings/openai/helpers.mjs.map +1 -0
  18. package/batteries/embeddings/openai/index.d.ts +17 -0
  19. package/batteries/embeddings/openai/types.cjs +2 -0
  20. package/batteries/embeddings/openai/types.d.ts +123 -0
  21. package/batteries/embeddings/openai/types.mjs +0 -0
  22. package/batteries/embeddings/openai/validation.cjs +56 -0
  23. package/batteries/embeddings/openai/validation.cjs.map +1 -0
  24. package/batteries/embeddings/openai/validation.d.ts +24 -0
  25. package/batteries/embeddings/openai/validation.mjs +53 -0
  26. package/batteries/embeddings/openai/validation.mjs.map +1 -0
  27. package/batteries/embeddings/openai.cjs +14 -0
  28. package/batteries/embeddings/openai.mjs +5 -0
  29. package/batteries/embeddings/webllm/adapter.cjs +147 -0
  30. package/batteries/embeddings/webllm/adapter.cjs.map +1 -0
  31. package/batteries/embeddings/webllm/adapter.d.ts +74 -0
  32. package/batteries/embeddings/webllm/adapter.mjs +145 -0
  33. package/batteries/embeddings/webllm/adapter.mjs.map +1 -0
  34. package/batteries/embeddings/webllm/exceptions.cjs +31 -0
  35. package/batteries/embeddings/webllm/exceptions.cjs.map +1 -0
  36. package/batteries/embeddings/webllm/exceptions.d.ts +25 -0
  37. package/batteries/embeddings/webllm/exceptions.mjs +28 -0
  38. package/batteries/embeddings/webllm/exceptions.mjs.map +1 -0
  39. package/batteries/embeddings/webllm/index.d.ts +15 -0
  40. package/batteries/embeddings/webllm/types.cjs +2 -0
  41. package/batteries/embeddings/webllm/types.d.ts +52 -0
  42. package/batteries/embeddings/webllm/types.mjs +0 -0
  43. package/batteries/embeddings/webllm/validation.cjs +43 -0
  44. package/batteries/embeddings/webllm/validation.cjs.map +1 -0
  45. package/batteries/embeddings/webllm/validation.d.ts +25 -0
  46. package/batteries/embeddings/webllm/validation.mjs +40 -0
  47. package/batteries/embeddings/webllm/validation.mjs.map +1 -0
  48. package/batteries/embeddings/webllm.cjs +10 -0
  49. package/batteries/embeddings/webllm.mjs +4 -0
  50. package/batteries/embeddings.cjs +15 -0
  51. package/batteries/embeddings.mjs +6 -0
  52. package/batteries/index.d.ts +1 -0
  53. package/batteries/llm/openai_chat_completions/adapter.cjs +14 -73
  54. package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -1
  55. package/batteries/llm/openai_chat_completions/adapter.mjs +8 -67
  56. package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -1
  57. package/batteries/llm/openai_chat_completions/helpers.cjs +2 -2
  58. package/batteries/llm/openai_chat_completions/helpers.mjs +2 -2
  59. package/batteries/llm/openai_chat_completions/validation.cjs +1 -1
  60. package/batteries/llm/openai_chat_completions/validation.mjs +1 -1
  61. package/batteries/llm/webllm_chat_completions/adapter.cjs +7 -6
  62. package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -1
  63. package/batteries/llm/webllm_chat_completions/adapter.mjs +7 -6
  64. package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -1
  65. package/batteries/llm/webllm_chat_completions/validation.cjs +1 -1
  66. package/batteries/llm/webllm_chat_completions/validation.mjs +1 -1
  67. package/batteries/storage/flydrive.cjs +1 -1
  68. package/batteries/storage/flydrive.mjs +1 -1
  69. package/batteries/storage/in_memory.cjs +1 -1
  70. package/batteries/storage/in_memory.mjs +1 -1
  71. package/batteries/storage/opfs.cjs +1 -1
  72. package/batteries/storage/opfs.mjs +1 -1
  73. package/batteries/tools/color.cjs +2 -2
  74. package/batteries/tools/color.mjs +2 -2
  75. package/batteries/tools/comparison.cjs +3 -3
  76. package/batteries/tools/comparison.mjs +3 -3
  77. package/batteries/tools/data_structure.cjs +3 -3
  78. package/batteries/tools/data_structure.mjs +3 -3
  79. package/batteries/tools/datetime_extended.cjs +2 -2
  80. package/batteries/tools/datetime_extended.mjs +2 -2
  81. package/batteries/tools/datetime_math.cjs +2 -2
  82. package/batteries/tools/datetime_math.mjs +2 -2
  83. package/batteries/tools/encoding.cjs +3 -3
  84. package/batteries/tools/encoding.mjs +3 -3
  85. package/batteries/tools/formatting.cjs +3 -3
  86. package/batteries/tools/formatting.mjs +3 -3
  87. package/batteries/tools/geo_basics.cjs +2 -2
  88. package/batteries/tools/geo_basics.mjs +2 -2
  89. package/batteries/tools/math.cjs +3 -3
  90. package/batteries/tools/math.mjs +3 -3
  91. package/batteries/tools/memory.cjs +5 -5
  92. package/batteries/tools/memory.mjs +5 -5
  93. package/batteries/tools/parsing.cjs +4 -4
  94. package/batteries/tools/parsing.mjs +4 -4
  95. package/batteries/tools/retrievables.cjs +4 -4
  96. package/batteries/tools/retrievables.mjs +4 -4
  97. package/batteries/tools/standing_instructions.cjs +4 -4
  98. package/batteries/tools/standing_instructions.mjs +4 -4
  99. package/batteries/tools/statistics.cjs +4 -4
  100. package/batteries/tools/statistics.mjs +4 -4
  101. package/batteries/tools/string_processing.cjs +3 -3
  102. package/batteries/tools/string_processing.mjs +3 -3
  103. package/batteries/tools/structured_data.cjs +3 -3
  104. package/batteries/tools/structured_data.mjs +3 -3
  105. package/batteries/tools/text_analysis.cjs +3 -3
  106. package/batteries/tools/text_analysis.mjs +3 -3
  107. package/batteries/tools/text_comparison.cjs +2 -2
  108. package/batteries/tools/text_comparison.mjs +2 -2
  109. package/batteries/tools/time.cjs +2 -2
  110. package/batteries/tools/time.mjs +2 -2
  111. package/batteries/tools/unit_conversion.cjs +2 -2
  112. package/batteries/tools/unit_conversion.mjs +2 -2
  113. package/batteries.cjs +13 -0
  114. package/batteries.mjs +8 -3
  115. package/{common-DuKWGTVd.js → common-D_e5zYsG.js} +8 -8
  116. package/{common-DuKWGTVd.js.map → common-D_e5zYsG.js.map} +1 -1
  117. package/{common-ClCHam5-.mjs → common-lMrnzoyn.mjs} +8 -8
  118. package/{common-ClCHam5-.mjs.map → common-lMrnzoyn.mjs.map} +1 -1
  119. package/common.cjs +7 -7
  120. package/common.mjs +7 -7
  121. package/{dispatch_runner-uNtS-XSP.mjs → dispatch_runner-CDF3X0nv.mjs} +3 -3
  122. package/{dispatch_runner-uNtS-XSP.mjs.map → dispatch_runner-CDF3X0nv.mjs.map} +1 -1
  123. package/{dispatch_runner-CEFHXRJZ.js → dispatch_runner-CpuyATj1.js} +3 -3
  124. package/{dispatch_runner-CEFHXRJZ.js.map → dispatch_runner-CpuyATj1.js.map} +1 -1
  125. package/dispatch_runner.cjs +1 -1
  126. package/dispatch_runner.mjs +1 -1
  127. package/exceptions.cjs +1 -1
  128. package/exceptions.mjs +1 -1
  129. package/forge.cjs +4 -4
  130. package/forge.mjs +4 -4
  131. package/guards.cjs +8 -8
  132. package/guards.mjs +8 -8
  133. package/index.cjs +12 -12
  134. package/index.mjs +12 -12
  135. package/lib/exceptions/runtime.d.ts +5 -0
  136. package/lib/types/turn_runner.d.ts +32 -10
  137. package/lib/utils/retry.cjs +107 -0
  138. package/lib/utils/retry.cjs.map +1 -0
  139. package/lib/utils/retry.d.ts +63 -0
  140. package/lib/utils/retry.mjs +102 -0
  141. package/lib/utils/retry.mjs.map +1 -0
  142. package/mcp/adk-docs-corpus.json +1 -1
  143. package/package.json +128 -63
  144. package/{runtime-DyD9oQjH.js → runtime-MFFcJrRv.js} +6 -2
  145. package/runtime-MFFcJrRv.js.map +1 -0
  146. package/{runtime-CDIZwCT0.mjs → runtime-j92CNi5z.mjs} +6 -2
  147. package/runtime-j92CNi5z.mjs.map +1 -0
  148. package/skills/adk-assembly/SKILL.md +2 -2
  149. package/{spooled_artifact-CHvDDYGA.js → spooled_artifact-B8gIIn9h.js} +4 -4
  150. package/{spooled_artifact-CHvDDYGA.js.map → spooled_artifact-B8gIIn9h.js.map} +1 -1
  151. package/{spooled_artifact-D-JrpY4W.mjs → spooled_artifact-CWoKUDEm.mjs} +4 -4
  152. package/{spooled_artifact-D-JrpY4W.mjs.map → spooled_artifact-CWoKUDEm.mjs.map} +1 -1
  153. package/spooled_artifact.cjs +2 -2
  154. package/spooled_artifact.mjs +2 -2
  155. package/{spooled_markdown_artifact-B4eWOfCX.mjs → spooled_markdown_artifact-CNle4jXN.mjs} +3 -3
  156. package/{spooled_markdown_artifact-B4eWOfCX.mjs.map → spooled_markdown_artifact-CNle4jXN.mjs.map} +1 -1
  157. package/{spooled_markdown_artifact-BYfPqFvk.js → spooled_markdown_artifact-DQX0RCdI.js} +3 -3
  158. package/{spooled_markdown_artifact-BYfPqFvk.js.map → spooled_markdown_artifact-DQX0RCdI.js.map} +1 -1
  159. package/{thought-DBNsR6l8.js → thought-BD6AkkOr.js} +4 -4
  160. package/{thought-DBNsR6l8.js.map → thought-BD6AkkOr.js.map} +1 -1
  161. package/{thought-D9IS11b5.mjs → thought-B_P8LiB6.mjs} +4 -4
  162. package/{thought-D9IS11b5.mjs.map → thought-B_P8LiB6.mjs.map} +1 -1
  163. package/{tool-CsYuHhiS.mjs → tool-CRZSUcdP.mjs} +3 -3
  164. package/{tool-CsYuHhiS.mjs.map → tool-CRZSUcdP.mjs.map} +1 -1
  165. package/{tool-DIHzOZiV.js → tool-CX9vNHAw.js} +3 -3
  166. package/{tool-DIHzOZiV.js.map → tool-CX9vNHAw.js.map} +1 -1
  167. package/{tool_call-CkOVOhg0.js → tool_call--7ti-frB.js} +4 -4
  168. package/{tool_call-CkOVOhg0.js.map → tool_call--7ti-frB.js.map} +1 -1
  169. package/{tool_call-Bs_Q5LOG.mjs → tool_call-BUeMuCc6.mjs} +4 -4
  170. package/{tool_call-Bs_Q5LOG.mjs.map → tool_call-BUeMuCc6.mjs.map} +1 -1
  171. package/{tool_registry-CX3ofUh9.mjs → tool_registry-BGHg6KTq.mjs} +2 -2
  172. package/{tool_registry-CX3ofUh9.mjs.map → tool_registry-BGHg6KTq.mjs.map} +1 -1
  173. package/{tool_registry-CKk5ooxm.js → tool_registry-CtCQ4Xoz.js} +2 -2
  174. package/{tool_registry-CKk5ooxm.js.map → tool_registry-CtCQ4Xoz.js.map} +1 -1
  175. package/{turn_runner-D0qGIrRI.js → turn_runner-BJTtAORU.js} +7 -6
  176. package/turn_runner-BJTtAORU.js.map +1 -0
  177. package/{turn_runner-C1-mup84.mjs → turn_runner-C02LZHjt.mjs} +8 -7
  178. package/turn_runner-C02LZHjt.mjs.map +1 -0
  179. package/turn_runner.cjs +1 -1
  180. package/turn_runner.mjs +1 -1
  181. package/runtime-CDIZwCT0.mjs.map +0 -1
  182. package/runtime-DyD9oQjH.js.map +0 -1
  183. package/turn_runner-C1-mup84.mjs.map +0 -1
  184. package/turn_runner-D0qGIrRI.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"dispatch_runner-uNtS-XSP.mjs","names":["#id","#turnAbortController","#stash","#systemPrompt","#standingInstructions","#turnMemories","#turnRetrievables","#turnMessages","#turnThoughts","#turnToolCalls","#id","#dispatchId","#iteration","#turnAbortController","#stash","#systemPrompt","#standingInstructions","#turnMemories","#turnRetrievables","#turnMessages","#turnThoughts","#turnToolCalls","#tools","#toolCallChecksums","#fetchMemories","#fetchRetrievables","#fetchMessages","#fetchThoughts","#fetchToolCalls","#fetchTools","#refreshStandingInstructions","#storeStandingInstruction","#mutateStandingInstruction","#deleteStandingInstruction","#storeMemory","#mutateMemory","#deleteMemory","#storeRetrievable","#mutateRetrievable","#deleteRetrievable","#storeMessage","#mutateMessage","#deleteMessage","#storeThought","#mutateThought","#deleteThought","#storeToolCall","#mutateToolCall","#deleteToolCall","#storeMediaBytes","#storeRetrievableBytes","#waitFor","#signalled","#nackError","#hooks","#ackHandlers","#doStoreStandingInstruction","#doMutateStandingInstruction","#doDeleteStandingInstruction","#doStoreMemory","#doMutateMemory","#doDeleteMemory","#doStoreRetrievable","#doMutateRetrievable","#doDeleteRetrievable","#doStoreMessage","#doMutateMessage","#doDeleteMessage","#doStoreThought","#doMutateThought","#doDeleteThought","#doStoreToolCall","#doMutateToolCall","#doDeleteToolCall","#sourceCtx","#deltaQueue","#functionalHooks","#observabilityHooks","#inputPipeline","#outputPipeline","#buildContext","#wireContextHooks","#runDispatch","#buildHelpers","#runPipeline","#flush","#isAbortError","#applyDeltaToParent"],"sources":["../src/lib/contracts/turn_runner_context.ts","../src/lib/contracts/dispatch_context.ts","../src/lib/dispatch_runner.ts"],"sourcesContent":["import { v6 as uuidv6 } from 'uuid'\nimport { validator } from '@nhtio/validation'\nimport { Registry } from '../classes/registry'\nimport { Tokenizable } from '../classes/tokenizable'\nimport { validateOrThrow } from '../utils/validation'\nimport { isInstanceOf, isError } from '../utils/guards'\nimport { E_INVALID_TURN_CONTEXT } from '../exceptions/runtime'\nimport type { Tool } from '../classes/tool'\nimport type { Memory } from '../classes/memory'\nimport type { Message } from '../classes/message'\nimport type { Thought } from '../classes/thought'\nimport type { SpoolReader } from './spool_reader'\nimport type { MediaReader } from './media_reader'\nimport type { ToolCall } from '../classes/tool_call'\nimport type { ConduitBytes } from './dispatch_context'\nimport type { Retrievable } from '../classes/retrievable'\nimport type { ToolRegistry } from '../classes/tool_registry'\nimport type {\n EmitMessageFn,\n EmitThoughtFn,\n EmitToolCallFn,\n EmitToolExecutionEndFn,\n EmitToolExecutionStartFn,\n OpenGateFn,\n} from '../types/turn_runner'\n\n/**\n * Plain input object supplied to {@link TurnContext} at construction time.\n *\n * @remarks\n * Validated against `turnContextSchema` before the `TurnContext` instance is created.\n * Fields will grow as the turn execution model takes shape (e.g. input message, tool\n * definitions, model client config).\n */\nexport interface RawTurnContext {\n /** `AbortController` whose signal can be used to cancel the turn mid-flight. */\n turnAbortController: AbortController\n /** A registry for arbitrary additional data to be added to the context as needed; initially empty. */\n stash?: Record<string, unknown>\n /** The system prompt guiding the agent's behavior for this turn. */\n systemPrompt: string | Tokenizable\n /** Standing instructions for the agent, applied to every turn. */\n standingInstructions: (string | Tokenizable)[]\n}\n\n/**\n * A fully-resolved {@link RawTurnContext} where all optional fields have been filled in by the\n * schema (e.g. `stash` defaulted to `{}`).\n *\n * @remarks\n * This is the shape returned by `turnContextSchema` after validation — use it wherever a\n * guaranteed-present context is needed rather than the raw caller-supplied input.\n */\nexport type ResolvedTurnContext = Required<RawTurnContext>\n\n/**\n * Validator schema used to validate a {@link RawTurnContext} before constructing a {@link TurnContext}.\n *\n * @remarks\n * Validates all four fields of {@link RawTurnContext}:\n * - `turnAbortController` — required `AbortController` instance.\n * - `stash` — optional string-keyed object; defaults to `{}`.\n * - `systemPrompt` — required string or {@link @nhtio/adk!Tokenizable}, via {@link @nhtio/adk!Tokenizable.schema}.\n * - `standingInstructions` — optional array of strings or {@link @nhtio/adk!Tokenizable} instances, each\n * validated via {@link @nhtio/adk!Tokenizable.schema}; defaults to `[]`.\n *\n * Throws a `ValidationException` (via {@link validateOrThrow}) when validation fails.\n */\nexport const turnContextSchema = validator\n .object<RawTurnContext>({\n turnAbortController: validator\n .alternatives(\n validator.object().instance(AbortController as any),\n validator.function().instance(AbortController as any)\n )\n .required(),\n stash: validator.object().pattern(validator.string(), validator.any()).default({}),\n systemPrompt: Tokenizable.schema.required(),\n standingInstructions: validator.array().items(Tokenizable.schema).default([]),\n })\n .required()\n\n/**\n * A function that retrieves the memories relevant to the current turn.\n *\n * @remarks\n * Receives the active {@link TurnContext} so implementations can filter or rank memories\n * based on turn-specific state (e.g. the system prompt, standing instructions, or stash).\n * May be synchronous or asynchronous.\n */\nexport type MemoryRetrievalFn = (ctx: TurnContext) => Memory[] | Promise<Memory[]>\n\n/**\n * A function that retrieves the retrievable (RAG) records relevant to the current turn.\n *\n * @remarks\n * Receives the active {@link TurnContext} so implementations can rank, filter, or compose\n * retrieval results against the turn-specific state (system prompt, standing instructions, etc.).\n * The retrieval middleware that produces these records is responsible for assigning each one's\n * `trustTier` — batteries MUST NOT auto-classify retrieved content.\n * May be synchronous or asynchronous.\n */\nexport type RetrievableRetrievalFn = (ctx: TurnContext) => Retrievable[] | Promise<Retrievable[]>\n\n/**\n * A function that retrieves the conversation messages relevant to the current turn.\n *\n * @remarks\n * Receives the active {@link TurnContext} so implementations can apply turn-aware filtering or\n * windowing. Returns only `user` and `assistant` {@link @nhtio/adk!Message} entries — system instructions\n * and tool results are not part of the persisted message history.\n * May be synchronous or asynchronous.\n */\nexport type MessageRetrievalFn = (ctx: TurnContext) => Message[] | Promise<Message[]>\n\n/**\n * A function that retrieves the thought traces relevant to the current turn.\n *\n * @remarks\n * Receives the active {@link TurnContext} so implementations can apply turn-aware filtering or\n * attribution (e.g. filtering to a specific agent's identity in multi-agent conversations).\n * May be synchronous or asynchronous.\n */\nexport type ThoughtRetrievalFn = (ctx: TurnContext) => Thought[] | Promise<Thought[]>\n\n/**\n * A function that retrieves the tool call records relevant to the current turn.\n *\n * @remarks\n * Receives the active {@link TurnContext} so implementations can filter by completion state,\n * agent identity, or any other turn-specific criteria.\n * May be synchronous or asynchronous.\n */\nexport type ToolCallRetrievalFn = (ctx: TurnContext) => ToolCall[] | Promise<ToolCall[]>\n\n/**\n * A function that retrieves the tools available for the current turn.\n *\n * @remarks\n * Receives the active {@link TurnContext} so implementations can apply turn-aware filtering\n * (e.g. RBAC scopes, feature flags). May be synchronous or asynchronous.\n */\nexport type ToolsRetrievalFn = (ctx: TurnContext) => Tool[] | Promise<Tool[]>\n\n/**\n * A function that refreshes and returns the standing instructions for the current turn.\n *\n * @remarks\n * Called to re-derive standing instructions mid-turn when they may have changed.\n * May be synchronous or asynchronous.\n */\nexport type StandingInstructionsRefreshFn = (\n ctx: TurnContext\n) => (string | Tokenizable)[] | Promise<(string | Tokenizable)[]>\n\n/** Stores a new standing instruction in the persistence layer. */\nexport type StandingInstructionStoreFn = (\n ctx: TurnContext,\n v: string | Tokenizable\n) => void | Promise<void>\n\n/** Updates an existing standing instruction in the persistence layer. */\nexport type StandingInstructionMutateFn = (\n ctx: TurnContext,\n v: string | Tokenizable\n) => void | Promise<void>\n\n/** Removes a standing instruction from the persistence layer. */\nexport type StandingInstructionDeleteFn = (\n ctx: TurnContext,\n v: string | Tokenizable\n) => void | Promise<void>\n\n/** Stores a new memory in the persistence layer. */\nexport type MemoryStoreFn = (ctx: TurnContext, v: Memory) => void | Promise<void>\n\n/** Updates an existing memory in the persistence layer. */\nexport type MemoryMutateFn = (ctx: TurnContext, v: Memory) => void | Promise<void>\n\n/** Removes a memory from the persistence layer by ID. */\nexport type MemoryDeleteFn = (ctx: TurnContext, id: string) => void | Promise<void>\n\n/** Stores a new retrievable record in the persistence layer. */\nexport type RetrievableStoreFn = (ctx: TurnContext, v: Retrievable) => void | Promise<void>\n\n/** Updates an existing retrievable record in the persistence layer. */\nexport type RetrievableMutateFn = (ctx: TurnContext, v: Retrievable) => void | Promise<void>\n\n/** Removes a retrievable record from the persistence layer by ID. */\nexport type RetrievableDeleteFn = (ctx: TurnContext, id: string) => void | Promise<void>\n\n/** Stores a new message in the persistence layer. */\nexport type MessageStoreFn = (ctx: TurnContext, v: Message) => void | Promise<void>\n\n/** Updates an existing message in the persistence layer. */\nexport type MessageMutateFn = (ctx: TurnContext, v: Message) => void | Promise<void>\n\n/** Removes a message from the persistence layer by ID. */\nexport type MessageDeleteFn = (ctx: TurnContext, id: string) => void | Promise<void>\n\n/** Stores a new thought in the persistence layer. */\nexport type ThoughtStoreFn = (ctx: TurnContext, v: Thought) => void | Promise<void>\n\n/** Updates an existing thought in the persistence layer. */\nexport type ThoughtMutateFn = (ctx: TurnContext, v: Thought) => void | Promise<void>\n\n/** Removes a thought from the persistence layer by ID. */\nexport type ThoughtDeleteFn = (ctx: TurnContext, id: string) => void | Promise<void>\n\n/** Stores a new tool call in the persistence layer. */\nexport type ToolCallStoreFn = (ctx: TurnContext, v: ToolCall) => void | Promise<void>\n\n/** Updates an existing tool call in the persistence layer. */\nexport type ToolCallMutateFn = (ctx: TurnContext, v: ToolCall) => void | Promise<void>\n\n/** Removes a tool call from the persistence layer by ID. */\nexport type ToolCallDeleteFn = (ctx: TurnContext, id: string) => void | Promise<void>\n\n/**\n * Persists tool-generated media bytes into consumer storage and returns a {@link @nhtio/adk!MediaReader}.\n * A byte-persistence conduit, not a mutation — returns a value and touches no turn state.\n */\nexport type MediaBytesStoreFn = (\n ctx: TurnContext,\n id: string,\n bytes: ConduitBytes\n) => MediaReader | Promise<MediaReader>\n\n/**\n * Persists extracted retrievable text bytes into consumer storage and returns a\n * {@link @nhtio/adk!SpoolReader}. A byte-persistence conduit, not a mutation.\n */\nexport type RetrievableBytesStoreFn = (\n ctx: TurnContext,\n id: string,\n bytes: ConduitBytes\n) => SpoolReader | Promise<SpoolReader>\n\n/**\n * Callbacks injected into a {@link TurnContext} by `TurnRunner` at run time.\n *\n * @remarks\n * These are supplied by the `TurnRunnerConfig` and bound to the context so middleware\n * can call fetch, emit, and mutation methods directly on the context without needing a reference\n * to the runner or its emitters. Not exported — `TurnContext` is constructed internally and\n * callers never need to reference this shape.\n *\n * @internal\n */\ninterface TurnRunnerInjected {\n /** Retrieves memories relevant to this turn. */\n fetchMemories: MemoryRetrievalFn\n /** Retrieves conversation messages relevant to this turn. */\n fetchMessages: MessageRetrievalFn\n /** Retrieves thought traces relevant to this turn. */\n fetchThoughts: ThoughtRetrievalFn\n /** Retrieves tool call records relevant to this turn. */\n fetchToolCalls: ToolCallRetrievalFn\n /** Retrieves tools available for this turn. */\n fetchTools: ToolsRetrievalFn\n /** Refreshes and returns the standing instructions for this turn. */\n refreshStandingInstructions: StandingInstructionsRefreshFn\n /** Stores a new standing instruction in the persistence layer. */\n storeStandingInstruction: StandingInstructionStoreFn\n /** Updates an existing standing instruction in the persistence layer. */\n mutateStandingInstruction: StandingInstructionMutateFn\n /** Removes a standing instruction from the persistence layer. */\n deleteStandingInstruction: StandingInstructionDeleteFn\n /** Stores a new memory in the persistence layer. */\n storeMemory: MemoryStoreFn\n /** Updates an existing memory in the persistence layer. */\n mutateMemory: MemoryMutateFn\n /** Removes a memory from the persistence layer by ID. */\n deleteMemory: MemoryDeleteFn\n /** Retrieves retrievable records relevant to this turn. */\n fetchRetrievables: RetrievableRetrievalFn\n /** Stores a new retrievable record in the persistence layer. */\n storeRetrievable: RetrievableStoreFn\n /** Updates an existing retrievable record in the persistence layer. */\n mutateRetrievable: RetrievableMutateFn\n /** Removes a retrievable record from the persistence layer by ID. */\n deleteRetrievable: RetrievableDeleteFn\n /** Stores a new message in the persistence layer. */\n storeMessage: MessageStoreFn\n /** Updates an existing message in the persistence layer. */\n mutateMessage: MessageMutateFn\n /** Removes a message from the persistence layer by ID. */\n deleteMessage: MessageDeleteFn\n /** Stores a new thought in the persistence layer. */\n storeThought: ThoughtStoreFn\n /** Updates an existing thought in the persistence layer. */\n mutateThought: ThoughtMutateFn\n /** Removes a thought from the persistence layer by ID. */\n deleteThought: ThoughtDeleteFn\n /** Stores a new tool call in the persistence layer. */\n storeToolCall: ToolCallStoreFn\n /** Updates an existing tool call in the persistence layer. */\n mutateToolCall: ToolCallMutateFn\n /** Removes a tool call from the persistence layer by ID. */\n deleteToolCall: ToolCallDeleteFn\n /** Persists tool-generated media bytes; returns a `MediaReader`. */\n storeMediaBytes: MediaBytesStoreFn\n /** Persists extracted retrievable text bytes; returns a `SpoolReader`. */\n storeRetrievableBytes: RetrievableBytesStoreFn\n /** Emits a `message` event on the runner. */\n emitMessage: EmitMessageFn\n /** Emits a `thought` event on the runner. */\n emitThought: EmitThoughtFn\n /** Emits a `toolCall` event on the runner. */\n emitToolCall: EmitToolCallFn\n /** Emits a `toolExecutionStart` event on the observability bus. */\n emitToolExecutionStart: EmitToolExecutionStartFn\n /** Emits a `toolExecutionEnd` event on the observability bus. */\n emitToolExecutionEnd: EmitToolExecutionEndFn\n /** Opens a turn gate; `turnId` and `abortSignal` are injected by the runner. */\n openGate: OpenGateFn\n /** The turn-scoped tool registry constructed from the runner's baseline tools. */\n tools: ToolRegistry\n}\n\n/**\n * The validated, strongly-typed context object threaded through every middleware step in a\n * single agent turn.\n *\n * @remarks\n * Constructed from a {@link RawTurnContext} by {@link @nhtio/adk!TurnRunner.run}. Middleware functions\n * receive this object and use it to read and share state across pipeline steps.\n */\nexport class TurnContext {\n /**\n * Returns `true` if `value` is a {@link TurnContext} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety. The ADK does not export the\n * `TurnContext` class itself as a constructable value — use this guard plus the\n * {@link TurnContext} type for runtime detection and TypeScript narrowing.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link TurnContext} instance.\n */\n public static isTurnContext(value: unknown): value is TurnContext {\n return isInstanceOf(value, 'TurnContext', TurnContext)\n }\n\n #id: string\n #turnAbortController: AbortController\n #stash: Registry\n #systemPrompt: Tokenizable\n #standingInstructions: Set<Tokenizable>\n #turnMemories: Set<Memory>\n #turnRetrievables: Set<Retrievable>\n #turnMessages: Set<Message>\n #turnThoughts: Set<Thought>\n #turnToolCalls: Set<ToolCall>\n\n /**\n * @param raw - The raw context input validated against {@link turnContextSchema}.\n * @param injected - Runtime callbacks supplied by `TurnRunner`; bound as instance methods so\n * middleware can call fetch and emit methods directly on the context.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} when `raw` does not satisfy the schema.\n *\n * @internal\n */\n constructor(raw: RawTurnContext, injected: TurnRunnerInjected) {\n try {\n raw = validateOrThrow<ResolvedTurnContext>(turnContextSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_TURN_CONTEXT({ cause: isError(err) ? err : undefined })\n }\n this.#id = uuidv6()\n this.#turnAbortController = raw.turnAbortController\n this.#stash = new Registry(raw.stash)\n this.#systemPrompt = Tokenizable.isTokenizable(raw.systemPrompt)\n ? raw.systemPrompt\n : new Tokenizable(raw.systemPrompt)\n this.#standingInstructions = new Set(\n (raw.standingInstructions || []).map((instr) =>\n Tokenizable.isTokenizable(instr) ? instr : new Tokenizable(instr)\n )\n )\n this.#turnMemories = new Set()\n this.#turnRetrievables = new Set()\n this.#turnMessages = new Set()\n this.#turnThoughts = new Set()\n this.#turnToolCalls = new Set()\n\n // Expose read-only properties on the instance for easy access in middleware.\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n aborted: {\n get: () => Boolean(this.#turnAbortController.signal.aborted),\n enumerable: true,\n configurable: false,\n },\n abortSignal: {\n get: () => this.#turnAbortController.signal,\n enumerable: true,\n configurable: false,\n },\n abort: {\n value: (reason?: unknown) => this.#turnAbortController.abort(reason),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n stash: {\n get: () => this.#stash,\n enumerable: true,\n configurable: false,\n },\n systemPrompt: {\n get: () => this.#systemPrompt,\n enumerable: true,\n configurable: false,\n },\n standingInstructions: {\n get: () => this.#standingInstructions,\n enumerable: true,\n configurable: false,\n },\n turnMemories: {\n get: () => this.#turnMemories,\n enumerable: true,\n configurable: false,\n },\n turnRetrievables: {\n get: () => this.#turnRetrievables,\n enumerable: true,\n configurable: false,\n },\n turnMessages: {\n get: () => this.#turnMessages,\n enumerable: true,\n configurable: false,\n },\n turnThoughts: {\n get: () => this.#turnThoughts,\n enumerable: true,\n configurable: false,\n },\n turnToolCalls: {\n get: () => this.#turnToolCalls,\n enumerable: true,\n configurable: false,\n },\n })\n\n // Attach injected dependencies as instance methods for access in middleware.\n Object.defineProperties(this, {\n fetchMemories: {\n value: () => injected.fetchMemories(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchMessages: {\n value: () => injected.fetchMessages(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchThoughts: {\n value: () => injected.fetchThoughts(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchToolCalls: {\n value: () => injected.fetchToolCalls(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchTools: {\n value: () => injected.fetchTools(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n refreshStandingInstructions: {\n value: () => injected.refreshStandingInstructions(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeStandingInstruction: {\n value: (v: string | Tokenizable) => injected.storeStandingInstruction(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateStandingInstruction: {\n value: (v: string | Tokenizable) => injected.mutateStandingInstruction(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteStandingInstruction: {\n value: (v: string | Tokenizable) => injected.deleteStandingInstruction(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeMemory: {\n value: (v: Memory) => injected.storeMemory(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateMemory: {\n value: (v: Memory) => injected.mutateMemory(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteMemory: {\n value: (id: string) => injected.deleteMemory(this, id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchRetrievables: {\n value: () => injected.fetchRetrievables(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeRetrievable: {\n value: (v: Retrievable) => injected.storeRetrievable(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateRetrievable: {\n value: (v: Retrievable) => injected.mutateRetrievable(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteRetrievable: {\n value: (id: string) => injected.deleteRetrievable(this, id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeMessage: {\n value: (v: Message) => injected.storeMessage(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateMessage: {\n value: (v: Message) => injected.mutateMessage(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteMessage: {\n value: (id: string) => injected.deleteMessage(this, id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeThought: {\n value: (v: Thought) => injected.storeThought(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateThought: {\n value: (v: Thought) => injected.mutateThought(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteThought: {\n value: (id: string) => injected.deleteThought(this, id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeToolCall: {\n value: (v: ToolCall) => injected.storeToolCall(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateToolCall: {\n value: (v: ToolCall) => injected.mutateToolCall(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteToolCall: {\n value: (id: string) => injected.deleteToolCall(this, id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeMediaBytes: {\n value: (id: string, bytes: ConduitBytes) => injected.storeMediaBytes(this, id, bytes),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeRetrievableBytes: {\n value: (id: string, bytes: ConduitBytes) => injected.storeRetrievableBytes(this, id, bytes),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitMessage: {\n value: injected.emitMessage,\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitThought: {\n value: injected.emitThought,\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitToolCall: {\n value: injected.emitToolCall,\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitToolExecutionStart: {\n value: injected.emitToolExecutionStart,\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitToolExecutionEnd: {\n value: injected.emitToolExecutionEnd,\n enumerable: true,\n configurable: false,\n writable: false,\n },\n waitFor: {\n value: injected.openGate,\n enumerable: true,\n configurable: false,\n writable: false,\n },\n tools: {\n get: () => injected.tools,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /** Unique identifier for this turn, generated as a UUIDv6 at construction time. */\n declare readonly id: string\n /** `true` when the turn's `AbortController` signal has fired. */\n declare readonly aborted: boolean\n /** The `AbortSignal` from the turn's `AbortController`. */\n declare readonly abortSignal: AbortSignal\n /**\n * Aborts the turn's `AbortController` with the supplied reason. Middleware should call this\n * when refusing the turn — the runner reads `aborted` between every stage and short-circuits\n * cleanly: `turnEnd` still fires, no `error` event is emitted, and during dispatch\n * `dispatchEnd.status === 'aborted'` carries the operational signal.\n */\n declare readonly abort: (reason?: unknown) => void\n /** Arbitrary key-value store that middleware can read and write across pipeline steps. */\n declare readonly stash: Registry\n /** The system prompt guiding the agent's behaviour for this turn. */\n declare readonly systemPrompt: Tokenizable\n /** Standing instructions applied to every turn, in insertion order. */\n declare readonly standingInstructions: Set<Tokenizable>\n /** Memories loaded for this turn; populated by middleware after calling `fetchMemories()`. */\n declare readonly turnMemories: Set<Memory>\n /** Retrievable records loaded for this turn; populated by middleware after calling `fetchRetrievables()`. */\n declare readonly turnRetrievables: Set<Retrievable>\n /** Conversation messages loaded for this turn; populated by middleware after calling `fetchMessages()`. */\n declare readonly turnMessages: Set<Message>\n /** Thought traces loaded for this turn; populated by middleware after calling `fetchThoughts()`. */\n declare readonly turnThoughts: Set<Thought>\n /** Tool call records loaded for this turn; populated by middleware after calling `fetchToolCalls()`. */\n declare readonly turnToolCalls: Set<ToolCall>\n /** Fetches memories relevant to this turn; delegates to the callback supplied at construction. */\n declare readonly fetchMemories: () => Memory[] | Promise<Memory[]>\n /** Fetches conversation messages relevant to this turn; delegates to the callback supplied at construction. */\n declare readonly fetchMessages: () => Message[] | Promise<Message[]>\n /** Fetches thought traces relevant to this turn; delegates to the callback supplied at construction. */\n declare readonly fetchThoughts: () => Thought[] | Promise<Thought[]>\n /** Fetches tool call records relevant to this turn; delegates to the callback supplied at construction. */\n declare readonly fetchToolCalls: () => ToolCall[] | Promise<ToolCall[]>\n /** Fetches tools available for this turn; delegates to the callback supplied at construction. */\n declare readonly fetchTools: () => Tool[] | Promise<Tool[]>\n /** Refreshes and returns the standing instructions; delegates to the callback supplied at construction. */\n declare readonly refreshStandingInstructions: () =>\n | (string | Tokenizable)[]\n | Promise<(string | Tokenizable)[]>\n /** Stores a new standing instruction in the persistence layer. */\n declare readonly storeStandingInstruction: (v: string | Tokenizable) => void | Promise<void>\n /** Updates an existing standing instruction in the persistence layer. */\n declare readonly mutateStandingInstruction: (v: string | Tokenizable) => void | Promise<void>\n /** Removes a standing instruction from the persistence layer. */\n declare readonly deleteStandingInstruction: (v: string | Tokenizable) => void | Promise<void>\n /** Stores a new memory in the persistence layer. */\n declare readonly storeMemory: (v: Memory) => void | Promise<void>\n /** Updates an existing memory in the persistence layer. */\n declare readonly mutateMemory: (v: Memory) => void | Promise<void>\n /** Removes a memory from the persistence layer by ID. */\n declare readonly deleteMemory: (id: string) => void | Promise<void>\n /** Fetches retrievable records relevant to this turn; delegates to the callback supplied at construction. */\n declare readonly fetchRetrievables: () => Retrievable[] | Promise<Retrievable[]>\n /** Stores a new retrievable record in the persistence layer. */\n declare readonly storeRetrievable: (v: Retrievable) => void | Promise<void>\n /** Updates an existing retrievable record in the persistence layer. */\n declare readonly mutateRetrievable: (v: Retrievable) => void | Promise<void>\n /** Removes a retrievable record from the persistence layer by ID. */\n declare readonly deleteRetrievable: (id: string) => void | Promise<void>\n /** Stores a new message in the persistence layer. */\n declare readonly storeMessage: (v: Message) => void | Promise<void>\n /** Updates an existing message in the persistence layer. */\n declare readonly mutateMessage: (v: Message) => void | Promise<void>\n /** Removes a message from the persistence layer by ID. */\n declare readonly deleteMessage: (id: string) => void | Promise<void>\n /** Stores a new thought in the persistence layer. */\n declare readonly storeThought: (v: Thought) => void | Promise<void>\n /** Updates an existing thought in the persistence layer. */\n declare readonly mutateThought: (v: Thought) => void | Promise<void>\n /** Removes a thought from the persistence layer by ID. */\n declare readonly deleteThought: (id: string) => void | Promise<void>\n /** Stores a new tool call in the persistence layer. */\n declare readonly storeToolCall: (v: ToolCall) => void | Promise<void>\n /** Updates an existing tool call in the persistence layer. */\n declare readonly mutateToolCall: (v: ToolCall) => void | Promise<void>\n /** Removes a tool call from the persistence layer by ID. */\n declare readonly deleteToolCall: (id: string) => void | Promise<void>\n /**\n * Persists tool-generated media bytes into consumer storage and returns a {@link @nhtio/adk!MediaReader}.\n * Low-level conduit — returns a value, touches no turn state; build a {@link @nhtio/adk!Media} from the\n * reader and persist the owning primitive separately.\n */\n declare readonly storeMediaBytes: (\n id: string,\n bytes: ConduitBytes\n ) => MediaReader | Promise<MediaReader>\n /**\n * Persists extracted retrievable text bytes into consumer storage and returns a\n * {@link @nhtio/adk!SpoolReader}. Wrap it in a {@link @nhtio/adk!SpooledArtifact} for `Retrievable.content`\n * and persist the record via {@link TurnContext.storeRetrievable} separately.\n */\n declare readonly storeRetrievableBytes: (\n id: string,\n bytes: ConduitBytes\n ) => SpoolReader | Promise<SpoolReader>\n /** Emits a `message` event on the runner; may be called at any point during the turn. */\n declare readonly emitMessage: EmitMessageFn\n /** Emits a `thought` event on the runner; may be called at any point during the turn. */\n declare readonly emitThought: EmitThoughtFn\n /** Emits a `toolCall` event on the runner; may be called at any point during the turn. */\n declare readonly emitToolCall: EmitToolCallFn\n /** Emits a `toolExecutionStart` event on the observability bus; forwarded from `DispatchContext` by `DispatchRunner` when a tool is invoked inside a dispatch. */\n declare readonly emitToolExecutionStart: EmitToolExecutionStartFn\n /** Emits a `toolExecutionEnd` event on the observability bus; forwarded from `DispatchContext` by `DispatchRunner` when a tool finishes executing inside a dispatch. */\n declare readonly emitToolExecutionEnd: EmitToolExecutionEndFn\n /** Opens a turn gate and suspends until it resolves, rejects, times out, or is aborted. */\n declare readonly waitFor: OpenGateFn\n /** Turn-scoped tool registry constructed from the runner's baseline tools; middleware may trim or extend it. */\n declare readonly tools: ToolRegistry\n}\n","import { v6 as uuidv6 } from 'uuid'\nimport { Hooks } from '@nhtio/hooks'\nimport { validator } from '@nhtio/validation'\nimport { Registry } from '../classes/registry'\nimport { Tokenizable } from '../classes/tokenizable'\nimport { validateOrThrow } from '../utils/validation'\nimport { isInstanceOf, isError } from '../utils/guards'\nimport { ToolRegistry } from '../classes/tool_registry'\nimport {\n E_INVALID_LLM_EXECUTION_CONTEXT,\n E_LLM_EXECUTION_GATE_NOT_SUPPORTED,\n E_LLM_EXECUTION_ALREADY_SIGNALLED,\n} from '../exceptions/runtime'\nimport type { Tool } from '../classes/tool'\nimport type { Memory } from '../classes/memory'\nimport type { Message } from '../classes/message'\nimport type { Thought } from '../classes/thought'\nimport type { SpoolReader } from './spool_reader'\nimport type { MediaReader } from './media_reader'\nimport type { ToolCall } from '../classes/tool_call'\nimport type { Retrievable } from '../classes/retrievable'\nimport type {\n DispatchContextHooks,\n DispatchContextHookRegistrations,\n} from '../types/dispatch_context'\nimport type {\n EmitMessageFn,\n EmitThoughtFn,\n EmitToolCallFn,\n EmitToolExecutionStartFn,\n EmitToolExecutionEndFn,\n OpenGateFn,\n} from '../types/turn_runner'\n\n/** Payload accepted by the byte-persistence conduits — text, raw bytes, or a stream. */\nexport type ConduitBytes = string | Uint8Array | ReadableStream<Uint8Array>\n\n// ── LLM-scoped callback fn types ─────────────────────────────────────────────\n\n/** Retrieves memories for an LLM execution context. */\nexport type DispatchMemoryRetrievalFn = (ctx: DispatchContext) => Memory[] | Promise<Memory[]>\n\n/** Retrieves messages for an LLM execution context. */\nexport type DispatchMessageRetrievalFn = (ctx: DispatchContext) => Message[] | Promise<Message[]>\n\n/** Retrieves thoughts for an LLM execution context. */\nexport type DispatchThoughtRetrievalFn = (ctx: DispatchContext) => Thought[] | Promise<Thought[]>\n\n/** Retrieves tool calls for an LLM execution context. */\nexport type DispatchToolCallRetrievalFn = (ctx: DispatchContext) => ToolCall[] | Promise<ToolCall[]>\n\n/** Retrieves tools for an LLM execution context. */\nexport type DispatchToolsRetrievalFn = (ctx: DispatchContext) => Tool[] | Promise<Tool[]>\n\n/** Refreshes and returns standing instructions for an LLM execution context. */\nexport type DispatchStandingInstructionsRefreshFn = (\n ctx: DispatchContext\n) => (string | Tokenizable)[] | Promise<(string | Tokenizable)[]>\n\n/** Stores a new standing instruction (LLM execution context variant). */\nexport type DispatchStandingInstructionStoreFn = (\n ctx: DispatchContext,\n v: string | Tokenizable\n) => void | Promise<void>\n\n/** Updates an existing standing instruction (LLM execution context variant). */\nexport type DispatchStandingInstructionMutateFn = (\n ctx: DispatchContext,\n v: string | Tokenizable\n) => void | Promise<void>\n\n/** Removes a standing instruction (LLM execution context variant). */\nexport type DispatchStandingInstructionDeleteFn = (\n ctx: DispatchContext,\n v: string | Tokenizable\n) => void | Promise<void>\n\n/** Stores a new memory (LLM execution context variant). */\nexport type DispatchMemoryStoreFn = (ctx: DispatchContext, v: Memory) => void | Promise<void>\n\n/** Updates an existing memory (LLM execution context variant). */\nexport type DispatchMemoryMutateFn = (ctx: DispatchContext, v: Memory) => void | Promise<void>\n\n/** Removes a memory by ID (LLM execution context variant). */\nexport type DispatchMemoryDeleteFn = (ctx: DispatchContext, id: string) => void | Promise<void>\n\n/** Retrieves retrievable records for an LLM execution context. */\nexport type DispatchRetrievableRetrievalFn = (\n ctx: DispatchContext\n) => Retrievable[] | Promise<Retrievable[]>\n\n/** Stores a new retrievable record (LLM execution context variant). */\nexport type DispatchRetrievableStoreFn = (\n ctx: DispatchContext,\n v: Retrievable\n) => void | Promise<void>\n\n/** Updates an existing retrievable record (LLM execution context variant). */\nexport type DispatchRetrievableMutateFn = (\n ctx: DispatchContext,\n v: Retrievable\n) => void | Promise<void>\n\n/** Removes a retrievable record by ID (LLM execution context variant). */\nexport type DispatchRetrievableDeleteFn = (ctx: DispatchContext, id: string) => void | Promise<void>\n\n/** Stores a new message (LLM execution context variant). */\nexport type DispatchMessageStoreFn = (ctx: DispatchContext, v: Message) => void | Promise<void>\n\n/** Updates an existing message (LLM execution context variant). */\nexport type DispatchMessageMutateFn = (ctx: DispatchContext, v: Message) => void | Promise<void>\n\n/** Removes a message by ID (LLM execution context variant). */\nexport type DispatchMessageDeleteFn = (ctx: DispatchContext, id: string) => void | Promise<void>\n\n/** Stores a new thought (LLM execution context variant). */\nexport type DispatchThoughtStoreFn = (ctx: DispatchContext, v: Thought) => void | Promise<void>\n\n/** Updates an existing thought (LLM execution context variant). */\nexport type DispatchThoughtMutateFn = (ctx: DispatchContext, v: Thought) => void | Promise<void>\n\n/** Removes a thought by ID (LLM execution context variant). */\nexport type DispatchThoughtDeleteFn = (ctx: DispatchContext, id: string) => void | Promise<void>\n\n/** Stores a new tool call (LLM execution context variant). */\nexport type DispatchToolCallStoreFn = (ctx: DispatchContext, v: ToolCall) => void | Promise<void>\n\n/** Updates an existing tool call (LLM execution context variant). */\nexport type DispatchToolCallMutateFn = (ctx: DispatchContext, v: ToolCall) => void | Promise<void>\n\n/** Removes a tool call by ID (LLM execution context variant). */\nexport type DispatchToolCallDeleteFn = (ctx: DispatchContext, id: string) => void | Promise<void>\n\n/**\n * Persists tool-generated media bytes into consumer storage and returns a {@link @nhtio/adk!MediaReader}\n * (LLM execution context variant). Unlike the `store*` mutation callbacks this returns a value and\n * does NOT add anything to the turn Sets — the handler builds a {@link @nhtio/adk!Media} from the reader\n * and persists it via `storeMessage`/`storeToolCall` separately.\n */\nexport type DispatchMediaBytesStoreFn = (\n ctx: DispatchContext,\n id: string,\n bytes: ConduitBytes\n) => MediaReader | Promise<MediaReader>\n\n/**\n * Persists extracted retrievable text bytes into consumer storage and returns a\n * {@link @nhtio/adk!SpoolReader} (LLM execution context variant). The handler wraps the reader in a\n * {@link @nhtio/adk!SpooledArtifact} for `new Retrievable({ content })` and persists the record via\n * `storeRetrievable` separately. Returns a value; does NOT touch the turn Sets.\n */\nexport type DispatchRetrievableBytesStoreFn = (\n ctx: DispatchContext,\n id: string,\n bytes: ConduitBytes\n) => SpoolReader | Promise<SpoolReader>\n\n// ── RawDispatchContext ────────────────────────────────────────────────────\n\n/**\n * Plain input object supplied to {@link DispatchContext} at construction time.\n *\n * @remarks\n * All fetch and mutation callbacks are required — every execution context must have a persistence\n * layer wired up, even in standalone mode. Optional pre-fetched arrays populate the context's Sets\n * at construction time without replacing the callbacks (the callbacks are still invoked on\n * subsequent fetch calls).\n */\nexport interface RawDispatchContext {\n /** `AbortController` whose signal can cancel execution mid-flight. */\n turnAbortController?: AbortController\n /** Arbitrary key-value store for cross-step state. */\n stash?: Record<string, unknown>\n /** The system prompt for this execution. */\n systemPrompt: string | Tokenizable\n /** Standing instructions for this execution. */\n standingInstructions?: (string | Tokenizable)[]\n\n // Pre-fetched data (optional — populates Sets at construction)\n /** Pre-fetched memories to populate the context at construction. */\n memories?: Memory[]\n /** Pre-fetched retrievable records to populate the context at construction. */\n retrievables?: Retrievable[]\n /** Pre-fetched messages to populate the context at construction. */\n messages?: Message[]\n /** Pre-fetched thoughts to populate the context at construction. */\n thoughts?: Thought[]\n /** Pre-fetched tool calls to populate the context at construction. */\n toolCalls?: ToolCall[]\n /** Pre-fetched tools to populate the tool registry at construction. */\n tools?: Tool[]\n\n // Fetch callbacks (required)\n /** Retrieves memories for this execution. */\n fetchMemories: DispatchMemoryRetrievalFn\n /** Retrieves retrievable records for this execution. */\n fetchRetrievables: DispatchRetrievableRetrievalFn\n /** Retrieves messages for this execution. */\n fetchMessages: DispatchMessageRetrievalFn\n /** Retrieves thoughts for this execution. */\n fetchThoughts: DispatchThoughtRetrievalFn\n /** Retrieves tool calls for this execution. */\n fetchToolCalls: DispatchToolCallRetrievalFn\n /** Retrieves tools for this execution. */\n fetchTools: DispatchToolsRetrievalFn\n /** Refreshes and returns standing instructions for this execution. */\n refreshStandingInstructions: DispatchStandingInstructionsRefreshFn\n\n // Mutation callbacks (required — persistence layer; called immediately on every mutation)\n /** Stores a new standing instruction. */\n storeStandingInstruction: DispatchStandingInstructionStoreFn\n /** Updates an existing standing instruction. */\n mutateStandingInstruction: DispatchStandingInstructionMutateFn\n /** Removes a standing instruction. */\n deleteStandingInstruction: DispatchStandingInstructionDeleteFn\n /** Stores a new memory. */\n storeMemory: DispatchMemoryStoreFn\n /** Updates an existing memory. */\n mutateMemory: DispatchMemoryMutateFn\n /** Removes a memory by ID. */\n deleteMemory: DispatchMemoryDeleteFn\n /** Stores a new retrievable record. */\n storeRetrievable: DispatchRetrievableStoreFn\n /** Updates an existing retrievable record. */\n mutateRetrievable: DispatchRetrievableMutateFn\n /** Removes a retrievable record by ID. */\n deleteRetrievable: DispatchRetrievableDeleteFn\n /** Stores a new message. */\n storeMessage: DispatchMessageStoreFn\n /** Updates an existing message. */\n mutateMessage: DispatchMessageMutateFn\n /** Removes a message by ID. */\n deleteMessage: DispatchMessageDeleteFn\n /** Stores a new thought. */\n storeThought: DispatchThoughtStoreFn\n /** Updates an existing thought. */\n mutateThought: DispatchThoughtMutateFn\n /** Removes a thought by ID. */\n deleteThought: DispatchThoughtDeleteFn\n /** Stores a new tool call. */\n storeToolCall: DispatchToolCallStoreFn\n /** Updates an existing tool call. */\n mutateToolCall: DispatchToolCallMutateFn\n /** Removes a tool call by ID. */\n deleteToolCall: DispatchToolCallDeleteFn\n /** Persists tool-generated media bytes; returns a `MediaReader`. */\n storeMediaBytes: DispatchMediaBytesStoreFn\n /** Persists extracted retrievable text bytes; returns a `SpoolReader`. */\n storeRetrievableBytes: DispatchRetrievableBytesStoreFn\n\n /** Optional hook registrations for emit events. */\n hooks?: DispatchContextHookRegistrations\n /** Optional gate suspension function. When absent, `waitFor` rejects with {@link @nhtio/adk!E_LLM_EXECUTION_GATE_NOT_SUPPORTED}. */\n waitFor?: OpenGateFn\n}\n\nconst rawDispatchContextSchema = validator.object<RawDispatchContext>({\n turnAbortController: validator\n .alternatives(\n validator.object().instance(AbortController as any),\n validator.function().instance(AbortController as any)\n )\n .optional(),\n stash: validator.object().pattern(validator.string(), validator.any()).default({}),\n systemPrompt: Tokenizable.schema.required(),\n standingInstructions: validator.array().items(Tokenizable.schema).default([]),\n memories: validator.array().default([]),\n retrievables: validator.array().default([]),\n messages: validator.array().default([]),\n thoughts: validator.array().default([]),\n toolCalls: validator.array().default([]),\n tools: validator.array().default([]),\n fetchMemories: validator.function().required(),\n fetchRetrievables: validator.function().required(),\n fetchMessages: validator.function().required(),\n fetchThoughts: validator.function().required(),\n fetchToolCalls: validator.function().required(),\n fetchTools: validator.function().required(),\n refreshStandingInstructions: validator.function().required(),\n storeStandingInstruction: validator.function().required(),\n mutateStandingInstruction: validator.function().required(),\n deleteStandingInstruction: validator.function().required(),\n storeMemory: validator.function().required(),\n mutateMemory: validator.function().required(),\n deleteMemory: validator.function().required(),\n storeRetrievable: validator.function().required(),\n mutateRetrievable: validator.function().required(),\n deleteRetrievable: validator.function().required(),\n storeMessage: validator.function().required(),\n mutateMessage: validator.function().required(),\n deleteMessage: validator.function().required(),\n storeThought: validator.function().required(),\n mutateThought: validator.function().required(),\n deleteThought: validator.function().required(),\n storeToolCall: validator.function().required(),\n mutateToolCall: validator.function().required(),\n deleteToolCall: validator.function().required(),\n storeMediaBytes: validator.function().required(),\n storeRetrievableBytes: validator.function().required(),\n hooks: validator.object().optional(),\n waitFor: validator.function().optional(),\n})\n\n// ── DispatchContext ───────────────────────────────────────────────────────\n\n/**\n * Context object for a single LLM execution call.\n *\n * @remarks\n * Mirrors the surface of {@link @nhtio/adk!TurnContext} but is path-agnostic — it knows nothing about a\n * parent context. Mutations apply to local Sets immediately, call persistence callbacks\n * immediately, and fire the corresponding mutation hook (`storedMemory`, `mutatedMemory`,\n * `deletedMemory`, etc.) in both standalone and derived dispatches.\n *\n * The {@link @nhtio/adk!DispatchRunner} is the only thing that creates a context with a parent\n * relationship: when dispatched with a `source: TurnContext`, the runner subscribes to the\n * mutation hooks, queues deltas internally, and flushes them to the parent's Sets at the end of\n * each iteration. The context itself remains unaware of the parent.\n *\n * Middleware/executor signals termination via {@link DispatchContext.ack} (clean completion)\n * or {@link DispatchContext.nack} (failure). Both set an internal flag the runner reads at\n * end-of-iteration to decide whether to loop or exit. {@link DispatchContext.isSignalled},\n * {@link DispatchContext.isAcked}, and {@link DispatchContext.nackError} are publicly\n * readable getters so middleware can inspect signal state and bail early.\n */\nexport class DispatchContext {\n #id: string\n #dispatchId: string\n #iteration: number\n #turnAbortController: AbortController\n #stash: Registry\n #systemPrompt: Tokenizable\n #standingInstructions: Set<Tokenizable>\n #turnMemories: Set<Memory>\n #turnRetrievables: Set<Retrievable>\n #turnMessages: Set<Message>\n #turnThoughts: Set<Thought>\n #turnToolCalls: Set<ToolCall>\n #tools: ToolRegistry\n #hooks: Hooks<DispatchContextHooks>\n #ackHandlers: Set<() => void>\n\n // Persistence callbacks\n #fetchMemories: DispatchMemoryRetrievalFn\n #fetchRetrievables: DispatchRetrievableRetrievalFn\n #fetchMessages: DispatchMessageRetrievalFn\n #fetchThoughts: DispatchThoughtRetrievalFn\n #fetchToolCalls: DispatchToolCallRetrievalFn\n #fetchTools: DispatchToolsRetrievalFn\n #refreshStandingInstructions: DispatchStandingInstructionsRefreshFn\n #storeStandingInstruction: DispatchStandingInstructionStoreFn\n #mutateStandingInstruction: DispatchStandingInstructionMutateFn\n #deleteStandingInstruction: DispatchStandingInstructionDeleteFn\n #storeMemory: DispatchMemoryStoreFn\n #mutateMemory: DispatchMemoryMutateFn\n #deleteMemory: DispatchMemoryDeleteFn\n #storeRetrievable: DispatchRetrievableStoreFn\n #mutateRetrievable: DispatchRetrievableMutateFn\n #deleteRetrievable: DispatchRetrievableDeleteFn\n #storeMessage: DispatchMessageStoreFn\n #mutateMessage: DispatchMessageMutateFn\n #deleteMessage: DispatchMessageDeleteFn\n #storeThought: DispatchThoughtStoreFn\n #mutateThought: DispatchThoughtMutateFn\n #deleteThought: DispatchThoughtDeleteFn\n #storeToolCall: DispatchToolCallStoreFn\n #mutateToolCall: DispatchToolCallMutateFn\n #deleteToolCall: DispatchToolCallDeleteFn\n #storeMediaBytes: DispatchMediaBytesStoreFn\n #storeRetrievableBytes: DispatchRetrievableBytesStoreFn\n #waitFor: OpenGateFn | undefined\n\n // Checksum frequency index for this execution\n #toolCallChecksums: Map<string, number>\n\n // Termination signal state\n #signalled: 'ack' | 'nack' | undefined\n #nackError: Error | undefined\n\n /**\n * @param raw - Raw input validated against the schema.\n * @throws {@link @nhtio/adk!E_INVALID_LLM_EXECUTION_CONTEXT} when `raw` does not satisfy the schema.\n */\n constructor(raw: RawDispatchContext) {\n let resolved: RawDispatchContext & {\n stash: Record<string, unknown>\n standingInstructions: (string | Tokenizable)[]\n memories: Memory[]\n retrievables: Retrievable[]\n messages: Message[]\n thoughts: Thought[]\n toolCalls: ToolCall[]\n tools: Tool[]\n }\n try {\n resolved = validateOrThrow(rawDispatchContextSchema, raw, true) as typeof resolved\n } catch (err) {\n throw new E_INVALID_LLM_EXECUTION_CONTEXT({ cause: isError(err) ? err : undefined })\n }\n\n this.#id = uuidv6()\n this.#dispatchId = ''\n this.#iteration = 0\n this.#turnAbortController = resolved.turnAbortController ?? new AbortController()\n this.#stash = new Registry(resolved.stash)\n this.#systemPrompt = Tokenizable.isTokenizable(resolved.systemPrompt)\n ? resolved.systemPrompt\n : new Tokenizable(resolved.systemPrompt)\n this.#standingInstructions = new Set(\n resolved.standingInstructions.map((i) =>\n Tokenizable.isTokenizable(i) ? i : new Tokenizable(i)\n )\n )\n this.#turnMemories = new Set(resolved.memories)\n this.#turnRetrievables = new Set(resolved.retrievables)\n this.#turnMessages = new Set(resolved.messages)\n this.#turnThoughts = new Set(resolved.thoughts)\n this.#turnToolCalls = new Set(resolved.toolCalls)\n this.#tools = new ToolRegistry(resolved.tools)\n this.#toolCallChecksums = new Map()\n for (const tc of resolved.toolCalls) {\n const prev = this.#toolCallChecksums.get(tc.checksum) ?? 0\n this.#toolCallChecksums.set(tc.checksum, prev + 1)\n }\n\n this.#fetchMemories = resolved.fetchMemories\n this.#fetchRetrievables = resolved.fetchRetrievables\n this.#fetchMessages = resolved.fetchMessages\n this.#fetchThoughts = resolved.fetchThoughts\n this.#fetchToolCalls = resolved.fetchToolCalls\n this.#fetchTools = resolved.fetchTools\n this.#refreshStandingInstructions = resolved.refreshStandingInstructions\n this.#storeStandingInstruction = resolved.storeStandingInstruction\n this.#mutateStandingInstruction = resolved.mutateStandingInstruction\n this.#deleteStandingInstruction = resolved.deleteStandingInstruction\n this.#storeMemory = resolved.storeMemory\n this.#mutateMemory = resolved.mutateMemory\n this.#deleteMemory = resolved.deleteMemory\n this.#storeRetrievable = resolved.storeRetrievable\n this.#mutateRetrievable = resolved.mutateRetrievable\n this.#deleteRetrievable = resolved.deleteRetrievable\n this.#storeMessage = resolved.storeMessage\n this.#mutateMessage = resolved.mutateMessage\n this.#deleteMessage = resolved.deleteMessage\n this.#storeThought = resolved.storeThought\n this.#mutateThought = resolved.mutateThought\n this.#deleteThought = resolved.deleteThought\n this.#storeToolCall = resolved.storeToolCall\n this.#mutateToolCall = resolved.mutateToolCall\n this.#deleteToolCall = resolved.deleteToolCall\n this.#storeMediaBytes = resolved.storeMediaBytes\n this.#storeRetrievableBytes = resolved.storeRetrievableBytes\n this.#waitFor = resolved.waitFor\n\n this.#signalled = undefined\n this.#nackError = undefined\n\n // Register hooks\n this.#hooks = new Hooks<DispatchContextHooks>()\n this.#ackHandlers = new Set()\n if (resolved.hooks) {\n const regs = resolved.hooks\n for (const key of Object.keys(regs) as (keyof DispatchContextHooks)[]) {\n const entry = regs[key]\n if (!entry) continue\n const handlers = Array.isArray(entry) ? entry : [entry]\n for (const h of handlers) {\n this.#hooks.add(key, h as any)\n }\n }\n }\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n dispatchId: {\n get: () => this.#dispatchId,\n enumerable: true,\n configurable: false,\n },\n iteration: {\n get: () => this.#iteration,\n enumerable: true,\n configurable: false,\n },\n aborted: {\n get: () => Boolean(this.#turnAbortController.signal.aborted),\n enumerable: true,\n configurable: false,\n },\n abortSignal: {\n get: () => this.#turnAbortController.signal,\n enumerable: true,\n configurable: false,\n },\n abort: {\n value: (reason?: unknown) => this.#turnAbortController.abort(reason),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n isSignalled: {\n get: () => this.#signalled !== undefined,\n enumerable: true,\n configurable: false,\n },\n isAcked: {\n get: () => this.#signalled === 'ack',\n enumerable: true,\n configurable: false,\n },\n nackError: {\n get: () => this.#nackError,\n enumerable: true,\n configurable: false,\n },\n stash: {\n get: () => this.#stash,\n enumerable: true,\n configurable: false,\n },\n systemPrompt: {\n get: () => this.#systemPrompt,\n enumerable: true,\n configurable: false,\n },\n standingInstructions: {\n get: () => this.#standingInstructions,\n enumerable: true,\n configurable: false,\n },\n turnMemories: {\n get: () => this.#turnMemories,\n enumerable: true,\n configurable: false,\n },\n turnRetrievables: {\n get: () => this.#turnRetrievables,\n enumerable: true,\n configurable: false,\n },\n turnMessages: {\n get: () => this.#turnMessages,\n enumerable: true,\n configurable: false,\n },\n turnThoughts: {\n get: () => this.#turnThoughts,\n enumerable: true,\n configurable: false,\n },\n turnToolCalls: {\n get: () => this.#turnToolCalls,\n enumerable: true,\n configurable: false,\n },\n tools: {\n get: () => this.#tools,\n enumerable: true,\n configurable: false,\n },\n fetchMemories: {\n value: () => this.#fetchMemories(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchRetrievables: {\n value: () => this.#fetchRetrievables(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchMessages: {\n value: () => this.#fetchMessages(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchThoughts: {\n value: () => this.#fetchThoughts(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchToolCalls: {\n value: () => this.#fetchToolCalls(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchTools: {\n value: () => this.#fetchTools(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n refreshStandingInstructions: {\n value: () => this.#refreshStandingInstructions(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeStandingInstruction: {\n value: (v: string | Tokenizable) => this.#doStoreStandingInstruction(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateStandingInstruction: {\n value: (v: string | Tokenizable) => this.#doMutateStandingInstruction(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteStandingInstruction: {\n value: (v: string | Tokenizable) => this.#doDeleteStandingInstruction(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeMemory: {\n value: (v: Memory) => this.#doStoreMemory(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateMemory: {\n value: (v: Memory) => this.#doMutateMemory(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteMemory: {\n value: (id: string) => this.#doDeleteMemory(id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeRetrievable: {\n value: (v: Retrievable) => this.#doStoreRetrievable(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateRetrievable: {\n value: (v: Retrievable) => this.#doMutateRetrievable(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteRetrievable: {\n value: (id: string) => this.#doDeleteRetrievable(id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeMessage: {\n value: (v: Message) => this.#doStoreMessage(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateMessage: {\n value: (v: Message) => this.#doMutateMessage(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteMessage: {\n value: (id: string) => this.#doDeleteMessage(id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeThought: {\n value: (v: Thought) => this.#doStoreThought(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateThought: {\n value: (v: Thought) => this.#doMutateThought(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteThought: {\n value: (id: string) => this.#doDeleteThought(id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeToolCall: {\n value: (v: ToolCall) => this.#doStoreToolCall(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateToolCall: {\n value: (v: ToolCall) => this.#doMutateToolCall(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteToolCall: {\n value: (id: string) => this.#doDeleteToolCall(id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeMediaBytes: {\n value: (id: string, bytes: ConduitBytes) => this.#storeMediaBytes(this, id, bytes),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeRetrievableBytes: {\n value: (id: string, bytes: ConduitBytes) => this.#storeRetrievableBytes(this, id, bytes),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitMessage: {\n value: (content: Parameters<EmitMessageFn>[0]) => {\n void this.#hooks.runner('message').run(content)\n },\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitThought: {\n value: (content: Parameters<EmitThoughtFn>[0]) => {\n void this.#hooks.runner('thought').run(content)\n },\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitToolCall: {\n value: (content: Parameters<EmitToolCallFn>[0]) => {\n void this.#hooks.runner('toolCall').run(content)\n },\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitToolExecutionStart: {\n value: (event: Parameters<EmitToolExecutionStartFn>[0]) => {\n void this.#hooks.runner('toolExecutionStart').run(event)\n },\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitToolExecutionEnd: {\n value: (event: Parameters<EmitToolExecutionEndFn>[0]) => {\n void this.#hooks.runner('toolExecutionEnd').run(event)\n },\n enumerable: true,\n configurable: false,\n writable: false,\n },\n waitFor: {\n value: <T>(gateRaw: Parameters<OpenGateFn>[0]): Promise<T> => {\n if (!this.#waitFor) {\n return Promise.reject(new E_LLM_EXECUTION_GATE_NOT_SUPPORTED())\n }\n return this.#waitFor<T>(gateRaw)\n },\n enumerable: true,\n configurable: false,\n writable: false,\n },\n })\n }\n\n // ── Mutation helpers ──────────────────────────────────────────────────────\n\n async #doStoreStandingInstruction(v: string | Tokenizable): Promise<void> {\n const t = Tokenizable.isTokenizable(v) ? v : new Tokenizable(v)\n this.#standingInstructions.add(t)\n await this.#storeStandingInstruction(this, v)\n void this.#hooks.runner('storedStandingInstruction').run(t)\n }\n\n async #doMutateStandingInstruction(v: string | Tokenizable): Promise<void> {\n const t = Tokenizable.isTokenizable(v) ? v : new Tokenizable(v)\n this.#standingInstructions.add(t)\n await this.#mutateStandingInstruction(this, v)\n void this.#hooks.runner('mutatedStandingInstruction').run(t)\n }\n\n async #doDeleteStandingInstruction(v: string | Tokenizable): Promise<void> {\n const t = Tokenizable.isTokenizable(v) ? v : new Tokenizable(v)\n this.#standingInstructions.delete(t)\n await this.#deleteStandingInstruction(this, v)\n void this.#hooks.runner('deletedStandingInstruction').run(t)\n }\n\n async #doStoreMemory(v: Memory): Promise<void> {\n this.#turnMemories.add(v)\n await this.#storeMemory(this, v)\n void this.#hooks.runner('storedMemory').run(v)\n }\n\n async #doMutateMemory(v: Memory): Promise<void> {\n this.#turnMemories.add(v)\n await this.#mutateMemory(this, v)\n void this.#hooks.runner('mutatedMemory').run(v)\n }\n\n async #doDeleteMemory(id: string): Promise<void> {\n for (const m of this.#turnMemories) {\n if ((m as any).id === id) {\n this.#turnMemories.delete(m)\n break\n }\n }\n await this.#deleteMemory(this, id)\n void this.#hooks.runner('deletedMemory').run(id)\n }\n\n async #doStoreRetrievable(v: Retrievable): Promise<void> {\n this.#turnRetrievables.add(v)\n await this.#storeRetrievable(this, v)\n void this.#hooks.runner('storedRetrievable').run(v)\n }\n\n async #doMutateRetrievable(v: Retrievable): Promise<void> {\n this.#turnRetrievables.add(v)\n await this.#mutateRetrievable(this, v)\n void this.#hooks.runner('mutatedRetrievable').run(v)\n }\n\n async #doDeleteRetrievable(id: string): Promise<void> {\n for (const r of this.#turnRetrievables) {\n if ((r as any).id === id) {\n this.#turnRetrievables.delete(r)\n break\n }\n }\n await this.#deleteRetrievable(this, id)\n void this.#hooks.runner('deletedRetrievable').run(id)\n }\n\n async #doStoreMessage(v: Message): Promise<void> {\n this.#turnMessages.add(v)\n await this.#storeMessage(this, v)\n void this.#hooks.runner('storedMessage').run(v)\n }\n\n async #doMutateMessage(v: Message): Promise<void> {\n this.#turnMessages.add(v)\n await this.#mutateMessage(this, v)\n void this.#hooks.runner('mutatedMessage').run(v)\n }\n\n async #doDeleteMessage(id: string): Promise<void> {\n for (const m of this.#turnMessages) {\n if ((m as any).id === id) {\n this.#turnMessages.delete(m)\n break\n }\n }\n await this.#deleteMessage(this, id)\n void this.#hooks.runner('deletedMessage').run(id)\n }\n\n async #doStoreThought(v: Thought): Promise<void> {\n this.#turnThoughts.add(v)\n await this.#storeThought(this, v)\n void this.#hooks.runner('storedThought').run(v)\n }\n\n async #doMutateThought(v: Thought): Promise<void> {\n this.#turnThoughts.add(v)\n await this.#mutateThought(this, v)\n void this.#hooks.runner('mutatedThought').run(v)\n }\n\n async #doDeleteThought(id: string): Promise<void> {\n for (const t of this.#turnThoughts) {\n if ((t as any).id === id) {\n this.#turnThoughts.delete(t)\n break\n }\n }\n await this.#deleteThought(this, id)\n void this.#hooks.runner('deletedThought').run(id)\n }\n\n async #doStoreToolCall(v: ToolCall): Promise<void> {\n this.#turnToolCalls.add(v)\n const prev = this.#toolCallChecksums.get(v.checksum) ?? 0\n this.#toolCallChecksums.set(v.checksum, prev + 1)\n await this.#storeToolCall(this, v)\n void this.#hooks.runner('storedToolCall').run(v)\n }\n\n async #doMutateToolCall(v: ToolCall): Promise<void> {\n // Checksum is over tool+args, which do not change on mutation — checksum map is unchanged.\n this.#turnToolCalls.add(v)\n await this.#mutateToolCall(this, v)\n void this.#hooks.runner('mutatedToolCall').run(v)\n }\n\n async #doDeleteToolCall(id: string): Promise<void> {\n for (const tc of this.#turnToolCalls) {\n if ((tc as any).id === id) {\n this.#turnToolCalls.delete(tc)\n const count = this.#toolCallChecksums.get(tc.checksum) ?? 1\n if (count <= 1) this.#toolCallChecksums.delete(tc.checksum)\n else this.#toolCallChecksums.set(tc.checksum, count - 1)\n break\n }\n }\n await this.#deleteToolCall(this, id)\n void this.#hooks.runner('deletedToolCall').run(id)\n }\n\n // ── Internal setters (used by DispatchRunner) ─────────────────────────\n\n /** @internal Set by {@link @nhtio/adk!DispatchRunner} after construction. */\n _setDispatchId(id: string): void {\n this.#dispatchId = id\n }\n\n /** @internal Updated by {@link @nhtio/adk!DispatchRunner} on each iteration. */\n _setIteration(n: number): void {\n this.#iteration = n\n }\n\n /** @internal Accessor used by {@link @nhtio/adk!DispatchRunner} to register forwarding handlers. */\n _getHooks(): Hooks<DispatchContextHooks> {\n return this.#hooks\n }\n\n // ── Public API ────────────────────────────────────────────────────────────\n\n /**\n * Returns how many times a tool call with the given checksum has been stored in this execution.\n *\n * @remarks\n * Checksums are computed over `tool + args` (see {@link @nhtio/adk!ToolCall.checksum}). This count lets\n * the executor detect repeat invocations of the same call without scanning the full Set.\n * Returns `0` when the checksum has not been seen.\n *\n * @param checksum - The `ToolCall.checksum` value to look up.\n */\n toolCallCount(checksum: string): number {\n return this.#toolCallChecksums.get(checksum) ?? 0\n }\n\n /**\n * Signals successful completion of this execution.\n *\n * @remarks\n * Sets the context's internal signal flag. The {@link @nhtio/adk!DispatchRunner} reads the flag at the\n * end of each iteration to decide whether to loop or exit. Calling `ack()` does NOT abort the\n * current iteration — the current pipeline and flush complete first.\n *\n * @throws {@link @nhtio/adk!E_LLM_EXECUTION_ALREADY_SIGNALLED} when the context has already been signalled\n * (whether via `ack()` or `nack()`).\n */\n ack(): void {\n if (this.#signalled !== undefined) {\n throw new E_LLM_EXECUTION_ALREADY_SIGNALLED()\n }\n this.#signalled = 'ack'\n // Sync iteration — handlers must observe each other's side-effects in registration order\n // (e.g. ToolRegistry.bindContext relies on this for ephemeral pruning). The hook bus is\n // unsuitable here because its `await` between handlers reorders sync side-effects via\n // microtask queuing.\n for (const handler of this.#ackHandlers) {\n try {\n handler()\n } catch {\n // Swallow individual handler errors so one misbehaving subscriber can't prevent the\n // others from running. Ack itself has already succeeded.\n }\n }\n }\n\n /**\n * Registers a handler to run when this context completes successfully via {@link ack}.\n *\n * @remarks\n * The handler does NOT fire on {@link nack} — failed executor runs should leave any\n * ack-tied subscriptions alone so the consumer can inspect what was registered when\n * debugging the failure. Returns an unsubscribe function; subscriptions are short-lived\n * and die with the context regardless.\n *\n * The canonical consumer is `ToolRegistry.bindContext(ctx)`, which uses this hook to drop\n * ephemeral tools (notably forged artifact-query tools from `SpooledArtifact.forgeTools(ctx)`)\n * at ctx-completion. Consumers may also register custom handlers here for any per-executor\n * cleanup.\n *\n * @param handler - Callback invoked when `ack()` is called.\n * @returns An unsubscribe function that removes the handler.\n *\n * @see {@link @nhtio/adk!ToolRegistry.bindContext}\n * @see {@link @nhtio/adk!SpooledArtifact.forgeTools}\n */\n onAck(handler: () => void): () => void {\n this.#ackHandlers.add(handler)\n return () => {\n this.#ackHandlers.delete(handler)\n }\n }\n\n /**\n * Signals failed completion of this execution, optionally with an error.\n *\n * @remarks\n * Sets the context's internal signal flag and stores the error. The {@link @nhtio/adk!DispatchRunner}\n * reads the flag at the end of each iteration and surfaces the error via the `dispatchEnd`\n * observability payload and as the rejection reason of `dispatch()`. Calling `nack()` does NOT\n * abort the current iteration — the current pipeline and flush complete first.\n *\n * @param error - Optional error describing the failure. If omitted, a generic Error is used.\n * @throws {@link @nhtio/adk!E_LLM_EXECUTION_ALREADY_SIGNALLED} when the context has already been signalled.\n */\n nack(error?: Error): void {\n if (this.#signalled !== undefined) {\n throw new E_LLM_EXECUTION_ALREADY_SIGNALLED()\n }\n this.#signalled = 'nack'\n this.#nackError = error ?? new Error('LLM execution was nacked without an explicit error.')\n }\n\n /**\n * Returns `true` if `value` is a {@link DispatchContext} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety. The ADK does not export the\n * `DispatchContext` class itself as a constructable value — use this guard plus the\n * {@link DispatchContext} type for runtime detection and TypeScript narrowing.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link DispatchContext} instance.\n */\n public static isDispatchContext(value: unknown): value is DispatchContext {\n return isInstanceOf(value, 'DispatchContext', DispatchContext)\n }\n\n // ── declare readonly (TypeScript public surface) ──────────────────────────\n\n /** Unique identifier for this execution context, generated as UUIDv6 at construction time. */\n declare readonly id: string\n /** Stable identifier for the dispatch this context belongs to; set by `DispatchRunner`. */\n declare readonly dispatchId: string\n /** 0-based iteration count within the current dispatch; updated by `DispatchRunner`. */\n declare readonly iteration: number\n /** `true` when the abort controller signal has fired. */\n declare readonly aborted: boolean\n /** The `AbortSignal` from the execution's `AbortController`. */\n declare readonly abortSignal: AbortSignal\n /**\n * Aborts the dispatch's `AbortController` with the supplied reason. Middleware should call this\n * when refusing to proceed — the runner short-circuits cleanly, `dispatchEnd.status` resolves\n * to `'aborted'`, and no `error` event is emitted.\n */\n declare readonly abort: (reason?: unknown) => void\n /** `true` once {@link DispatchContext.ack} or {@link DispatchContext.nack} has been called. */\n declare readonly isSignalled: boolean\n /** `true` when the context was signalled via {@link DispatchContext.ack}. */\n declare readonly isAcked: boolean\n /** The error stored by {@link DispatchContext.nack}, or `undefined` if not nacked. */\n declare readonly nackError: Error | undefined\n /** Arbitrary key-value store for cross-step state. */\n declare readonly stash: Registry\n /** The system prompt for this execution. */\n declare readonly systemPrompt: Tokenizable\n /** Standing instructions for this execution, in insertion order. */\n declare readonly standingInstructions: Set<Tokenizable>\n /** Memories loaded for this execution. */\n declare readonly turnMemories: Set<Memory>\n /** Retrievable records loaded for this execution. */\n declare readonly turnRetrievables: Set<Retrievable>\n /** Messages loaded for this execution. */\n declare readonly turnMessages: Set<Message>\n /** Thoughts loaded for this execution. */\n declare readonly turnThoughts: Set<Thought>\n /** Tool calls loaded for this execution. */\n declare readonly turnToolCalls: Set<ToolCall>\n /** Tool registry for this execution. */\n declare readonly tools: ToolRegistry\n /** Fetches memories; delegates to the callback supplied at construction. */\n declare readonly fetchMemories: () => Memory[] | Promise<Memory[]>\n /** Fetches retrievable records; delegates to the callback supplied at construction. */\n declare readonly fetchRetrievables: () => Retrievable[] | Promise<Retrievable[]>\n /** Fetches messages; delegates to the callback supplied at construction. */\n declare readonly fetchMessages: () => Message[] | Promise<Message[]>\n /** Fetches thoughts; delegates to the callback supplied at construction. */\n declare readonly fetchThoughts: () => Thought[] | Promise<Thought[]>\n /** Fetches tool calls; delegates to the callback supplied at construction. */\n declare readonly fetchToolCalls: () => ToolCall[] | Promise<ToolCall[]>\n /** Fetches tools; delegates to the callback supplied at construction. */\n declare readonly fetchTools: () => Tool[] | Promise<Tool[]>\n /** Refreshes and returns standing instructions. */\n declare readonly refreshStandingInstructions: () =>\n | (string | Tokenizable)[]\n | Promise<(string | Tokenizable)[]>\n /** Stores a new standing instruction in the local Set and persistence layer. */\n declare readonly storeStandingInstruction: (v: string | Tokenizable) => Promise<void>\n /** Updates an existing standing instruction in the local Set and persistence layer. */\n declare readonly mutateStandingInstruction: (v: string | Tokenizable) => Promise<void>\n /** Removes a standing instruction from the local Set and persistence layer. */\n declare readonly deleteStandingInstruction: (v: string | Tokenizable) => Promise<void>\n /** Stores a new memory in the local Set and persistence layer. */\n declare readonly storeMemory: (v: Memory) => Promise<void>\n /** Updates an existing memory in the local Set and persistence layer. */\n declare readonly mutateMemory: (v: Memory) => Promise<void>\n /** Removes a memory from the local Set and persistence layer by ID. */\n declare readonly deleteMemory: (id: string) => Promise<void>\n /** Stores a new retrievable record in the local Set and persistence layer. */\n declare readonly storeRetrievable: (v: Retrievable) => Promise<void>\n /** Updates an existing retrievable record in the local Set and persistence layer. */\n declare readonly mutateRetrievable: (v: Retrievable) => Promise<void>\n /** Removes a retrievable record from the local Set and persistence layer by ID. */\n declare readonly deleteRetrievable: (id: string) => Promise<void>\n /** Stores a new message in the local Set and persistence layer. */\n declare readonly storeMessage: (v: Message) => Promise<void>\n /** Updates an existing message in the local Set and persistence layer. */\n declare readonly mutateMessage: (v: Message) => Promise<void>\n /** Removes a message from the local Set and persistence layer by ID. */\n declare readonly deleteMessage: (id: string) => Promise<void>\n /** Stores a new thought in the local Set and persistence layer. */\n declare readonly storeThought: (v: Thought) => Promise<void>\n /** Updates an existing thought in the local Set and persistence layer. */\n declare readonly mutateThought: (v: Thought) => Promise<void>\n /** Removes a thought from the local Set and persistence layer by ID. */\n declare readonly deleteThought: (id: string) => Promise<void>\n /** Stores a new tool call in the local Set and persistence layer. */\n declare readonly storeToolCall: (v: ToolCall) => Promise<void>\n /** Updates an existing tool call in the local Set and persistence layer. */\n declare readonly mutateToolCall: (v: ToolCall) => Promise<void>\n /** Removes a tool call from the local Set and persistence layer by ID. */\n declare readonly deleteToolCall: (id: string) => Promise<void>\n /**\n * Persists tool-generated media bytes into consumer storage and returns a {@link @nhtio/adk!MediaReader}.\n *\n * @remarks\n * This is a low-level persistence conduit, NOT a mutation: it does not add to `turnMessages`/\n * `turnToolCalls` or fire a `stored*` hook. The handler builds a {@link @nhtio/adk!Media} from the\n * returned reader (`Media.toolGenerated({ reader })`) and stores the owning primitive — a\n * {@link @nhtio/adk!Message} attachment or {@link @nhtio/adk!ToolCall} result — via the relevant\n * `store*` method separately. Persisting bytes without storing the primitive means the framework\n * never sees the media.\n */\n declare readonly storeMediaBytes: (\n id: string,\n bytes: ConduitBytes\n ) => MediaReader | Promise<MediaReader>\n /**\n * Persists extracted retrievable text bytes into consumer storage and returns a\n * {@link @nhtio/adk!SpoolReader}.\n *\n * @remarks\n * Low-level persistence conduit, same posture as {@link DispatchContext.storeMediaBytes}: returns a\n * value, touches no Sets, fires no hook. Wrap the reader in a {@link @nhtio/adk!SpooledArtifact} and\n * pass it as `Retrievable.content`, then persist the record via {@link DispatchContext.storeRetrievable}.\n */\n declare readonly storeRetrievableBytes: (\n id: string,\n bytes: ConduitBytes\n ) => SpoolReader | Promise<SpoolReader>\n /** Emits a `message` hook; fires registered handlers synchronously. */\n declare readonly emitMessage: EmitMessageFn\n /** Emits a `thought` hook; fires registered handlers synchronously. */\n declare readonly emitThought: EmitThoughtFn\n /** Emits a `toolCall` hook; fires registered handlers synchronously. */\n declare readonly emitToolCall: EmitToolCallFn\n /** Emits a `toolExecutionStart` hook; fires registered handlers synchronously. */\n declare readonly emitToolExecutionStart: EmitToolExecutionStartFn\n /** Emits a `toolExecutionEnd` hook; fires registered handlers synchronously. */\n declare readonly emitToolExecutionEnd: EmitToolExecutionEndFn\n /** Opens a gate and suspends until it resolves, rejects, times out, or is aborted. */\n declare readonly waitFor: OpenGateFn\n}\n","import { DateTime } from 'luxon'\nimport { sha256 } from 'js-sha256'\nimport { v6 as uuidv6 } from 'uuid'\nimport { Hooks } from '@nhtio/hooks'\nimport { validator } from '@nhtio/validation'\nimport { Middleware } from '@nhtio/middleware'\nimport { validateOrThrow } from './utils/validation'\nimport { isError, isInstanceOf } from './utils/guards'\nimport { canonicalStringify } from './utils/canonical_json'\nimport { TurnContext } from './contracts/turn_runner_context'\nimport { DispatchContext } from './contracts/dispatch_context'\nimport {\n E_INVALID_LLM_DISPATCH_INPUT,\n E_DISPATCH_PIPELINE_ERROR,\n E_LLM_EXECUTION_EXECUTOR_ERROR,\n E_PIPELINE_SHORT_CIRCUITED,\n} from './exceptions/runtime'\nimport type { Memory } from './classes/memory'\nimport type { Message } from './classes/message'\nimport type { Thought } from './classes/thought'\nimport type { ToolCall } from './classes/tool_call'\nimport type { Retrievable } from './classes/retrievable'\nimport type { Tokenizable } from './classes/tokenizable'\nimport type { BaseException } from './classes/base_exception'\nimport type { Runner as MiddlewareRunner } from '@nhtio/middleware'\nimport type { RawDispatchContext } from './contracts/dispatch_context'\nimport type { TurnStreamableContent, TurnToolCallContent } from './types/turn_runner'\nimport type {\n DispatchPipelineMiddlewareFn,\n DispatchExecutorFn,\n DispatchExecutorHelpers,\n DispatchExecutorLogChannel,\n DispatchExecutorLogEntry,\n DispatchExecutorLogLevel,\n LogEvent,\n ContextDelta,\n DispatchRunnerFunctionalHooks,\n DispatchRunnerObservabilityHooks,\n DispatchRunnerFunctionalHookRegistrations,\n DispatchRunnerObservabilityHookRegistrations,\n} from './types/dispatch_runner'\n\n/**\n * Plain input object supplied to {@link DispatchRunner.dispatch}.\n *\n * @remarks\n * Exactly one of `source` or `raw` is required:\n *\n * - `source` — switches to the **derived path**. The runner snapshots primitives from the\n * provided {@link @nhtio/adk!TurnContext}, wires all fetch/refresh/mutation callbacks to delegate to it,\n * forwards emits back to its buses, and bubbles mutations to its Sets at the end of every\n * iteration.\n *\n * - `raw` — switches to the **standalone path**. The runner constructs an {@link @nhtio/adk!DispatchContext}\n * directly from the provided raw input. No parent relationship exists; mutations are not bubbled.\n *\n * The `executor` is the user-provided callback that performs the actual LLM API call between the\n * input and output middleware pipelines on every iteration.\n */\nexport interface RawDispatchRunnerInput {\n /** Source {@link @nhtio/adk!TurnContext} to derive the execution context from. Mutually exclusive with `raw`. */\n source?: TurnContext\n /** Raw input for a standalone {@link @nhtio/adk!DispatchContext}. Mutually exclusive with `source`. */\n raw?: Omit<RawDispatchContext, 'hooks'>\n /** User-provided callback that makes the LLM API call. Invoked between input and output pipelines on every iteration. */\n executor: DispatchExecutorFn\n /** Input middleware functions, executed in order before the executor on every iteration. */\n turnInputPipeline?: DispatchPipelineMiddlewareFn[]\n /** Output middleware functions, executed in order after the executor on every iteration. */\n turnOutputPipeline?: DispatchPipelineMiddlewareFn[]\n /** Optional functional hook registrations: message, thought, toolCall. */\n hooks?: DispatchRunnerFunctionalHookRegistrations\n /** Optional observability hook registrations: lifecycle events + tool execution + error. */\n observers?: DispatchRunnerObservabilityHookRegistrations\n}\n\nconst dispatchInputSchema = validator.object<RawDispatchRunnerInput>({\n source: validator\n .any()\n .custom((value, helpers) => {\n if (value === undefined) return value\n if (isInstanceOf(value, 'TurnContext', TurnContext)) return value\n return helpers.error('any.invalid')\n })\n .optional(),\n raw: validator.object().unknown(true).optional(),\n executor: validator.function().required(),\n turnInputPipeline: validator.array().items(validator.function()).default([]),\n turnOutputPipeline: validator.array().items(validator.function()).default([]),\n hooks: validator.object().optional(),\n observers: validator.object().optional(),\n})\n\n/**\n * Orchestrates a single LLM execution dispatch — input pipeline → executor → output pipeline —\n * looped until middleware/executor signals completion via {@link @nhtio/adk!DispatchContext.ack} /\n * {@link @nhtio/adk!DispatchContext.nack} or the abort signal fires.\n *\n * @remarks\n * `DispatchRunner` has a private constructor and is invoked via the static `dispatch()`\n * method. Each dispatch creates a fresh single-use runner that is garbage-collected after the\n * call completes — matching the `@nhtio/hooks` GC rationale already baked into the context.\n *\n * The runner owns the relationship between an {@link @nhtio/adk!DispatchContext} and its parent\n * {@link @nhtio/adk!TurnContext} (when given a source). It subscribes to the context's mutation hooks,\n * queues `ContextDelta` entries, and flushes them to the parent's Sets at the end of every\n * iteration. Emits propagate from the context's hooks → the runner's hooks → (optionally) the\n * parent `TurnContext`'s emit methods → the `TurnRunner`'s buses.\n *\n * Two hook buses, mirroring `TurnRunner`'s pattern:\n *\n * - **Functional** (`hooks`): `message`, `thought`, `toolCall` — pipeline-affecting events\n * - **Observability** (`observers`): `iterationStart`, `iterationEnd`, `dispatchStart`,\n * `dispatchEnd`, `error`, `toolExecutionStart`, `toolExecutionEnd` — instrumentation only\n *\n * The runner has no `maxIterations`, no `maxToolCallChecksumRepeats`. Implementers use the\n * primitives — `ctx.iteration`, `ctx.toolCallCount(checksum)`, `ctx.ack()`, `ctx.nack()`,\n * `ctx.abortSignal` — to build any termination bounds they need in their own middleware.\n */\n/**\n * Module-private token gating direct construction of {@link DispatchRunner}. Callers must use\n * {@link DispatchRunner.dispatch}; the symbol is not exported, so external code cannot satisfy\n * the guard at runtime.\n */\nconst CONSTRUCT_TOKEN = Symbol('DispatchRunner.construct')\n\nexport class DispatchRunner {\n #functionalHooks: Hooks<DispatchRunnerFunctionalHooks>\n #observabilityHooks: Hooks<DispatchRunnerObservabilityHooks>\n // The Middleware holders are built once; a FRESH Runner is derived from each\n // per dispatch iteration. A Runner is single-use — its internal cursor\n // (#currentIndex) is never reset by run() — so reusing one Runner across\n // iterations silently no-ops every pipeline after the first. The dispatch loop\n // runs the input/output pipelines once PER iteration, so it must mint a new\n // Runner each time or the citation/quality gate (and all output middleware)\n // would only ever fire on iteration 0.\n #inputPipeline: Middleware<DispatchPipelineMiddlewareFn>\n #outputPipeline: Middleware<DispatchPipelineMiddlewareFn>\n #sourceCtx: TurnContext | undefined\n #deltaQueue: ContextDelta[]\n\n constructor(\n token: typeof CONSTRUCT_TOKEN,\n sourceCtx: TurnContext | undefined,\n turnInputPipeline: DispatchPipelineMiddlewareFn[],\n turnOutputPipeline: DispatchPipelineMiddlewareFn[],\n hooks: DispatchRunnerFunctionalHookRegistrations | undefined,\n observers: DispatchRunnerObservabilityHookRegistrations | undefined\n ) {\n if (token !== CONSTRUCT_TOKEN) {\n throw new E_INVALID_LLM_DISPATCH_INPUT()\n }\n this.#sourceCtx = sourceCtx\n this.#deltaQueue = []\n this.#functionalHooks = new Hooks<DispatchRunnerFunctionalHooks>()\n this.#observabilityHooks = new Hooks<DispatchRunnerObservabilityHooks>()\n\n const inputPipeline = new Middleware<DispatchPipelineMiddlewareFn>()\n const outputPipeline = new Middleware<DispatchPipelineMiddlewareFn>()\n const wrap =\n (fn: DispatchPipelineMiddlewareFn): DispatchPipelineMiddlewareFn =>\n (ctx, next) => {\n // Skip downstream user middlewares once an abort has been signalled. The\n // wrapper still calls next() so the pipeline reaches its terminal resolver\n // (keeping the short-circuit detector quiet); the original middleware body\n // does not run, so it has nothing to clean up.\n if (ctx.aborted) return next()\n return fn(ctx, next)\n }\n for (const fn of turnInputPipeline) inputPipeline.add(wrap(fn))\n for (const fn of turnOutputPipeline) outputPipeline.add(wrap(fn))\n // Hold the Middleware; derive a fresh Runner per iteration (see field docs).\n this.#inputPipeline = inputPipeline\n this.#outputPipeline = outputPipeline\n\n if (hooks) {\n for (const key of Object.keys(hooks) as (keyof DispatchRunnerFunctionalHooks)[]) {\n const entry = hooks[key]\n if (!entry) continue\n const handlers = Array.isArray(entry) ? entry : [entry]\n for (const h of handlers) this.#functionalHooks.add(key, h as any)\n }\n }\n if (observers) {\n for (const key of Object.keys(observers) as (keyof DispatchRunnerObservabilityHooks)[]) {\n const entry = observers[key]\n if (!entry) continue\n const handlers = Array.isArray(entry) ? entry : [entry]\n for (const h of handlers) this.#observabilityHooks.add(key, h as any)\n }\n }\n }\n\n /**\n * Returns `true` if `value` is a {@link DispatchRunner} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link DispatchRunner} instance.\n */\n public static isDispatchRunner(value: unknown): value is DispatchRunner {\n return isInstanceOf(value, 'DispatchRunner', DispatchRunner)\n }\n\n /**\n * Dispatches a single LLM execution.\n *\n * @remarks\n * Constructs an {@link @nhtio/adk!DispatchContext} (derived from `source` or from `raw`), runs the\n * iteration loop, and resolves when middleware/executor signals completion via `ctx.ack()` or\n * the abort signal fires. Rejects with the nack error when middleware/executor calls\n * `ctx.nack(err)`. Pipeline and executor errors are wrapped, surfaced on the observability\n * `error` hook, and re-thrown.\n *\n * @param input - The dispatch input. Provide either `source` (derived path) or `raw` (standalone).\n * @throws {@link @nhtio/adk!E_INVALID_LLM_DISPATCH_INPUT} when the input does not satisfy validation, or\n * when neither `source` nor `raw` is provided, or when both are provided.\n */\n public static async dispatch(input: RawDispatchRunnerInput): Promise<void> {\n let resolved: RawDispatchRunnerInput & {\n turnInputPipeline: DispatchPipelineMiddlewareFn[]\n turnOutputPipeline: DispatchPipelineMiddlewareFn[]\n }\n try {\n resolved = validateOrThrow(dispatchInputSchema, input, true) as typeof resolved\n } catch (err) {\n throw new E_INVALID_LLM_DISPATCH_INPUT({ cause: isError(err) ? err : undefined })\n }\n\n if (!resolved.source && !resolved.raw) {\n throw new E_INVALID_LLM_DISPATCH_INPUT()\n }\n if (resolved.source && resolved.raw) {\n throw new E_INVALID_LLM_DISPATCH_INPUT()\n }\n\n const runner = new DispatchRunner(\n CONSTRUCT_TOKEN,\n resolved.source,\n resolved.turnInputPipeline,\n resolved.turnOutputPipeline,\n resolved.hooks,\n resolved.observers\n )\n\n const llmCtx = runner.#buildContext(resolved.source, resolved.raw)\n runner.#wireContextHooks(llmCtx)\n\n await runner.#runDispatch(llmCtx, resolved.executor)\n }\n\n // ── Context construction ──────────────────────────────────────────────────\n\n #buildContext(\n source: TurnContext | undefined,\n raw: Omit<RawDispatchContext, 'hooks'> | undefined\n ): DispatchContext {\n if (source) {\n const ac = new AbortController()\n source.abortSignal.addEventListener('abort', () => ac.abort(), { once: true })\n\n const builtRaw: RawDispatchContext = {\n turnAbortController: ac,\n stash: source.stash.all(),\n systemPrompt: source.systemPrompt,\n standingInstructions: [...source.standingInstructions],\n memories: [...source.turnMemories],\n retrievables: [...source.turnRetrievables],\n messages: [...source.turnMessages],\n thoughts: [...source.turnThoughts],\n toolCalls: [...source.turnToolCalls],\n tools: source.tools.all(),\n fetchMemories: () => source.fetchMemories(),\n fetchRetrievables: () => source.fetchRetrievables(),\n fetchMessages: () => source.fetchMessages(),\n fetchThoughts: () => source.fetchThoughts(),\n fetchToolCalls: () => source.fetchToolCalls(),\n fetchTools: () => source.fetchTools(),\n refreshStandingInstructions: () => source.refreshStandingInstructions(),\n storeStandingInstruction: (_c, v) => source.storeStandingInstruction(v),\n mutateStandingInstruction: (_c, v) => source.mutateStandingInstruction(v),\n deleteStandingInstruction: (_c, v) => source.deleteStandingInstruction(v),\n storeMemory: (_c, v) => source.storeMemory(v),\n mutateMemory: (_c, v) => source.mutateMemory(v),\n deleteMemory: (_c, id) => source.deleteMemory(id),\n storeRetrievable: (_c, v) => source.storeRetrievable(v),\n mutateRetrievable: (_c, v) => source.mutateRetrievable(v),\n deleteRetrievable: (_c, id) => source.deleteRetrievable(id),\n storeMessage: (_c, v) => source.storeMessage(v),\n mutateMessage: (_c, v) => source.mutateMessage(v),\n deleteMessage: (_c, id) => source.deleteMessage(id),\n storeThought: (_c, v) => source.storeThought(v),\n mutateThought: (_c, v) => source.mutateThought(v),\n deleteThought: (_c, id) => source.deleteThought(id),\n storeToolCall: (_c, v) => source.storeToolCall(v),\n mutateToolCall: (_c, v) => source.mutateToolCall(v),\n deleteToolCall: (_c, id) => source.deleteToolCall(id),\n storeMediaBytes: (_c, id, bytes) => source.storeMediaBytes(id, bytes),\n storeRetrievableBytes: (_c, id, bytes) => source.storeRetrievableBytes(id, bytes),\n waitFor: source.waitFor,\n }\n return new DispatchContext(builtRaw)\n }\n\n // Standalone path — runner does not pass hooks (it registers its own forwarders below).\n return new DispatchContext(raw as RawDispatchContext)\n }\n\n // ── Wire forwarding handlers from ctx hooks to runner hooks ───────────────\n\n #wireContextHooks(llmCtx: DispatchContext): void {\n const ctxHooks = llmCtx._getHooks()\n\n // Functional forwarders: ctx → runner (functional) → (if source) → TurnContext\n ctxHooks.add('message', (c) => {\n void this.#functionalHooks.runner('message').run(c)\n if (this.#sourceCtx) this.#sourceCtx.emitMessage(c)\n })\n ctxHooks.add('thought', (c) => {\n void this.#functionalHooks.runner('thought').run(c)\n if (this.#sourceCtx) this.#sourceCtx.emitThought(c)\n })\n ctxHooks.add('toolCall', (c) => {\n void this.#functionalHooks.runner('toolCall').run(c)\n if (this.#sourceCtx) this.#sourceCtx.emitToolCall(c)\n })\n\n // Observability forwarders for tool execution lifecycle\n ctxHooks.add('toolExecutionStart', (e) => {\n void this.#observabilityHooks.runner('toolExecutionStart').run(e)\n if (this.#sourceCtx) this.#sourceCtx.emitToolExecutionStart(e)\n })\n ctxHooks.add('toolExecutionEnd', (e) => {\n void this.#observabilityHooks.runner('toolExecutionEnd').run(e)\n if (this.#sourceCtx) this.#sourceCtx.emitToolExecutionEnd(e)\n })\n\n // Mutation hooks → push to internal delta queue (only meaningful when source exists,\n // but registering unconditionally keeps the API uniform; queue is drained only in derived)\n ctxHooks.add('storedStandingInstruction', (v) => {\n this.#deltaQueue.push({ op: 'store', type: 'standingInstruction', value: v })\n })\n ctxHooks.add('mutatedStandingInstruction', (v) => {\n this.#deltaQueue.push({ op: 'mutate', type: 'standingInstruction', value: v })\n })\n ctxHooks.add('deletedStandingInstruction', (v) => {\n this.#deltaQueue.push({ op: 'delete', type: 'standingInstruction', value: v })\n })\n ctxHooks.add('storedMemory', (v) => {\n this.#deltaQueue.push({ op: 'store', type: 'memory', value: v })\n })\n ctxHooks.add('mutatedMemory', (v) => {\n this.#deltaQueue.push({ op: 'mutate', type: 'memory', value: v })\n })\n ctxHooks.add('deletedMemory', (id) => {\n this.#deltaQueue.push({ op: 'delete', type: 'memory', value: id })\n })\n ctxHooks.add('storedRetrievable', (v) => {\n this.#deltaQueue.push({ op: 'store', type: 'retrievable', value: v })\n })\n ctxHooks.add('mutatedRetrievable', (v) => {\n this.#deltaQueue.push({ op: 'mutate', type: 'retrievable', value: v })\n })\n ctxHooks.add('deletedRetrievable', (id) => {\n this.#deltaQueue.push({ op: 'delete', type: 'retrievable', value: id })\n })\n ctxHooks.add('storedMessage', (v) => {\n this.#deltaQueue.push({ op: 'store', type: 'message', value: v })\n })\n ctxHooks.add('mutatedMessage', (v) => {\n this.#deltaQueue.push({ op: 'mutate', type: 'message', value: v })\n })\n ctxHooks.add('deletedMessage', (id) => {\n this.#deltaQueue.push({ op: 'delete', type: 'message', value: id })\n })\n ctxHooks.add('storedThought', (v) => {\n this.#deltaQueue.push({ op: 'store', type: 'thought', value: v })\n })\n ctxHooks.add('mutatedThought', (v) => {\n this.#deltaQueue.push({ op: 'mutate', type: 'thought', value: v })\n })\n ctxHooks.add('deletedThought', (id) => {\n this.#deltaQueue.push({ op: 'delete', type: 'thought', value: id })\n })\n ctxHooks.add('storedToolCall', (v) => {\n this.#deltaQueue.push({ op: 'store', type: 'toolCall', value: v })\n })\n ctxHooks.add('mutatedToolCall', (v) => {\n this.#deltaQueue.push({ op: 'mutate', type: 'toolCall', value: v })\n })\n ctxHooks.add('deletedToolCall', (id) => {\n this.#deltaQueue.push({ op: 'delete', type: 'toolCall', value: id })\n })\n }\n\n // ── Helper builder ────────────────────────────────────────────────────────\n\n /**\n * Constructs an {@link @nhtio/adk!DispatchExecutorHelpers} instance bound to a single dispatch.\n *\n * @remarks\n * Per-id stream state lives on closure-captured `Map`s, so it persists across iterations of\n * the dispatch but cannot leak between dispatches (the runner itself is single-use and\n * garbage-collected after `dispatch()` returns).\n */\n #buildHelpers(ctx: DispatchContext): DispatchExecutorHelpers {\n const observabilityHooks = this.#observabilityHooks\n const makeLogEmitter =\n (level: DispatchExecutorLogLevel) =>\n (entry: DispatchExecutorLogEntry): void => {\n const event: LogEvent = {\n dispatchId: ctx.dispatchId,\n iteration: ctx.iteration,\n emittedAt: DateTime.now(),\n level,\n kind: entry.kind,\n message: entry.message,\n ...(entry.payload !== undefined ? { payload: entry.payload } : {}),\n }\n void observabilityHooks.runner('log').run(event)\n }\n const log: DispatchExecutorLogChannel = {\n trace: makeLogEmitter('trace'),\n debug: makeLogEmitter('debug'),\n info: makeLogEmitter('info'),\n warn: makeLogEmitter('warn'),\n error: makeLogEmitter('error'),\n }\n\n const messageStreams = new Map<\n string,\n { full: string; createdAt: DateTime; isComplete: boolean }\n >()\n const thoughtStreams = new Map<\n string,\n { full: string; createdAt: DateTime; isComplete: boolean }\n >()\n const toolCallStreams = new Map<\n string,\n {\n tool?: string\n args?: unknown\n checksum?: string\n results?: unknown\n isError: boolean\n isComplete: boolean\n createdAt: DateTime\n }\n >()\n\n const buildStream = (\n store: Map<string, { full: string; createdAt: DateTime; isComplete: boolean }>,\n id: string,\n deltaText: string,\n isComplete: boolean\n ): TurnStreamableContent => {\n let entry = store.get(id)\n const now = DateTime.now()\n if (!entry) {\n entry = { full: '', createdAt: now, isComplete: false }\n store.set(id, entry)\n }\n if (entry.isComplete) {\n throw new Error(`stream \"${id}\" is already complete; further chunks are not accepted`)\n }\n entry.full = entry.full + deltaText\n entry.isComplete = isComplete\n return {\n id,\n createdAt: entry.createdAt,\n updatedAt: now,\n full: entry.full,\n aDelta: deltaText,\n isComplete,\n ...(isComplete ? { completedAt: now } : {}),\n }\n }\n\n return {\n reportMessage: (id, deltaText, opts) => {\n const isComplete = opts?.isComplete ?? false\n ctx.emitMessage(buildStream(messageStreams, id, deltaText, isComplete))\n },\n reportThought: (id, deltaText, opts) => {\n const isComplete = opts?.isComplete ?? false\n ctx.emitThought(buildStream(thoughtStreams, id, deltaText, isComplete))\n },\n reportToolCall: (id, partial) => {\n let entry = toolCallStreams.get(id)\n const now = DateTime.now()\n if (!entry) {\n entry = { isError: false, isComplete: false, createdAt: now }\n toolCallStreams.set(id, entry)\n }\n if (entry.isComplete) {\n throw new Error(`tool call \"${id}\" is already complete; further updates are not accepted`)\n }\n if (partial.tool !== undefined) entry.tool = partial.tool\n if (partial.args !== undefined) entry.args = partial.args\n if (partial.results !== undefined) entry.results = partial.results\n if (partial.isError !== undefined) entry.isError = partial.isError\n if (partial.isComplete !== undefined) entry.isComplete = partial.isComplete\n\n // Compute checksum once tool + args are both set (or recompute if either changed)\n if (entry.tool !== undefined && entry.args !== undefined) {\n entry.checksum = sha256(canonicalStringify({ tool: entry.tool, args: entry.args }))\n }\n\n const content: TurnToolCallContent = {\n id,\n tool: entry.tool ?? '',\n args: entry.args,\n checksum: entry.checksum ?? '',\n createdAt: entry.createdAt,\n updatedAt: now,\n isComplete: entry.isComplete,\n isError: entry.isError,\n ...(entry.results !== undefined ? { results: entry.results } : {}),\n ...(entry.isComplete ? { completedAt: now } : {}),\n }\n ctx.emitToolCall(content)\n },\n log,\n }\n }\n\n // ── Iteration loop ────────────────────────────────────────────────────────\n\n async #runDispatch(llmCtx: DispatchContext, executor: DispatchExecutorFn): Promise<void> {\n const dispatchId = uuidv6()\n llmCtx._setDispatchId(dispatchId)\n\n const dispatchStartedAt = DateTime.now()\n void this.#observabilityHooks\n .runner('dispatchStart')\n .run({ dispatchId, startedAt: dispatchStartedAt })\n\n // Helpers are constructed once per dispatch so per-id streaming state is preserved across\n // iterations, and garbage-collected with the runner so cross-dispatch state can't leak.\n const helpers = this.#buildHelpers(llmCtx)\n\n let iteration = 0\n let dispatchError: Error | undefined\n\n try {\n while (!llmCtx.aborted && !llmCtx.isSignalled) {\n llmCtx._setIteration(iteration)\n const iterationStartedAt = DateTime.now()\n void this.#observabilityHooks\n .runner('iterationStart')\n .run({ dispatchId, iteration, startedAt: iterationStartedAt })\n\n await this.#runPipeline(this.#inputPipeline.runner(), llmCtx, 'input')\n if (llmCtx.aborted || llmCtx.isSignalled) {\n // ack mid-iteration flushes parent-mirror deltas accumulated so far;\n // nack / abort discards them so a partial iteration cannot leak\n // partial writes into the parent turn.\n if (llmCtx.isAcked && !llmCtx.aborted) {\n await this.#flush()\n } else {\n this.#deltaQueue.length = 0\n }\n break\n }\n\n try {\n await executor(llmCtx, helpers)\n } catch (err) {\n if (this.#isAbortError(err)) {\n this.#deltaQueue.length = 0\n break\n }\n const wrapped = new E_LLM_EXECUTION_EXECUTOR_ERROR({\n cause: isError(err) ? err : undefined,\n })\n void this.#observabilityHooks.runner('error').run(wrapped as unknown as BaseException)\n this.#deltaQueue.length = 0\n throw wrapped\n }\n\n if (llmCtx.aborted || llmCtx.isSignalled) {\n if (llmCtx.isAcked && !llmCtx.aborted) {\n await this.#flush()\n } else {\n this.#deltaQueue.length = 0\n }\n break\n }\n\n await this.#runPipeline(this.#outputPipeline.runner(), llmCtx, 'output')\n await this.#flush()\n\n const iterationEndedAt = DateTime.now()\n void this.#observabilityHooks.runner('iterationEnd').run({\n dispatchId,\n iteration,\n startedAt: iterationStartedAt,\n endedAt: iterationEndedAt,\n durationMs: iterationEndedAt.diff(iterationStartedAt).milliseconds,\n })\n\n iteration++\n }\n } catch (err) {\n dispatchError = isError(err) ? err : new Error(String(err))\n }\n\n const status: DispatchEndStatus = dispatchError\n ? 'nack'\n : llmCtx.nackError\n ? 'nack'\n : llmCtx.isAcked\n ? 'ack'\n : 'aborted'\n const finalError = dispatchError ?? llmCtx.nackError\n\n // Parity with the thrown-executor-error path: when the dispatch ends with\n // a nack whose cause we have not already emitted (i.e. `ctx.nack(error)`\n // was called explicitly, rather than the executor throwing), surface the\n // error on the observability `error` bus so observers see one unified\n // error stream regardless of how the nack was reached.\n if (!dispatchError && llmCtx.nackError) {\n const nackErr = llmCtx.nackError\n const wrapped = isInstanceOf(nackErr, 'BaseException')\n ? (nackErr as unknown as BaseException)\n : (new E_LLM_EXECUTION_EXECUTOR_ERROR({\n cause: isError(nackErr) ? nackErr : undefined,\n }) as unknown as BaseException)\n void this.#observabilityHooks.runner('error').run(wrapped)\n }\n\n const dispatchEndedAt = DateTime.now()\n void this.#observabilityHooks.runner('dispatchEnd').run({\n dispatchId,\n status,\n error: finalError,\n iterations: iteration,\n startedAt: dispatchStartedAt,\n endedAt: dispatchEndedAt,\n durationMs: dispatchEndedAt.diff(dispatchStartedAt).milliseconds,\n })\n\n if (finalError) throw finalError\n }\n\n async #runPipeline(\n pipeline: MiddlewareRunner<DispatchPipelineMiddlewareFn>,\n llmCtx: DispatchContext,\n label: 'input' | 'output'\n ): Promise<void> {\n let pipelineError: Error | undefined\n let reached = false\n await pipeline\n .errorHandler(async (error) => {\n if (this.#isAbortError(error)) return\n pipelineError = new E_DISPATCH_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n })\n .finalHandler(async () => {\n reached = true\n })\n .run((fn, next) => Promise.resolve(fn(llmCtx, next)))\n\n if (pipelineError) {\n void this.#observabilityHooks.runner('error').run(pipelineError as unknown as BaseException)\n throw pipelineError\n }\n\n if (!reached && !llmCtx.aborted && !llmCtx.isSignalled) {\n const shortCircuitError = new E_PIPELINE_SHORT_CIRCUITED([`dispatch-${label}`])\n void this.#observabilityHooks\n .runner('error')\n .run(shortCircuitError as unknown as BaseException)\n throw shortCircuitError\n }\n }\n\n #isAbortError(err: unknown): boolean {\n return isError(err) && isInstanceOf(err, 'AbortError')\n }\n\n async #flush(): Promise<void> {\n if (!this.#sourceCtx) {\n this.#deltaQueue.length = 0\n return\n }\n while (this.#deltaQueue.length > 0) {\n const delta = this.#deltaQueue.shift()!\n this.#applyDeltaToParent(delta)\n }\n }\n\n #applyDeltaToParent(delta: ContextDelta): void {\n const ctx = this.#sourceCtx!\n const { op, type, value } = delta\n\n if (type === 'standingInstruction') {\n const t = value as Tokenizable\n if (op === 'store' || op === 'mutate') ctx.standingInstructions.add(t)\n else ctx.standingInstructions.delete(t)\n return\n }\n if (type === 'memory') {\n if (op === 'store' || op === 'mutate') {\n ctx.turnMemories.add(value as Memory)\n } else {\n for (const m of ctx.turnMemories) {\n if ((m as any).id === (value as any)) {\n ctx.turnMemories.delete(m)\n break\n }\n }\n }\n return\n }\n if (type === 'retrievable') {\n if (op === 'store' || op === 'mutate') {\n ctx.turnRetrievables.add(value as Retrievable)\n } else {\n for (const r of ctx.turnRetrievables) {\n if ((r as any).id === (value as any)) {\n ctx.turnRetrievables.delete(r)\n break\n }\n }\n }\n return\n }\n if (type === 'message') {\n if (op === 'store' || op === 'mutate') {\n ctx.turnMessages.add(value as Message)\n } else {\n for (const m of ctx.turnMessages) {\n if ((m as any).id === (value as any)) {\n ctx.turnMessages.delete(m)\n break\n }\n }\n }\n return\n }\n if (type === 'thought') {\n if (op === 'store' || op === 'mutate') {\n ctx.turnThoughts.add(value as Thought)\n } else {\n for (const t of ctx.turnThoughts) {\n if ((t as any).id === (value as any)) {\n ctx.turnThoughts.delete(t)\n break\n }\n }\n }\n return\n }\n if (type === 'toolCall') {\n if (op === 'store' || op === 'mutate') {\n ctx.turnToolCalls.add(value as ToolCall)\n } else {\n for (const tc of ctx.turnToolCalls) {\n if ((tc as any).id === (value as any)) {\n ctx.turnToolCalls.delete(tc)\n break\n }\n }\n }\n return\n }\n }\n}\n\ntype DispatchEndStatus = 'ack' | 'nack' | 'aborted'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoEA,IAAa,oBAAoB,UAC9B,OAAuB;CACtB,qBAAqB,UAClB,aACC,UAAU,OAAO,EAAE,SAAS,eAAsB,GAClD,UAAU,SAAS,EAAE,SAAS,eAAsB,CACtD,EACC,SAAS;CACZ,OAAO,UAAU,OAAO,EAAE,QAAQ,UAAU,OAAO,GAAG,UAAU,IAAI,CAAC,EAAE,QAAQ,CAAC,CAAC;CACjF,cAAc,YAAY,OAAO,SAAS;CAC1C,sBAAsB,UAAU,MAAM,EAAE,MAAM,YA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IAAI,aAAa,IAAI,KAAe;QAEpC,KAAK,MAAM,KAAK,IAAI,cAClB,IAAK,EAAU,OAAQ,OAAe;IACpC,IAAI,aAAa,OAAO,CAAC;IACzB;GACF;GAGJ;EACF;EACA,IAAI,SAAS,eAAe;GAC1B,IAAI,OAAO,WAAW,OAAO,UAC3B,IAAI,iBAAiB,IAAI,KAAoB;QAE7C,KAAK,MAAM,KAAK,IAAI,kBAClB,IAAK,EAAU,OAAQ,OAAe;IACpC,IAAI,iBAAiB,OAAO,CAAC;IAC7B;GACF;GAGJ;EACF;EACA,IAAI,SAAS,WAAW;GACtB,IAAI,OAAO,WAAW,OAAO,UAC3B,IAAI,aAAa,IAAI,KAAgB;QAErC,KAAK,MAAM,KAAK,IAAI,cAClB,IAAK,EAAU,OAAQ,OAAe;IACpC,IAAI,aAAa,OAAO,CAAC;IACzB;GACF;GAGJ;EACF;EACA,IAAI,SAAS,WAAW;GACtB,IAAI,OAAO,WAAW,OAAO,UAC3B,IAAI,aAAa,IAAI,KAAgB;QAErC,KAAK,MAAM,KAAK,IAAI,cAClB,IAAK,EAAU,OAAQ,OAAe;IACpC,IAAI,aAAa,OAAO,CAAC;IACzB;GACF;GAGJ;EACF;EACA,IAAI,SAAS,YAAY;GACvB,IAAI,OAAO,WAAW,OAAO,UAC3B,IAAI,cAAc,IAAI,KAAiB;QAEvC,KAAK,MAAM,MAAM,IAAI,eACnB,IAAK,GAAW,OAAQ,OAAe;IACrC,IAAI,cAAc,OAAO,EAAE;IAC3B;GACF;GAGJ;EACF;CACF;AACF"}
1
+ {"version":3,"file":"dispatch_runner-CDF3X0nv.mjs","names":["#id","#turnAbortController","#stash","#systemPrompt","#standingInstructions","#turnMemories","#turnRetrievables","#turnMessages","#turnThoughts","#turnToolCalls","#id","#dispatchId","#iteration","#turnAbortController","#stash","#systemPrompt","#standingInstructions","#turnMemories","#turnRetrievables","#turnMessages","#turnThoughts","#turnToolCalls","#tools","#toolCallChecksums","#fetchMemories","#fetchRetrievables","#fetchMessages","#fetchThoughts","#fetchToolCalls","#fetchTools","#refreshStandingInstructions","#storeStandingInstruction","#mutateStandingInstruction","#deleteStandingInstruction","#storeMemory","#mutateMemory","#deleteMemory","#storeRetrievable","#mutateRetrievable","#deleteRetrievable","#storeMessage","#mutateMessage","#deleteMessage","#storeThought","#mutateThought","#deleteThought","#storeToolCall","#mutateToolCall","#deleteToolCall","#storeMediaBytes","#storeRetrievableBytes","#waitFor","#signalled","#nackError","#hooks","#ackHandlers","#doStoreStandingInstruction","#doMutateStandingInstruction","#doDeleteStandingInstruction","#doStoreMemory","#doMutateMemory","#doDeleteMemory","#doStoreRetrievable","#doMutateRetrievable","#doDeleteRetrievable","#doStoreMessage","#doMutateMessage","#doDeleteMessage","#doStoreThought","#doMutateThought","#doDeleteThought","#doStoreToolCall","#doMutateToolCall","#doDeleteToolCall","#sourceCtx","#deltaQueue","#functionalHooks","#observabilityHooks","#inputPipeline","#outputPipeline","#buildContext","#wireContextHooks","#runDispatch","#buildHelpers","#runPipeline","#flush","#isAbortError","#applyDeltaToParent"],"sources":["../src/lib/contracts/turn_runner_context.ts","../src/lib/contracts/dispatch_context.ts","../src/lib/dispatch_runner.ts"],"sourcesContent":["import { v6 as uuidv6 } from 'uuid'\nimport { validator } from '@nhtio/validation'\nimport { Registry } from '../classes/registry'\nimport { Tokenizable } from '../classes/tokenizable'\nimport { validateOrThrow } from '../utils/validation'\nimport { isInstanceOf, isError } from '../utils/guards'\nimport { E_INVALID_TURN_CONTEXT } from '../exceptions/runtime'\nimport type { Tool } from '../classes/tool'\nimport type { Memory } from '../classes/memory'\nimport type { Message } from '../classes/message'\nimport type { Thought } from '../classes/thought'\nimport type { SpoolReader } from './spool_reader'\nimport type { MediaReader } from './media_reader'\nimport type { ToolCall } from '../classes/tool_call'\nimport type { ConduitBytes } from './dispatch_context'\nimport type { Retrievable } from '../classes/retrievable'\nimport type { ToolRegistry } from '../classes/tool_registry'\nimport type {\n EmitMessageFn,\n EmitThoughtFn,\n EmitToolCallFn,\n EmitToolExecutionEndFn,\n EmitToolExecutionStartFn,\n OpenGateFn,\n} from '../types/turn_runner'\n\n/**\n * Plain input object supplied to {@link TurnContext} at construction time.\n *\n * @remarks\n * Validated against `turnContextSchema` before the `TurnContext` instance is created.\n * Fields will grow as the turn execution model takes shape (e.g. input message, tool\n * definitions, model client config).\n */\nexport interface RawTurnContext {\n /** `AbortController` whose signal can be used to cancel the turn mid-flight. */\n turnAbortController: AbortController\n /** A registry for arbitrary additional data to be added to the context as needed; initially empty. */\n stash?: Record<string, unknown>\n /** The system prompt guiding the agent's behavior for this turn. */\n systemPrompt: string | Tokenizable\n /** Standing instructions for the agent, applied to every turn. */\n standingInstructions: (string | Tokenizable)[]\n}\n\n/**\n * A fully-resolved {@link RawTurnContext} where all optional fields have been filled in by the\n * schema (e.g. `stash` defaulted to `{}`).\n *\n * @remarks\n * This is the shape returned by `turnContextSchema` after validation — use it wherever a\n * guaranteed-present context is needed rather than the raw caller-supplied input.\n */\nexport type ResolvedTurnContext = Required<RawTurnContext>\n\n/**\n * Validator schema used to validate a {@link RawTurnContext} before constructing a {@link TurnContext}.\n *\n * @remarks\n * Validates all four fields of {@link RawTurnContext}:\n * - `turnAbortController` — required `AbortController` instance.\n * - `stash` — optional string-keyed object; defaults to `{}`.\n * - `systemPrompt` — required string or {@link @nhtio/adk!Tokenizable}, via {@link @nhtio/adk!Tokenizable.schema}.\n * - `standingInstructions` — optional array of strings or {@link @nhtio/adk!Tokenizable} instances, each\n * validated via {@link @nhtio/adk!Tokenizable.schema}; defaults to `[]`.\n *\n * Throws a `ValidationException` (via {@link validateOrThrow}) when validation fails.\n */\nexport const turnContextSchema = validator\n .object<RawTurnContext>({\n turnAbortController: validator\n .alternatives(\n validator.object().instance(AbortController as any),\n validator.function().instance(AbortController as any)\n )\n .required(),\n stash: validator.object().pattern(validator.string(), validator.any()).default({}),\n systemPrompt: Tokenizable.schema.required(),\n standingInstructions: validator.array().items(Tokenizable.schema).default([]),\n })\n .required()\n\n/**\n * A function that retrieves the memories relevant to the current turn.\n *\n * @remarks\n * Receives the active {@link TurnContext} so implementations can filter or rank memories\n * based on turn-specific state (e.g. the system prompt, standing instructions, or stash).\n * May be synchronous or asynchronous.\n */\nexport type MemoryRetrievalFn = (ctx: TurnContext) => Memory[] | Promise<Memory[]>\n\n/**\n * A function that retrieves the retrievable (RAG) records relevant to the current turn.\n *\n * @remarks\n * Receives the active {@link TurnContext} so implementations can rank, filter, or compose\n * retrieval results against the turn-specific state (system prompt, standing instructions, etc.).\n * The retrieval middleware that produces these records is responsible for assigning each one's\n * `trustTier` — batteries MUST NOT auto-classify retrieved content.\n * May be synchronous or asynchronous.\n */\nexport type RetrievableRetrievalFn = (ctx: TurnContext) => Retrievable[] | Promise<Retrievable[]>\n\n/**\n * A function that retrieves the conversation messages relevant to the current turn.\n *\n * @remarks\n * Receives the active {@link TurnContext} so implementations can apply turn-aware filtering or\n * windowing. Returns only `user` and `assistant` {@link @nhtio/adk!Message} entries — system instructions\n * and tool results are not part of the persisted message history.\n * May be synchronous or asynchronous.\n */\nexport type MessageRetrievalFn = (ctx: TurnContext) => Message[] | Promise<Message[]>\n\n/**\n * A function that retrieves the thought traces relevant to the current turn.\n *\n * @remarks\n * Receives the active {@link TurnContext} so implementations can apply turn-aware filtering or\n * attribution (e.g. filtering to a specific agent's identity in multi-agent conversations).\n * May be synchronous or asynchronous.\n */\nexport type ThoughtRetrievalFn = (ctx: TurnContext) => Thought[] | Promise<Thought[]>\n\n/**\n * A function that retrieves the tool call records relevant to the current turn.\n *\n * @remarks\n * Receives the active {@link TurnContext} so implementations can filter by completion state,\n * agent identity, or any other turn-specific criteria.\n * May be synchronous or asynchronous.\n */\nexport type ToolCallRetrievalFn = (ctx: TurnContext) => ToolCall[] | Promise<ToolCall[]>\n\n/**\n * A function that retrieves the tools available for the current turn.\n *\n * @remarks\n * Receives the active {@link TurnContext} so implementations can apply turn-aware filtering\n * (e.g. RBAC scopes, feature flags). May be synchronous or asynchronous.\n */\nexport type ToolsRetrievalFn = (ctx: TurnContext) => Tool[] | Promise<Tool[]>\n\n/**\n * A function that refreshes and returns the standing instructions for the current turn.\n *\n * @remarks\n * Called to re-derive standing instructions mid-turn when they may have changed.\n * May be synchronous or asynchronous.\n */\nexport type StandingInstructionsRefreshFn = (\n ctx: TurnContext\n) => (string | Tokenizable)[] | Promise<(string | Tokenizable)[]>\n\n/** Stores a new standing instruction in the persistence layer. */\nexport type StandingInstructionStoreFn = (\n ctx: TurnContext,\n v: string | Tokenizable\n) => void | Promise<void>\n\n/** Updates an existing standing instruction in the persistence layer. */\nexport type StandingInstructionMutateFn = (\n ctx: TurnContext,\n v: string | Tokenizable\n) => void | Promise<void>\n\n/** Removes a standing instruction from the persistence layer. */\nexport type StandingInstructionDeleteFn = (\n ctx: TurnContext,\n v: string | Tokenizable\n) => void | Promise<void>\n\n/** Stores a new memory in the persistence layer. */\nexport type MemoryStoreFn = (ctx: TurnContext, v: Memory) => void | Promise<void>\n\n/** Updates an existing memory in the persistence layer. */\nexport type MemoryMutateFn = (ctx: TurnContext, v: Memory) => void | Promise<void>\n\n/** Removes a memory from the persistence layer by ID. */\nexport type MemoryDeleteFn = (ctx: TurnContext, id: string) => void | Promise<void>\n\n/** Stores a new retrievable record in the persistence layer. */\nexport type RetrievableStoreFn = (ctx: TurnContext, v: Retrievable) => void | Promise<void>\n\n/** Updates an existing retrievable record in the persistence layer. */\nexport type RetrievableMutateFn = (ctx: TurnContext, v: Retrievable) => void | Promise<void>\n\n/** Removes a retrievable record from the persistence layer by ID. */\nexport type RetrievableDeleteFn = (ctx: TurnContext, id: string) => void | Promise<void>\n\n/** Stores a new message in the persistence layer. */\nexport type MessageStoreFn = (ctx: TurnContext, v: Message) => void | Promise<void>\n\n/** Updates an existing message in the persistence layer. */\nexport type MessageMutateFn = (ctx: TurnContext, v: Message) => void | Promise<void>\n\n/** Removes a message from the persistence layer by ID. */\nexport type MessageDeleteFn = (ctx: TurnContext, id: string) => void | Promise<void>\n\n/** Stores a new thought in the persistence layer. */\nexport type ThoughtStoreFn = (ctx: TurnContext, v: Thought) => void | Promise<void>\n\n/** Updates an existing thought in the persistence layer. */\nexport type ThoughtMutateFn = (ctx: TurnContext, v: Thought) => void | Promise<void>\n\n/** Removes a thought from the persistence layer by ID. */\nexport type ThoughtDeleteFn = (ctx: TurnContext, id: string) => void | Promise<void>\n\n/** Stores a new tool call in the persistence layer. */\nexport type ToolCallStoreFn = (ctx: TurnContext, v: ToolCall) => void | Promise<void>\n\n/** Updates an existing tool call in the persistence layer. */\nexport type ToolCallMutateFn = (ctx: TurnContext, v: ToolCall) => void | Promise<void>\n\n/** Removes a tool call from the persistence layer by ID. */\nexport type ToolCallDeleteFn = (ctx: TurnContext, id: string) => void | Promise<void>\n\n/**\n * Persists tool-generated media bytes into consumer storage and returns a {@link @nhtio/adk!MediaReader}.\n * A byte-persistence conduit, not a mutation — returns a value and touches no turn state.\n */\nexport type MediaBytesStoreFn = (\n ctx: TurnContext,\n id: string,\n bytes: ConduitBytes\n) => MediaReader | Promise<MediaReader>\n\n/**\n * Persists extracted retrievable text bytes into consumer storage and returns a\n * {@link @nhtio/adk!SpoolReader}. A byte-persistence conduit, not a mutation.\n */\nexport type RetrievableBytesStoreFn = (\n ctx: TurnContext,\n id: string,\n bytes: ConduitBytes\n) => SpoolReader | Promise<SpoolReader>\n\n/**\n * Callbacks injected into a {@link TurnContext} by `TurnRunner` at run time.\n *\n * @remarks\n * These are supplied by the `TurnRunnerConfig` and bound to the context so middleware\n * can call fetch, emit, and mutation methods directly on the context without needing a reference\n * to the runner or its emitters. Not exported — `TurnContext` is constructed internally and\n * callers never need to reference this shape.\n *\n * @internal\n */\ninterface TurnRunnerInjected {\n /** Retrieves memories relevant to this turn. */\n fetchMemories: MemoryRetrievalFn\n /** Retrieves conversation messages relevant to this turn. */\n fetchMessages: MessageRetrievalFn\n /** Retrieves thought traces relevant to this turn. */\n fetchThoughts: ThoughtRetrievalFn\n /** Retrieves tool call records relevant to this turn. */\n fetchToolCalls: ToolCallRetrievalFn\n /** Retrieves tools available for this turn. */\n fetchTools: ToolsRetrievalFn\n /** Refreshes and returns the standing instructions for this turn. */\n refreshStandingInstructions: StandingInstructionsRefreshFn\n /** Stores a new standing instruction in the persistence layer. */\n storeStandingInstruction: StandingInstructionStoreFn\n /** Updates an existing standing instruction in the persistence layer. */\n mutateStandingInstruction: StandingInstructionMutateFn\n /** Removes a standing instruction from the persistence layer. */\n deleteStandingInstruction: StandingInstructionDeleteFn\n /** Stores a new memory in the persistence layer. */\n storeMemory: MemoryStoreFn\n /** Updates an existing memory in the persistence layer. */\n mutateMemory: MemoryMutateFn\n /** Removes a memory from the persistence layer by ID. */\n deleteMemory: MemoryDeleteFn\n /** Retrieves retrievable records relevant to this turn. */\n fetchRetrievables: RetrievableRetrievalFn\n /** Stores a new retrievable record in the persistence layer. */\n storeRetrievable: RetrievableStoreFn\n /** Updates an existing retrievable record in the persistence layer. */\n mutateRetrievable: RetrievableMutateFn\n /** Removes a retrievable record from the persistence layer by ID. */\n deleteRetrievable: RetrievableDeleteFn\n /** Stores a new message in the persistence layer. */\n storeMessage: MessageStoreFn\n /** Updates an existing message in the persistence layer. */\n mutateMessage: MessageMutateFn\n /** Removes a message from the persistence layer by ID. */\n deleteMessage: MessageDeleteFn\n /** Stores a new thought in the persistence layer. */\n storeThought: ThoughtStoreFn\n /** Updates an existing thought in the persistence layer. */\n mutateThought: ThoughtMutateFn\n /** Removes a thought from the persistence layer by ID. */\n deleteThought: ThoughtDeleteFn\n /** Stores a new tool call in the persistence layer. */\n storeToolCall: ToolCallStoreFn\n /** Updates an existing tool call in the persistence layer. */\n mutateToolCall: ToolCallMutateFn\n /** Removes a tool call from the persistence layer by ID. */\n deleteToolCall: ToolCallDeleteFn\n /** Persists tool-generated media bytes; returns a `MediaReader`. */\n storeMediaBytes: MediaBytesStoreFn\n /** Persists extracted retrievable text bytes; returns a `SpoolReader`. */\n storeRetrievableBytes: RetrievableBytesStoreFn\n /** Emits a `message` event on the runner. */\n emitMessage: EmitMessageFn\n /** Emits a `thought` event on the runner. */\n emitThought: EmitThoughtFn\n /** Emits a `toolCall` event on the runner. */\n emitToolCall: EmitToolCallFn\n /** Emits a `toolExecutionStart` event on the observability bus. */\n emitToolExecutionStart: EmitToolExecutionStartFn\n /** Emits a `toolExecutionEnd` event on the observability bus. */\n emitToolExecutionEnd: EmitToolExecutionEndFn\n /** Opens a turn gate; `turnId` and `abortSignal` are injected by the runner. */\n openGate: OpenGateFn\n /** The turn-scoped tool registry constructed from the runner's baseline tools. */\n tools: ToolRegistry\n}\n\n/**\n * The validated, strongly-typed context object threaded through every middleware step in a\n * single agent turn.\n *\n * @remarks\n * Constructed from a {@link RawTurnContext} by {@link @nhtio/adk!TurnRunner.run}. Middleware functions\n * receive this object and use it to read and share state across pipeline steps.\n */\nexport class TurnContext {\n /**\n * Returns `true` if `value` is a {@link TurnContext} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety. The ADK does not export the\n * `TurnContext` class itself as a constructable value — use this guard plus the\n * {@link TurnContext} type for runtime detection and TypeScript narrowing.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link TurnContext} instance.\n */\n public static isTurnContext(value: unknown): value is TurnContext {\n return isInstanceOf(value, 'TurnContext', TurnContext)\n }\n\n #id: string\n #turnAbortController: AbortController\n #stash: Registry\n #systemPrompt: Tokenizable\n #standingInstructions: Set<Tokenizable>\n #turnMemories: Set<Memory>\n #turnRetrievables: Set<Retrievable>\n #turnMessages: Set<Message>\n #turnThoughts: Set<Thought>\n #turnToolCalls: Set<ToolCall>\n\n /**\n * @param raw - The raw context input validated against {@link turnContextSchema}.\n * @param injected - Runtime callbacks supplied by `TurnRunner`; bound as instance methods so\n * middleware can call fetch and emit methods directly on the context.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} when `raw` does not satisfy the schema.\n *\n * @internal\n */\n constructor(raw: RawTurnContext, injected: TurnRunnerInjected) {\n try {\n raw = validateOrThrow<ResolvedTurnContext>(turnContextSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_TURN_CONTEXT({ cause: isError(err) ? err : undefined })\n }\n this.#id = uuidv6()\n this.#turnAbortController = raw.turnAbortController\n this.#stash = new Registry(raw.stash)\n this.#systemPrompt = Tokenizable.isTokenizable(raw.systemPrompt)\n ? raw.systemPrompt\n : new Tokenizable(raw.systemPrompt)\n this.#standingInstructions = new Set(\n (raw.standingInstructions || []).map((instr) =>\n Tokenizable.isTokenizable(instr) ? instr : new Tokenizable(instr)\n )\n )\n this.#turnMemories = new Set()\n this.#turnRetrievables = new Set()\n this.#turnMessages = new Set()\n this.#turnThoughts = new Set()\n this.#turnToolCalls = new Set()\n\n // Expose read-only properties on the instance for easy access in middleware.\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n aborted: {\n get: () => Boolean(this.#turnAbortController.signal.aborted),\n enumerable: true,\n configurable: false,\n },\n abortSignal: {\n get: () => this.#turnAbortController.signal,\n enumerable: true,\n configurable: false,\n },\n abort: {\n value: (reason?: unknown) => this.#turnAbortController.abort(reason),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n stash: {\n get: () => this.#stash,\n enumerable: true,\n configurable: false,\n },\n systemPrompt: {\n get: () => this.#systemPrompt,\n enumerable: true,\n configurable: false,\n },\n standingInstructions: {\n get: () => this.#standingInstructions,\n enumerable: true,\n configurable: false,\n },\n turnMemories: {\n get: () => this.#turnMemories,\n enumerable: true,\n configurable: false,\n },\n turnRetrievables: {\n get: () => this.#turnRetrievables,\n enumerable: true,\n configurable: false,\n },\n turnMessages: {\n get: () => this.#turnMessages,\n enumerable: true,\n configurable: false,\n },\n turnThoughts: {\n get: () => this.#turnThoughts,\n enumerable: true,\n configurable: false,\n },\n turnToolCalls: {\n get: () => this.#turnToolCalls,\n enumerable: true,\n configurable: false,\n },\n })\n\n // Attach injected dependencies as instance methods for access in middleware.\n Object.defineProperties(this, {\n fetchMemories: {\n value: () => injected.fetchMemories(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchMessages: {\n value: () => injected.fetchMessages(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchThoughts: {\n value: () => injected.fetchThoughts(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchToolCalls: {\n value: () => injected.fetchToolCalls(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchTools: {\n value: () => injected.fetchTools(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n refreshStandingInstructions: {\n value: () => injected.refreshStandingInstructions(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeStandingInstruction: {\n value: (v: string | Tokenizable) => injected.storeStandingInstruction(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateStandingInstruction: {\n value: (v: string | Tokenizable) => injected.mutateStandingInstruction(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteStandingInstruction: {\n value: (v: string | Tokenizable) => injected.deleteStandingInstruction(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeMemory: {\n value: (v: Memory) => injected.storeMemory(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateMemory: {\n value: (v: Memory) => injected.mutateMemory(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteMemory: {\n value: (id: string) => injected.deleteMemory(this, id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchRetrievables: {\n value: () => injected.fetchRetrievables(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeRetrievable: {\n value: (v: Retrievable) => injected.storeRetrievable(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateRetrievable: {\n value: (v: Retrievable) => injected.mutateRetrievable(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteRetrievable: {\n value: (id: string) => injected.deleteRetrievable(this, id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeMessage: {\n value: (v: Message) => injected.storeMessage(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateMessage: {\n value: (v: Message) => injected.mutateMessage(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteMessage: {\n value: (id: string) => injected.deleteMessage(this, id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeThought: {\n value: (v: Thought) => injected.storeThought(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateThought: {\n value: (v: Thought) => injected.mutateThought(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteThought: {\n value: (id: string) => injected.deleteThought(this, id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeToolCall: {\n value: (v: ToolCall) => injected.storeToolCall(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateToolCall: {\n value: (v: ToolCall) => injected.mutateToolCall(this, v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteToolCall: {\n value: (id: string) => injected.deleteToolCall(this, id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeMediaBytes: {\n value: (id: string, bytes: ConduitBytes) => injected.storeMediaBytes(this, id, bytes),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeRetrievableBytes: {\n value: (id: string, bytes: ConduitBytes) => injected.storeRetrievableBytes(this, id, bytes),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitMessage: {\n value: injected.emitMessage,\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitThought: {\n value: injected.emitThought,\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitToolCall: {\n value: injected.emitToolCall,\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitToolExecutionStart: {\n value: injected.emitToolExecutionStart,\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitToolExecutionEnd: {\n value: injected.emitToolExecutionEnd,\n enumerable: true,\n configurable: false,\n writable: false,\n },\n waitFor: {\n value: injected.openGate,\n enumerable: true,\n configurable: false,\n writable: false,\n },\n tools: {\n get: () => injected.tools,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /** Unique identifier for this turn, generated as a UUIDv6 at construction time. */\n declare readonly id: string\n /** `true` when the turn's `AbortController` signal has fired. */\n declare readonly aborted: boolean\n /** The `AbortSignal` from the turn's `AbortController`. */\n declare readonly abortSignal: AbortSignal\n /**\n * Aborts the turn's `AbortController` with the supplied reason. Middleware should call this\n * when refusing the turn — the runner reads `aborted` between every stage and short-circuits\n * cleanly: `turnEnd` still fires, no `error` event is emitted, and during dispatch\n * `dispatchEnd.status === 'aborted'` carries the operational signal.\n */\n declare readonly abort: (reason?: unknown) => void\n /** Arbitrary key-value store that middleware can read and write across pipeline steps. */\n declare readonly stash: Registry\n /** The system prompt guiding the agent's behaviour for this turn. */\n declare readonly systemPrompt: Tokenizable\n /** Standing instructions applied to every turn, in insertion order. */\n declare readonly standingInstructions: Set<Tokenizable>\n /** Memories loaded for this turn; populated by middleware after calling `fetchMemories()`. */\n declare readonly turnMemories: Set<Memory>\n /** Retrievable records loaded for this turn; populated by middleware after calling `fetchRetrievables()`. */\n declare readonly turnRetrievables: Set<Retrievable>\n /** Conversation messages loaded for this turn; populated by middleware after calling `fetchMessages()`. */\n declare readonly turnMessages: Set<Message>\n /** Thought traces loaded for this turn; populated by middleware after calling `fetchThoughts()`. */\n declare readonly turnThoughts: Set<Thought>\n /** Tool call records loaded for this turn; populated by middleware after calling `fetchToolCalls()`. */\n declare readonly turnToolCalls: Set<ToolCall>\n /** Fetches memories relevant to this turn; delegates to the callback supplied at construction. */\n declare readonly fetchMemories: () => Memory[] | Promise<Memory[]>\n /** Fetches conversation messages relevant to this turn; delegates to the callback supplied at construction. */\n declare readonly fetchMessages: () => Message[] | Promise<Message[]>\n /** Fetches thought traces relevant to this turn; delegates to the callback supplied at construction. */\n declare readonly fetchThoughts: () => Thought[] | Promise<Thought[]>\n /** Fetches tool call records relevant to this turn; delegates to the callback supplied at construction. */\n declare readonly fetchToolCalls: () => ToolCall[] | Promise<ToolCall[]>\n /** Fetches tools available for this turn; delegates to the callback supplied at construction. */\n declare readonly fetchTools: () => Tool[] | Promise<Tool[]>\n /** Refreshes and returns the standing instructions; delegates to the callback supplied at construction. */\n declare readonly refreshStandingInstructions: () =>\n | (string | Tokenizable)[]\n | Promise<(string | Tokenizable)[]>\n /** Stores a new standing instruction in the persistence layer. */\n declare readonly storeStandingInstruction: (v: string | Tokenizable) => void | Promise<void>\n /** Updates an existing standing instruction in the persistence layer. */\n declare readonly mutateStandingInstruction: (v: string | Tokenizable) => void | Promise<void>\n /** Removes a standing instruction from the persistence layer. */\n declare readonly deleteStandingInstruction: (v: string | Tokenizable) => void | Promise<void>\n /** Stores a new memory in the persistence layer. */\n declare readonly storeMemory: (v: Memory) => void | Promise<void>\n /** Updates an existing memory in the persistence layer. */\n declare readonly mutateMemory: (v: Memory) => void | Promise<void>\n /** Removes a memory from the persistence layer by ID. */\n declare readonly deleteMemory: (id: string) => void | Promise<void>\n /** Fetches retrievable records relevant to this turn; delegates to the callback supplied at construction. */\n declare readonly fetchRetrievables: () => Retrievable[] | Promise<Retrievable[]>\n /** Stores a new retrievable record in the persistence layer. */\n declare readonly storeRetrievable: (v: Retrievable) => void | Promise<void>\n /** Updates an existing retrievable record in the persistence layer. */\n declare readonly mutateRetrievable: (v: Retrievable) => void | Promise<void>\n /** Removes a retrievable record from the persistence layer by ID. */\n declare readonly deleteRetrievable: (id: string) => void | Promise<void>\n /** Stores a new message in the persistence layer. */\n declare readonly storeMessage: (v: Message) => void | Promise<void>\n /** Updates an existing message in the persistence layer. */\n declare readonly mutateMessage: (v: Message) => void | Promise<void>\n /** Removes a message from the persistence layer by ID. */\n declare readonly deleteMessage: (id: string) => void | Promise<void>\n /** Stores a new thought in the persistence layer. */\n declare readonly storeThought: (v: Thought) => void | Promise<void>\n /** Updates an existing thought in the persistence layer. */\n declare readonly mutateThought: (v: Thought) => void | Promise<void>\n /** Removes a thought from the persistence layer by ID. */\n declare readonly deleteThought: (id: string) => void | Promise<void>\n /** Stores a new tool call in the persistence layer. */\n declare readonly storeToolCall: (v: ToolCall) => void | Promise<void>\n /** Updates an existing tool call in the persistence layer. */\n declare readonly mutateToolCall: (v: ToolCall) => void | Promise<void>\n /** Removes a tool call from the persistence layer by ID. */\n declare readonly deleteToolCall: (id: string) => void | Promise<void>\n /**\n * Persists tool-generated media bytes into consumer storage and returns a {@link @nhtio/adk!MediaReader}.\n * Low-level conduit — returns a value, touches no turn state; build a {@link @nhtio/adk!Media} from the\n * reader and persist the owning primitive separately.\n */\n declare readonly storeMediaBytes: (\n id: string,\n bytes: ConduitBytes\n ) => MediaReader | Promise<MediaReader>\n /**\n * Persists extracted retrievable text bytes into consumer storage and returns a\n * {@link @nhtio/adk!SpoolReader}. Wrap it in a {@link @nhtio/adk!SpooledArtifact} for `Retrievable.content`\n * and persist the record via {@link TurnContext.storeRetrievable} separately.\n */\n declare readonly storeRetrievableBytes: (\n id: string,\n bytes: ConduitBytes\n ) => SpoolReader | Promise<SpoolReader>\n /** Emits a `message` event on the runner; may be called at any point during the turn. */\n declare readonly emitMessage: EmitMessageFn\n /** Emits a `thought` event on the runner; may be called at any point during the turn. */\n declare readonly emitThought: EmitThoughtFn\n /** Emits a `toolCall` event on the runner; may be called at any point during the turn. */\n declare readonly emitToolCall: EmitToolCallFn\n /** Emits a `toolExecutionStart` event on the observability bus; forwarded from `DispatchContext` by `DispatchRunner` when a tool is invoked inside a dispatch. */\n declare readonly emitToolExecutionStart: EmitToolExecutionStartFn\n /** Emits a `toolExecutionEnd` event on the observability bus; forwarded from `DispatchContext` by `DispatchRunner` when a tool finishes executing inside a dispatch. */\n declare readonly emitToolExecutionEnd: EmitToolExecutionEndFn\n /** Opens a turn gate and suspends until it resolves, rejects, times out, or is aborted. */\n declare readonly waitFor: OpenGateFn\n /** Turn-scoped tool registry constructed from the runner's baseline tools; middleware may trim or extend it. */\n declare readonly tools: ToolRegistry\n}\n","import { v6 as uuidv6 } from 'uuid'\nimport { Hooks } from '@nhtio/hooks'\nimport { validator } from '@nhtio/validation'\nimport { Registry } from '../classes/registry'\nimport { Tokenizable } from '../classes/tokenizable'\nimport { validateOrThrow } from '../utils/validation'\nimport { isInstanceOf, isError } from '../utils/guards'\nimport { ToolRegistry } from '../classes/tool_registry'\nimport {\n E_INVALID_LLM_EXECUTION_CONTEXT,\n E_LLM_EXECUTION_GATE_NOT_SUPPORTED,\n E_LLM_EXECUTION_ALREADY_SIGNALLED,\n} from '../exceptions/runtime'\nimport type { Tool } from '../classes/tool'\nimport type { Memory } from '../classes/memory'\nimport type { Message } from '../classes/message'\nimport type { Thought } from '../classes/thought'\nimport type { SpoolReader } from './spool_reader'\nimport type { MediaReader } from './media_reader'\nimport type { ToolCall } from '../classes/tool_call'\nimport type { Retrievable } from '../classes/retrievable'\nimport type {\n DispatchContextHooks,\n DispatchContextHookRegistrations,\n} from '../types/dispatch_context'\nimport type {\n EmitMessageFn,\n EmitThoughtFn,\n EmitToolCallFn,\n EmitToolExecutionStartFn,\n EmitToolExecutionEndFn,\n OpenGateFn,\n} from '../types/turn_runner'\n\n/** Payload accepted by the byte-persistence conduits — text, raw bytes, or a stream. */\nexport type ConduitBytes = string | Uint8Array | ReadableStream<Uint8Array>\n\n// ── LLM-scoped callback fn types ─────────────────────────────────────────────\n\n/** Retrieves memories for an LLM execution context. */\nexport type DispatchMemoryRetrievalFn = (ctx: DispatchContext) => Memory[] | Promise<Memory[]>\n\n/** Retrieves messages for an LLM execution context. */\nexport type DispatchMessageRetrievalFn = (ctx: DispatchContext) => Message[] | Promise<Message[]>\n\n/** Retrieves thoughts for an LLM execution context. */\nexport type DispatchThoughtRetrievalFn = (ctx: DispatchContext) => Thought[] | Promise<Thought[]>\n\n/** Retrieves tool calls for an LLM execution context. */\nexport type DispatchToolCallRetrievalFn = (ctx: DispatchContext) => ToolCall[] | Promise<ToolCall[]>\n\n/** Retrieves tools for an LLM execution context. */\nexport type DispatchToolsRetrievalFn = (ctx: DispatchContext) => Tool[] | Promise<Tool[]>\n\n/** Refreshes and returns standing instructions for an LLM execution context. */\nexport type DispatchStandingInstructionsRefreshFn = (\n ctx: DispatchContext\n) => (string | Tokenizable)[] | Promise<(string | Tokenizable)[]>\n\n/** Stores a new standing instruction (LLM execution context variant). */\nexport type DispatchStandingInstructionStoreFn = (\n ctx: DispatchContext,\n v: string | Tokenizable\n) => void | Promise<void>\n\n/** Updates an existing standing instruction (LLM execution context variant). */\nexport type DispatchStandingInstructionMutateFn = (\n ctx: DispatchContext,\n v: string | Tokenizable\n) => void | Promise<void>\n\n/** Removes a standing instruction (LLM execution context variant). */\nexport type DispatchStandingInstructionDeleteFn = (\n ctx: DispatchContext,\n v: string | Tokenizable\n) => void | Promise<void>\n\n/** Stores a new memory (LLM execution context variant). */\nexport type DispatchMemoryStoreFn = (ctx: DispatchContext, v: Memory) => void | Promise<void>\n\n/** Updates an existing memory (LLM execution context variant). */\nexport type DispatchMemoryMutateFn = (ctx: DispatchContext, v: Memory) => void | Promise<void>\n\n/** Removes a memory by ID (LLM execution context variant). */\nexport type DispatchMemoryDeleteFn = (ctx: DispatchContext, id: string) => void | Promise<void>\n\n/** Retrieves retrievable records for an LLM execution context. */\nexport type DispatchRetrievableRetrievalFn = (\n ctx: DispatchContext\n) => Retrievable[] | Promise<Retrievable[]>\n\n/** Stores a new retrievable record (LLM execution context variant). */\nexport type DispatchRetrievableStoreFn = (\n ctx: DispatchContext,\n v: Retrievable\n) => void | Promise<void>\n\n/** Updates an existing retrievable record (LLM execution context variant). */\nexport type DispatchRetrievableMutateFn = (\n ctx: DispatchContext,\n v: Retrievable\n) => void | Promise<void>\n\n/** Removes a retrievable record by ID (LLM execution context variant). */\nexport type DispatchRetrievableDeleteFn = (ctx: DispatchContext, id: string) => void | Promise<void>\n\n/** Stores a new message (LLM execution context variant). */\nexport type DispatchMessageStoreFn = (ctx: DispatchContext, v: Message) => void | Promise<void>\n\n/** Updates an existing message (LLM execution context variant). */\nexport type DispatchMessageMutateFn = (ctx: DispatchContext, v: Message) => void | Promise<void>\n\n/** Removes a message by ID (LLM execution context variant). */\nexport type DispatchMessageDeleteFn = (ctx: DispatchContext, id: string) => void | Promise<void>\n\n/** Stores a new thought (LLM execution context variant). */\nexport type DispatchThoughtStoreFn = (ctx: DispatchContext, v: Thought) => void | Promise<void>\n\n/** Updates an existing thought (LLM execution context variant). */\nexport type DispatchThoughtMutateFn = (ctx: DispatchContext, v: Thought) => void | Promise<void>\n\n/** Removes a thought by ID (LLM execution context variant). */\nexport type DispatchThoughtDeleteFn = (ctx: DispatchContext, id: string) => void | Promise<void>\n\n/** Stores a new tool call (LLM execution context variant). */\nexport type DispatchToolCallStoreFn = (ctx: DispatchContext, v: ToolCall) => void | Promise<void>\n\n/** Updates an existing tool call (LLM execution context variant). */\nexport type DispatchToolCallMutateFn = (ctx: DispatchContext, v: ToolCall) => void | Promise<void>\n\n/** Removes a tool call by ID (LLM execution context variant). */\nexport type DispatchToolCallDeleteFn = (ctx: DispatchContext, id: string) => void | Promise<void>\n\n/**\n * Persists tool-generated media bytes into consumer storage and returns a {@link @nhtio/adk!MediaReader}\n * (LLM execution context variant). Unlike the `store*` mutation callbacks this returns a value and\n * does NOT add anything to the turn Sets — the handler builds a {@link @nhtio/adk!Media} from the reader\n * and persists it via `storeMessage`/`storeToolCall` separately.\n */\nexport type DispatchMediaBytesStoreFn = (\n ctx: DispatchContext,\n id: string,\n bytes: ConduitBytes\n) => MediaReader | Promise<MediaReader>\n\n/**\n * Persists extracted retrievable text bytes into consumer storage and returns a\n * {@link @nhtio/adk!SpoolReader} (LLM execution context variant). The handler wraps the reader in a\n * {@link @nhtio/adk!SpooledArtifact} for `new Retrievable({ content })` and persists the record via\n * `storeRetrievable` separately. Returns a value; does NOT touch the turn Sets.\n */\nexport type DispatchRetrievableBytesStoreFn = (\n ctx: DispatchContext,\n id: string,\n bytes: ConduitBytes\n) => SpoolReader | Promise<SpoolReader>\n\n// ── RawDispatchContext ────────────────────────────────────────────────────\n\n/**\n * Plain input object supplied to {@link DispatchContext} at construction time.\n *\n * @remarks\n * All fetch and mutation callbacks are required — every execution context must have a persistence\n * layer wired up, even in standalone mode. Optional pre-fetched arrays populate the context's Sets\n * at construction time without replacing the callbacks (the callbacks are still invoked on\n * subsequent fetch calls).\n */\nexport interface RawDispatchContext {\n /** `AbortController` whose signal can cancel execution mid-flight. */\n turnAbortController?: AbortController\n /** Arbitrary key-value store for cross-step state. */\n stash?: Record<string, unknown>\n /** The system prompt for this execution. */\n systemPrompt: string | Tokenizable\n /** Standing instructions for this execution. */\n standingInstructions?: (string | Tokenizable)[]\n\n // Pre-fetched data (optional — populates Sets at construction)\n /** Pre-fetched memories to populate the context at construction. */\n memories?: Memory[]\n /** Pre-fetched retrievable records to populate the context at construction. */\n retrievables?: Retrievable[]\n /** Pre-fetched messages to populate the context at construction. */\n messages?: Message[]\n /** Pre-fetched thoughts to populate the context at construction. */\n thoughts?: Thought[]\n /** Pre-fetched tool calls to populate the context at construction. */\n toolCalls?: ToolCall[]\n /** Pre-fetched tools to populate the tool registry at construction. */\n tools?: Tool[]\n\n // Fetch callbacks (required)\n /** Retrieves memories for this execution. */\n fetchMemories: DispatchMemoryRetrievalFn\n /** Retrieves retrievable records for this execution. */\n fetchRetrievables: DispatchRetrievableRetrievalFn\n /** Retrieves messages for this execution. */\n fetchMessages: DispatchMessageRetrievalFn\n /** Retrieves thoughts for this execution. */\n fetchThoughts: DispatchThoughtRetrievalFn\n /** Retrieves tool calls for this execution. */\n fetchToolCalls: DispatchToolCallRetrievalFn\n /** Retrieves tools for this execution. */\n fetchTools: DispatchToolsRetrievalFn\n /** Refreshes and returns standing instructions for this execution. */\n refreshStandingInstructions: DispatchStandingInstructionsRefreshFn\n\n // Mutation callbacks (required — persistence layer; called immediately on every mutation)\n /** Stores a new standing instruction. */\n storeStandingInstruction: DispatchStandingInstructionStoreFn\n /** Updates an existing standing instruction. */\n mutateStandingInstruction: DispatchStandingInstructionMutateFn\n /** Removes a standing instruction. */\n deleteStandingInstruction: DispatchStandingInstructionDeleteFn\n /** Stores a new memory. */\n storeMemory: DispatchMemoryStoreFn\n /** Updates an existing memory. */\n mutateMemory: DispatchMemoryMutateFn\n /** Removes a memory by ID. */\n deleteMemory: DispatchMemoryDeleteFn\n /** Stores a new retrievable record. */\n storeRetrievable: DispatchRetrievableStoreFn\n /** Updates an existing retrievable record. */\n mutateRetrievable: DispatchRetrievableMutateFn\n /** Removes a retrievable record by ID. */\n deleteRetrievable: DispatchRetrievableDeleteFn\n /** Stores a new message. */\n storeMessage: DispatchMessageStoreFn\n /** Updates an existing message. */\n mutateMessage: DispatchMessageMutateFn\n /** Removes a message by ID. */\n deleteMessage: DispatchMessageDeleteFn\n /** Stores a new thought. */\n storeThought: DispatchThoughtStoreFn\n /** Updates an existing thought. */\n mutateThought: DispatchThoughtMutateFn\n /** Removes a thought by ID. */\n deleteThought: DispatchThoughtDeleteFn\n /** Stores a new tool call. */\n storeToolCall: DispatchToolCallStoreFn\n /** Updates an existing tool call. */\n mutateToolCall: DispatchToolCallMutateFn\n /** Removes a tool call by ID. */\n deleteToolCall: DispatchToolCallDeleteFn\n /** Persists tool-generated media bytes; returns a `MediaReader`. */\n storeMediaBytes: DispatchMediaBytesStoreFn\n /** Persists extracted retrievable text bytes; returns a `SpoolReader`. */\n storeRetrievableBytes: DispatchRetrievableBytesStoreFn\n\n /** Optional hook registrations for emit events. */\n hooks?: DispatchContextHookRegistrations\n /** Optional gate suspension function. When absent, `waitFor` rejects with {@link @nhtio/adk!E_LLM_EXECUTION_GATE_NOT_SUPPORTED}. */\n waitFor?: OpenGateFn\n}\n\nconst rawDispatchContextSchema = validator.object<RawDispatchContext>({\n turnAbortController: validator\n .alternatives(\n validator.object().instance(AbortController as any),\n validator.function().instance(AbortController as any)\n )\n .optional(),\n stash: validator.object().pattern(validator.string(), validator.any()).default({}),\n systemPrompt: Tokenizable.schema.required(),\n standingInstructions: validator.array().items(Tokenizable.schema).default([]),\n memories: validator.array().default([]),\n retrievables: validator.array().default([]),\n messages: validator.array().default([]),\n thoughts: validator.array().default([]),\n toolCalls: validator.array().default([]),\n tools: validator.array().default([]),\n fetchMemories: validator.function().required(),\n fetchRetrievables: validator.function().required(),\n fetchMessages: validator.function().required(),\n fetchThoughts: validator.function().required(),\n fetchToolCalls: validator.function().required(),\n fetchTools: validator.function().required(),\n refreshStandingInstructions: validator.function().required(),\n storeStandingInstruction: validator.function().required(),\n mutateStandingInstruction: validator.function().required(),\n deleteStandingInstruction: validator.function().required(),\n storeMemory: validator.function().required(),\n mutateMemory: validator.function().required(),\n deleteMemory: validator.function().required(),\n storeRetrievable: validator.function().required(),\n mutateRetrievable: validator.function().required(),\n deleteRetrievable: validator.function().required(),\n storeMessage: validator.function().required(),\n mutateMessage: validator.function().required(),\n deleteMessage: validator.function().required(),\n storeThought: validator.function().required(),\n mutateThought: validator.function().required(),\n deleteThought: validator.function().required(),\n storeToolCall: validator.function().required(),\n mutateToolCall: validator.function().required(),\n deleteToolCall: validator.function().required(),\n storeMediaBytes: validator.function().required(),\n storeRetrievableBytes: validator.function().required(),\n hooks: validator.object().optional(),\n waitFor: validator.function().optional(),\n})\n\n// ── DispatchContext ───────────────────────────────────────────────────────\n\n/**\n * Context object for a single LLM execution call.\n *\n * @remarks\n * Mirrors the surface of {@link @nhtio/adk!TurnContext} but is path-agnostic — it knows nothing about a\n * parent context. Mutations apply to local Sets immediately, call persistence callbacks\n * immediately, and fire the corresponding mutation hook (`storedMemory`, `mutatedMemory`,\n * `deletedMemory`, etc.) in both standalone and derived dispatches.\n *\n * The {@link @nhtio/adk!DispatchRunner} is the only thing that creates a context with a parent\n * relationship: when dispatched with a `source: TurnContext`, the runner subscribes to the\n * mutation hooks, queues deltas internally, and flushes them to the parent's Sets at the end of\n * each iteration. The context itself remains unaware of the parent.\n *\n * Middleware/executor signals termination via {@link DispatchContext.ack} (clean completion)\n * or {@link DispatchContext.nack} (failure). Both set an internal flag the runner reads at\n * end-of-iteration to decide whether to loop or exit. {@link DispatchContext.isSignalled},\n * {@link DispatchContext.isAcked}, and {@link DispatchContext.nackError} are publicly\n * readable getters so middleware can inspect signal state and bail early.\n */\nexport class DispatchContext {\n #id: string\n #dispatchId: string\n #iteration: number\n #turnAbortController: AbortController\n #stash: Registry\n #systemPrompt: Tokenizable\n #standingInstructions: Set<Tokenizable>\n #turnMemories: Set<Memory>\n #turnRetrievables: Set<Retrievable>\n #turnMessages: Set<Message>\n #turnThoughts: Set<Thought>\n #turnToolCalls: Set<ToolCall>\n #tools: ToolRegistry\n #hooks: Hooks<DispatchContextHooks>\n #ackHandlers: Set<() => void>\n\n // Persistence callbacks\n #fetchMemories: DispatchMemoryRetrievalFn\n #fetchRetrievables: DispatchRetrievableRetrievalFn\n #fetchMessages: DispatchMessageRetrievalFn\n #fetchThoughts: DispatchThoughtRetrievalFn\n #fetchToolCalls: DispatchToolCallRetrievalFn\n #fetchTools: DispatchToolsRetrievalFn\n #refreshStandingInstructions: DispatchStandingInstructionsRefreshFn\n #storeStandingInstruction: DispatchStandingInstructionStoreFn\n #mutateStandingInstruction: DispatchStandingInstructionMutateFn\n #deleteStandingInstruction: DispatchStandingInstructionDeleteFn\n #storeMemory: DispatchMemoryStoreFn\n #mutateMemory: DispatchMemoryMutateFn\n #deleteMemory: DispatchMemoryDeleteFn\n #storeRetrievable: DispatchRetrievableStoreFn\n #mutateRetrievable: DispatchRetrievableMutateFn\n #deleteRetrievable: DispatchRetrievableDeleteFn\n #storeMessage: DispatchMessageStoreFn\n #mutateMessage: DispatchMessageMutateFn\n #deleteMessage: DispatchMessageDeleteFn\n #storeThought: DispatchThoughtStoreFn\n #mutateThought: DispatchThoughtMutateFn\n #deleteThought: DispatchThoughtDeleteFn\n #storeToolCall: DispatchToolCallStoreFn\n #mutateToolCall: DispatchToolCallMutateFn\n #deleteToolCall: DispatchToolCallDeleteFn\n #storeMediaBytes: DispatchMediaBytesStoreFn\n #storeRetrievableBytes: DispatchRetrievableBytesStoreFn\n #waitFor: OpenGateFn | undefined\n\n // Checksum frequency index for this execution\n #toolCallChecksums: Map<string, number>\n\n // Termination signal state\n #signalled: 'ack' | 'nack' | undefined\n #nackError: Error | undefined\n\n /**\n * @param raw - Raw input validated against the schema.\n * @throws {@link @nhtio/adk!E_INVALID_LLM_EXECUTION_CONTEXT} when `raw` does not satisfy the schema.\n */\n constructor(raw: RawDispatchContext) {\n let resolved: RawDispatchContext & {\n stash: Record<string, unknown>\n standingInstructions: (string | Tokenizable)[]\n memories: Memory[]\n retrievables: Retrievable[]\n messages: Message[]\n thoughts: Thought[]\n toolCalls: ToolCall[]\n tools: Tool[]\n }\n try {\n resolved = validateOrThrow(rawDispatchContextSchema, raw, true) as typeof resolved\n } catch (err) {\n throw new E_INVALID_LLM_EXECUTION_CONTEXT({ cause: isError(err) ? err : undefined })\n }\n\n this.#id = uuidv6()\n this.#dispatchId = ''\n this.#iteration = 0\n this.#turnAbortController = resolved.turnAbortController ?? new AbortController()\n this.#stash = new Registry(resolved.stash)\n this.#systemPrompt = Tokenizable.isTokenizable(resolved.systemPrompt)\n ? resolved.systemPrompt\n : new Tokenizable(resolved.systemPrompt)\n this.#standingInstructions = new Set(\n resolved.standingInstructions.map((i) =>\n Tokenizable.isTokenizable(i) ? i : new Tokenizable(i)\n )\n )\n this.#turnMemories = new Set(resolved.memories)\n this.#turnRetrievables = new Set(resolved.retrievables)\n this.#turnMessages = new Set(resolved.messages)\n this.#turnThoughts = new Set(resolved.thoughts)\n this.#turnToolCalls = new Set(resolved.toolCalls)\n this.#tools = new ToolRegistry(resolved.tools)\n this.#toolCallChecksums = new Map()\n for (const tc of resolved.toolCalls) {\n const prev = this.#toolCallChecksums.get(tc.checksum) ?? 0\n this.#toolCallChecksums.set(tc.checksum, prev + 1)\n }\n\n this.#fetchMemories = resolved.fetchMemories\n this.#fetchRetrievables = resolved.fetchRetrievables\n this.#fetchMessages = resolved.fetchMessages\n this.#fetchThoughts = resolved.fetchThoughts\n this.#fetchToolCalls = resolved.fetchToolCalls\n this.#fetchTools = resolved.fetchTools\n this.#refreshStandingInstructions = resolved.refreshStandingInstructions\n this.#storeStandingInstruction = resolved.storeStandingInstruction\n this.#mutateStandingInstruction = resolved.mutateStandingInstruction\n this.#deleteStandingInstruction = resolved.deleteStandingInstruction\n this.#storeMemory = resolved.storeMemory\n this.#mutateMemory = resolved.mutateMemory\n this.#deleteMemory = resolved.deleteMemory\n this.#storeRetrievable = resolved.storeRetrievable\n this.#mutateRetrievable = resolved.mutateRetrievable\n this.#deleteRetrievable = resolved.deleteRetrievable\n this.#storeMessage = resolved.storeMessage\n this.#mutateMessage = resolved.mutateMessage\n this.#deleteMessage = resolved.deleteMessage\n this.#storeThought = resolved.storeThought\n this.#mutateThought = resolved.mutateThought\n this.#deleteThought = resolved.deleteThought\n this.#storeToolCall = resolved.storeToolCall\n this.#mutateToolCall = resolved.mutateToolCall\n this.#deleteToolCall = resolved.deleteToolCall\n this.#storeMediaBytes = resolved.storeMediaBytes\n this.#storeRetrievableBytes = resolved.storeRetrievableBytes\n this.#waitFor = resolved.waitFor\n\n this.#signalled = undefined\n this.#nackError = undefined\n\n // Register hooks\n this.#hooks = new Hooks<DispatchContextHooks>()\n this.#ackHandlers = new Set()\n if (resolved.hooks) {\n const regs = resolved.hooks\n for (const key of Object.keys(regs) as (keyof DispatchContextHooks)[]) {\n const entry = regs[key]\n if (!entry) continue\n const handlers = Array.isArray(entry) ? entry : [entry]\n for (const h of handlers) {\n this.#hooks.add(key, h as any)\n }\n }\n }\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n dispatchId: {\n get: () => this.#dispatchId,\n enumerable: true,\n configurable: false,\n },\n iteration: {\n get: () => this.#iteration,\n enumerable: true,\n configurable: false,\n },\n aborted: {\n get: () => Boolean(this.#turnAbortController.signal.aborted),\n enumerable: true,\n configurable: false,\n },\n abortSignal: {\n get: () => this.#turnAbortController.signal,\n enumerable: true,\n configurable: false,\n },\n abort: {\n value: (reason?: unknown) => this.#turnAbortController.abort(reason),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n isSignalled: {\n get: () => this.#signalled !== undefined,\n enumerable: true,\n configurable: false,\n },\n isAcked: {\n get: () => this.#signalled === 'ack',\n enumerable: true,\n configurable: false,\n },\n nackError: {\n get: () => this.#nackError,\n enumerable: true,\n configurable: false,\n },\n stash: {\n get: () => this.#stash,\n enumerable: true,\n configurable: false,\n },\n systemPrompt: {\n get: () => this.#systemPrompt,\n enumerable: true,\n configurable: false,\n },\n standingInstructions: {\n get: () => this.#standingInstructions,\n enumerable: true,\n configurable: false,\n },\n turnMemories: {\n get: () => this.#turnMemories,\n enumerable: true,\n configurable: false,\n },\n turnRetrievables: {\n get: () => this.#turnRetrievables,\n enumerable: true,\n configurable: false,\n },\n turnMessages: {\n get: () => this.#turnMessages,\n enumerable: true,\n configurable: false,\n },\n turnThoughts: {\n get: () => this.#turnThoughts,\n enumerable: true,\n configurable: false,\n },\n turnToolCalls: {\n get: () => this.#turnToolCalls,\n enumerable: true,\n configurable: false,\n },\n tools: {\n get: () => this.#tools,\n enumerable: true,\n configurable: false,\n },\n fetchMemories: {\n value: () => this.#fetchMemories(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchRetrievables: {\n value: () => this.#fetchRetrievables(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchMessages: {\n value: () => this.#fetchMessages(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchThoughts: {\n value: () => this.#fetchThoughts(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchToolCalls: {\n value: () => this.#fetchToolCalls(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n fetchTools: {\n value: () => this.#fetchTools(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n refreshStandingInstructions: {\n value: () => this.#refreshStandingInstructions(this),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeStandingInstruction: {\n value: (v: string | Tokenizable) => this.#doStoreStandingInstruction(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateStandingInstruction: {\n value: (v: string | Tokenizable) => this.#doMutateStandingInstruction(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteStandingInstruction: {\n value: (v: string | Tokenizable) => this.#doDeleteStandingInstruction(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeMemory: {\n value: (v: Memory) => this.#doStoreMemory(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateMemory: {\n value: (v: Memory) => this.#doMutateMemory(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteMemory: {\n value: (id: string) => this.#doDeleteMemory(id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeRetrievable: {\n value: (v: Retrievable) => this.#doStoreRetrievable(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateRetrievable: {\n value: (v: Retrievable) => this.#doMutateRetrievable(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteRetrievable: {\n value: (id: string) => this.#doDeleteRetrievable(id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeMessage: {\n value: (v: Message) => this.#doStoreMessage(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateMessage: {\n value: (v: Message) => this.#doMutateMessage(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteMessage: {\n value: (id: string) => this.#doDeleteMessage(id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeThought: {\n value: (v: Thought) => this.#doStoreThought(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateThought: {\n value: (v: Thought) => this.#doMutateThought(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteThought: {\n value: (id: string) => this.#doDeleteThought(id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeToolCall: {\n value: (v: ToolCall) => this.#doStoreToolCall(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n mutateToolCall: {\n value: (v: ToolCall) => this.#doMutateToolCall(v),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n deleteToolCall: {\n value: (id: string) => this.#doDeleteToolCall(id),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeMediaBytes: {\n value: (id: string, bytes: ConduitBytes) => this.#storeMediaBytes(this, id, bytes),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n storeRetrievableBytes: {\n value: (id: string, bytes: ConduitBytes) => this.#storeRetrievableBytes(this, id, bytes),\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitMessage: {\n value: (content: Parameters<EmitMessageFn>[0]) => {\n void this.#hooks.runner('message').run(content)\n },\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitThought: {\n value: (content: Parameters<EmitThoughtFn>[0]) => {\n void this.#hooks.runner('thought').run(content)\n },\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitToolCall: {\n value: (content: Parameters<EmitToolCallFn>[0]) => {\n void this.#hooks.runner('toolCall').run(content)\n },\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitToolExecutionStart: {\n value: (event: Parameters<EmitToolExecutionStartFn>[0]) => {\n void this.#hooks.runner('toolExecutionStart').run(event)\n },\n enumerable: true,\n configurable: false,\n writable: false,\n },\n emitToolExecutionEnd: {\n value: (event: Parameters<EmitToolExecutionEndFn>[0]) => {\n void this.#hooks.runner('toolExecutionEnd').run(event)\n },\n enumerable: true,\n configurable: false,\n writable: false,\n },\n waitFor: {\n value: <T>(gateRaw: Parameters<OpenGateFn>[0]): Promise<T> => {\n if (!this.#waitFor) {\n return Promise.reject(new E_LLM_EXECUTION_GATE_NOT_SUPPORTED())\n }\n return this.#waitFor<T>(gateRaw)\n },\n enumerable: true,\n configurable: false,\n writable: false,\n },\n })\n }\n\n // ── Mutation helpers ──────────────────────────────────────────────────────\n\n async #doStoreStandingInstruction(v: string | Tokenizable): Promise<void> {\n const t = Tokenizable.isTokenizable(v) ? v : new Tokenizable(v)\n this.#standingInstructions.add(t)\n await this.#storeStandingInstruction(this, v)\n void this.#hooks.runner('storedStandingInstruction').run(t)\n }\n\n async #doMutateStandingInstruction(v: string | Tokenizable): Promise<void> {\n const t = Tokenizable.isTokenizable(v) ? v : new Tokenizable(v)\n this.#standingInstructions.add(t)\n await this.#mutateStandingInstruction(this, v)\n void this.#hooks.runner('mutatedStandingInstruction').run(t)\n }\n\n async #doDeleteStandingInstruction(v: string | Tokenizable): Promise<void> {\n const t = Tokenizable.isTokenizable(v) ? v : new Tokenizable(v)\n this.#standingInstructions.delete(t)\n await this.#deleteStandingInstruction(this, v)\n void this.#hooks.runner('deletedStandingInstruction').run(t)\n }\n\n async #doStoreMemory(v: Memory): Promise<void> {\n this.#turnMemories.add(v)\n await this.#storeMemory(this, v)\n void this.#hooks.runner('storedMemory').run(v)\n }\n\n async #doMutateMemory(v: Memory): Promise<void> {\n this.#turnMemories.add(v)\n await this.#mutateMemory(this, v)\n void this.#hooks.runner('mutatedMemory').run(v)\n }\n\n async #doDeleteMemory(id: string): Promise<void> {\n for (const m of this.#turnMemories) {\n if ((m as any).id === id) {\n this.#turnMemories.delete(m)\n break\n }\n }\n await this.#deleteMemory(this, id)\n void this.#hooks.runner('deletedMemory').run(id)\n }\n\n async #doStoreRetrievable(v: Retrievable): Promise<void> {\n this.#turnRetrievables.add(v)\n await this.#storeRetrievable(this, v)\n void this.#hooks.runner('storedRetrievable').run(v)\n }\n\n async #doMutateRetrievable(v: Retrievable): Promise<void> {\n this.#turnRetrievables.add(v)\n await this.#mutateRetrievable(this, v)\n void this.#hooks.runner('mutatedRetrievable').run(v)\n }\n\n async #doDeleteRetrievable(id: string): Promise<void> {\n for (const r of this.#turnRetrievables) {\n if ((r as any).id === id) {\n this.#turnRetrievables.delete(r)\n break\n }\n }\n await this.#deleteRetrievable(this, id)\n void this.#hooks.runner('deletedRetrievable').run(id)\n }\n\n async #doStoreMessage(v: Message): Promise<void> {\n this.#turnMessages.add(v)\n await this.#storeMessage(this, v)\n void this.#hooks.runner('storedMessage').run(v)\n }\n\n async #doMutateMessage(v: Message): Promise<void> {\n this.#turnMessages.add(v)\n await this.#mutateMessage(this, v)\n void this.#hooks.runner('mutatedMessage').run(v)\n }\n\n async #doDeleteMessage(id: string): Promise<void> {\n for (const m of this.#turnMessages) {\n if ((m as any).id === id) {\n this.#turnMessages.delete(m)\n break\n }\n }\n await this.#deleteMessage(this, id)\n void this.#hooks.runner('deletedMessage').run(id)\n }\n\n async #doStoreThought(v: Thought): Promise<void> {\n this.#turnThoughts.add(v)\n await this.#storeThought(this, v)\n void this.#hooks.runner('storedThought').run(v)\n }\n\n async #doMutateThought(v: Thought): Promise<void> {\n this.#turnThoughts.add(v)\n await this.#mutateThought(this, v)\n void this.#hooks.runner('mutatedThought').run(v)\n }\n\n async #doDeleteThought(id: string): Promise<void> {\n for (const t of this.#turnThoughts) {\n if ((t as any).id === id) {\n this.#turnThoughts.delete(t)\n break\n }\n }\n await this.#deleteThought(this, id)\n void this.#hooks.runner('deletedThought').run(id)\n }\n\n async #doStoreToolCall(v: ToolCall): Promise<void> {\n this.#turnToolCalls.add(v)\n const prev = this.#toolCallChecksums.get(v.checksum) ?? 0\n this.#toolCallChecksums.set(v.checksum, prev + 1)\n await this.#storeToolCall(this, v)\n void this.#hooks.runner('storedToolCall').run(v)\n }\n\n async #doMutateToolCall(v: ToolCall): Promise<void> {\n // Checksum is over tool+args, which do not change on mutation — checksum map is unchanged.\n this.#turnToolCalls.add(v)\n await this.#mutateToolCall(this, v)\n void this.#hooks.runner('mutatedToolCall').run(v)\n }\n\n async #doDeleteToolCall(id: string): Promise<void> {\n for (const tc of this.#turnToolCalls) {\n if ((tc as any).id === id) {\n this.#turnToolCalls.delete(tc)\n const count = this.#toolCallChecksums.get(tc.checksum) ?? 1\n if (count <= 1) this.#toolCallChecksums.delete(tc.checksum)\n else this.#toolCallChecksums.set(tc.checksum, count - 1)\n break\n }\n }\n await this.#deleteToolCall(this, id)\n void this.#hooks.runner('deletedToolCall').run(id)\n }\n\n // ── Internal setters (used by DispatchRunner) ─────────────────────────\n\n /** @internal Set by {@link @nhtio/adk!DispatchRunner} after construction. */\n _setDispatchId(id: string): void {\n this.#dispatchId = id\n }\n\n /** @internal Updated by {@link @nhtio/adk!DispatchRunner} on each iteration. */\n _setIteration(n: number): void {\n this.#iteration = n\n }\n\n /** @internal Accessor used by {@link @nhtio/adk!DispatchRunner} to register forwarding handlers. */\n _getHooks(): Hooks<DispatchContextHooks> {\n return this.#hooks\n }\n\n // ── Public API ────────────────────────────────────────────────────────────\n\n /**\n * Returns how many times a tool call with the given checksum has been stored in this execution.\n *\n * @remarks\n * Checksums are computed over `tool + args` (see {@link @nhtio/adk!ToolCall.checksum}). This count lets\n * the executor detect repeat invocations of the same call without scanning the full Set.\n * Returns `0` when the checksum has not been seen.\n *\n * @param checksum - The `ToolCall.checksum` value to look up.\n */\n toolCallCount(checksum: string): number {\n return this.#toolCallChecksums.get(checksum) ?? 0\n }\n\n /**\n * Signals successful completion of this execution.\n *\n * @remarks\n * Sets the context's internal signal flag. The {@link @nhtio/adk!DispatchRunner} reads the flag at the\n * end of each iteration to decide whether to loop or exit. Calling `ack()` does NOT abort the\n * current iteration — the current pipeline and flush complete first.\n *\n * @throws {@link @nhtio/adk!E_LLM_EXECUTION_ALREADY_SIGNALLED} when the context has already been signalled\n * (whether via `ack()` or `nack()`).\n */\n ack(): void {\n if (this.#signalled !== undefined) {\n throw new E_LLM_EXECUTION_ALREADY_SIGNALLED()\n }\n this.#signalled = 'ack'\n // Sync iteration — handlers must observe each other's side-effects in registration order\n // (e.g. ToolRegistry.bindContext relies on this for ephemeral pruning). The hook bus is\n // unsuitable here because its `await` between handlers reorders sync side-effects via\n // microtask queuing.\n for (const handler of this.#ackHandlers) {\n try {\n handler()\n } catch {\n // Swallow individual handler errors so one misbehaving subscriber can't prevent the\n // others from running. Ack itself has already succeeded.\n }\n }\n }\n\n /**\n * Registers a handler to run when this context completes successfully via {@link ack}.\n *\n * @remarks\n * The handler does NOT fire on {@link nack} — failed executor runs should leave any\n * ack-tied subscriptions alone so the consumer can inspect what was registered when\n * debugging the failure. Returns an unsubscribe function; subscriptions are short-lived\n * and die with the context regardless.\n *\n * The canonical consumer is `ToolRegistry.bindContext(ctx)`, which uses this hook to drop\n * ephemeral tools (notably forged artifact-query tools from `SpooledArtifact.forgeTools(ctx)`)\n * at ctx-completion. Consumers may also register custom handlers here for any per-executor\n * cleanup.\n *\n * @param handler - Callback invoked when `ack()` is called.\n * @returns An unsubscribe function that removes the handler.\n *\n * @see {@link @nhtio/adk!ToolRegistry.bindContext}\n * @see {@link @nhtio/adk!SpooledArtifact.forgeTools}\n */\n onAck(handler: () => void): () => void {\n this.#ackHandlers.add(handler)\n return () => {\n this.#ackHandlers.delete(handler)\n }\n }\n\n /**\n * Signals failed completion of this execution, optionally with an error.\n *\n * @remarks\n * Sets the context's internal signal flag and stores the error. The {@link @nhtio/adk!DispatchRunner}\n * reads the flag at the end of each iteration and surfaces the error via the `dispatchEnd`\n * observability payload and as the rejection reason of `dispatch()`. Calling `nack()` does NOT\n * abort the current iteration — the current pipeline and flush complete first.\n *\n * @param error - Optional error describing the failure. If omitted, a generic Error is used.\n * @throws {@link @nhtio/adk!E_LLM_EXECUTION_ALREADY_SIGNALLED} when the context has already been signalled.\n */\n nack(error?: Error): void {\n if (this.#signalled !== undefined) {\n throw new E_LLM_EXECUTION_ALREADY_SIGNALLED()\n }\n this.#signalled = 'nack'\n this.#nackError = error ?? new Error('LLM execution was nacked without an explicit error.')\n }\n\n /**\n * Returns `true` if `value` is a {@link DispatchContext} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety. The ADK does not export the\n * `DispatchContext` class itself as a constructable value — use this guard plus the\n * {@link DispatchContext} type for runtime detection and TypeScript narrowing.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link DispatchContext} instance.\n */\n public static isDispatchContext(value: unknown): value is DispatchContext {\n return isInstanceOf(value, 'DispatchContext', DispatchContext)\n }\n\n // ── declare readonly (TypeScript public surface) ──────────────────────────\n\n /** Unique identifier for this execution context, generated as UUIDv6 at construction time. */\n declare readonly id: string\n /** Stable identifier for the dispatch this context belongs to; set by `DispatchRunner`. */\n declare readonly dispatchId: string\n /** 0-based iteration count within the current dispatch; updated by `DispatchRunner`. */\n declare readonly iteration: number\n /** `true` when the abort controller signal has fired. */\n declare readonly aborted: boolean\n /** The `AbortSignal` from the execution's `AbortController`. */\n declare readonly abortSignal: AbortSignal\n /**\n * Aborts the dispatch's `AbortController` with the supplied reason. Middleware should call this\n * when refusing to proceed — the runner short-circuits cleanly, `dispatchEnd.status` resolves\n * to `'aborted'`, and no `error` event is emitted.\n */\n declare readonly abort: (reason?: unknown) => void\n /** `true` once {@link DispatchContext.ack} or {@link DispatchContext.nack} has been called. */\n declare readonly isSignalled: boolean\n /** `true` when the context was signalled via {@link DispatchContext.ack}. */\n declare readonly isAcked: boolean\n /** The error stored by {@link DispatchContext.nack}, or `undefined` if not nacked. */\n declare readonly nackError: Error | undefined\n /** Arbitrary key-value store for cross-step state. */\n declare readonly stash: Registry\n /** The system prompt for this execution. */\n declare readonly systemPrompt: Tokenizable\n /** Standing instructions for this execution, in insertion order. */\n declare readonly standingInstructions: Set<Tokenizable>\n /** Memories loaded for this execution. */\n declare readonly turnMemories: Set<Memory>\n /** Retrievable records loaded for this execution. */\n declare readonly turnRetrievables: Set<Retrievable>\n /** Messages loaded for this execution. */\n declare readonly turnMessages: Set<Message>\n /** Thoughts loaded for this execution. */\n declare readonly turnThoughts: Set<Thought>\n /** Tool calls loaded for this execution. */\n declare readonly turnToolCalls: Set<ToolCall>\n /** Tool registry for this execution. */\n declare readonly tools: ToolRegistry\n /** Fetches memories; delegates to the callback supplied at construction. */\n declare readonly fetchMemories: () => Memory[] | Promise<Memory[]>\n /** Fetches retrievable records; delegates to the callback supplied at construction. */\n declare readonly fetchRetrievables: () => Retrievable[] | Promise<Retrievable[]>\n /** Fetches messages; delegates to the callback supplied at construction. */\n declare readonly fetchMessages: () => Message[] | Promise<Message[]>\n /** Fetches thoughts; delegates to the callback supplied at construction. */\n declare readonly fetchThoughts: () => Thought[] | Promise<Thought[]>\n /** Fetches tool calls; delegates to the callback supplied at construction. */\n declare readonly fetchToolCalls: () => ToolCall[] | Promise<ToolCall[]>\n /** Fetches tools; delegates to the callback supplied at construction. */\n declare readonly fetchTools: () => Tool[] | Promise<Tool[]>\n /** Refreshes and returns standing instructions. */\n declare readonly refreshStandingInstructions: () =>\n | (string | Tokenizable)[]\n | Promise<(string | Tokenizable)[]>\n /** Stores a new standing instruction in the local Set and persistence layer. */\n declare readonly storeStandingInstruction: (v: string | Tokenizable) => Promise<void>\n /** Updates an existing standing instruction in the local Set and persistence layer. */\n declare readonly mutateStandingInstruction: (v: string | Tokenizable) => Promise<void>\n /** Removes a standing instruction from the local Set and persistence layer. */\n declare readonly deleteStandingInstruction: (v: string | Tokenizable) => Promise<void>\n /** Stores a new memory in the local Set and persistence layer. */\n declare readonly storeMemory: (v: Memory) => Promise<void>\n /** Updates an existing memory in the local Set and persistence layer. */\n declare readonly mutateMemory: (v: Memory) => Promise<void>\n /** Removes a memory from the local Set and persistence layer by ID. */\n declare readonly deleteMemory: (id: string) => Promise<void>\n /** Stores a new retrievable record in the local Set and persistence layer. */\n declare readonly storeRetrievable: (v: Retrievable) => Promise<void>\n /** Updates an existing retrievable record in the local Set and persistence layer. */\n declare readonly mutateRetrievable: (v: Retrievable) => Promise<void>\n /** Removes a retrievable record from the local Set and persistence layer by ID. */\n declare readonly deleteRetrievable: (id: string) => Promise<void>\n /** Stores a new message in the local Set and persistence layer. */\n declare readonly storeMessage: (v: Message) => Promise<void>\n /** Updates an existing message in the local Set and persistence layer. */\n declare readonly mutateMessage: (v: Message) => Promise<void>\n /** Removes a message from the local Set and persistence layer by ID. */\n declare readonly deleteMessage: (id: string) => Promise<void>\n /** Stores a new thought in the local Set and persistence layer. */\n declare readonly storeThought: (v: Thought) => Promise<void>\n /** Updates an existing thought in the local Set and persistence layer. */\n declare readonly mutateThought: (v: Thought) => Promise<void>\n /** Removes a thought from the local Set and persistence layer by ID. */\n declare readonly deleteThought: (id: string) => Promise<void>\n /** Stores a new tool call in the local Set and persistence layer. */\n declare readonly storeToolCall: (v: ToolCall) => Promise<void>\n /** Updates an existing tool call in the local Set and persistence layer. */\n declare readonly mutateToolCall: (v: ToolCall) => Promise<void>\n /** Removes a tool call from the local Set and persistence layer by ID. */\n declare readonly deleteToolCall: (id: string) => Promise<void>\n /**\n * Persists tool-generated media bytes into consumer storage and returns a {@link @nhtio/adk!MediaReader}.\n *\n * @remarks\n * This is a low-level persistence conduit, NOT a mutation: it does not add to `turnMessages`/\n * `turnToolCalls` or fire a `stored*` hook. The handler builds a {@link @nhtio/adk!Media} from the\n * returned reader (`Media.toolGenerated({ reader })`) and stores the owning primitive — a\n * {@link @nhtio/adk!Message} attachment or {@link @nhtio/adk!ToolCall} result — via the relevant\n * `store*` method separately. Persisting bytes without storing the primitive means the framework\n * never sees the media.\n */\n declare readonly storeMediaBytes: (\n id: string,\n bytes: ConduitBytes\n ) => MediaReader | Promise<MediaReader>\n /**\n * Persists extracted retrievable text bytes into consumer storage and returns a\n * {@link @nhtio/adk!SpoolReader}.\n *\n * @remarks\n * Low-level persistence conduit, same posture as {@link DispatchContext.storeMediaBytes}: returns a\n * value, touches no Sets, fires no hook. Wrap the reader in a {@link @nhtio/adk!SpooledArtifact} and\n * pass it as `Retrievable.content`, then persist the record via {@link DispatchContext.storeRetrievable}.\n */\n declare readonly storeRetrievableBytes: (\n id: string,\n bytes: ConduitBytes\n ) => SpoolReader | Promise<SpoolReader>\n /** Emits a `message` hook; fires registered handlers synchronously. */\n declare readonly emitMessage: EmitMessageFn\n /** Emits a `thought` hook; fires registered handlers synchronously. */\n declare readonly emitThought: EmitThoughtFn\n /** Emits a `toolCall` hook; fires registered handlers synchronously. */\n declare readonly emitToolCall: EmitToolCallFn\n /** Emits a `toolExecutionStart` hook; fires registered handlers synchronously. */\n declare readonly emitToolExecutionStart: EmitToolExecutionStartFn\n /** Emits a `toolExecutionEnd` hook; fires registered handlers synchronously. */\n declare readonly emitToolExecutionEnd: EmitToolExecutionEndFn\n /** Opens a gate and suspends until it resolves, rejects, times out, or is aborted. */\n declare readonly waitFor: OpenGateFn\n}\n","import { DateTime } from 'luxon'\nimport { sha256 } from 'js-sha256'\nimport { v6 as uuidv6 } from 'uuid'\nimport { Hooks } from '@nhtio/hooks'\nimport { validator } from '@nhtio/validation'\nimport { Middleware } from '@nhtio/middleware'\nimport { validateOrThrow } from './utils/validation'\nimport { isError, isInstanceOf } from './utils/guards'\nimport { canonicalStringify } from './utils/canonical_json'\nimport { TurnContext } from './contracts/turn_runner_context'\nimport { DispatchContext } from './contracts/dispatch_context'\nimport {\n E_INVALID_LLM_DISPATCH_INPUT,\n E_DISPATCH_PIPELINE_ERROR,\n E_LLM_EXECUTION_EXECUTOR_ERROR,\n E_PIPELINE_SHORT_CIRCUITED,\n} from './exceptions/runtime'\nimport type { Memory } from './classes/memory'\nimport type { Message } from './classes/message'\nimport type { Thought } from './classes/thought'\nimport type { ToolCall } from './classes/tool_call'\nimport type { Retrievable } from './classes/retrievable'\nimport type { Tokenizable } from './classes/tokenizable'\nimport type { BaseException } from './classes/base_exception'\nimport type { Runner as MiddlewareRunner } from '@nhtio/middleware'\nimport type { RawDispatchContext } from './contracts/dispatch_context'\nimport type { TurnStreamableContent, TurnToolCallContent } from './types/turn_runner'\nimport type {\n DispatchPipelineMiddlewareFn,\n DispatchExecutorFn,\n DispatchExecutorHelpers,\n DispatchExecutorLogChannel,\n DispatchExecutorLogEntry,\n DispatchExecutorLogLevel,\n LogEvent,\n ContextDelta,\n DispatchRunnerFunctionalHooks,\n DispatchRunnerObservabilityHooks,\n DispatchRunnerFunctionalHookRegistrations,\n DispatchRunnerObservabilityHookRegistrations,\n} from './types/dispatch_runner'\n\n/**\n * Plain input object supplied to {@link DispatchRunner.dispatch}.\n *\n * @remarks\n * Exactly one of `source` or `raw` is required:\n *\n * - `source` — switches to the **derived path**. The runner snapshots primitives from the\n * provided {@link @nhtio/adk!TurnContext}, wires all fetch/refresh/mutation callbacks to delegate to it,\n * forwards emits back to its buses, and bubbles mutations to its Sets at the end of every\n * iteration.\n *\n * - `raw` — switches to the **standalone path**. The runner constructs an {@link @nhtio/adk!DispatchContext}\n * directly from the provided raw input. No parent relationship exists; mutations are not bubbled.\n *\n * The `executor` is the user-provided callback that performs the actual LLM API call between the\n * input and output middleware pipelines on every iteration.\n */\nexport interface RawDispatchRunnerInput {\n /** Source {@link @nhtio/adk!TurnContext} to derive the execution context from. Mutually exclusive with `raw`. */\n source?: TurnContext\n /** Raw input for a standalone {@link @nhtio/adk!DispatchContext}. Mutually exclusive with `source`. */\n raw?: Omit<RawDispatchContext, 'hooks'>\n /** User-provided callback that makes the LLM API call. Invoked between input and output pipelines on every iteration. */\n executor: DispatchExecutorFn\n /** Input middleware functions, executed in order before the executor on every iteration. */\n turnInputPipeline?: DispatchPipelineMiddlewareFn[]\n /** Output middleware functions, executed in order after the executor on every iteration. */\n turnOutputPipeline?: DispatchPipelineMiddlewareFn[]\n /** Optional functional hook registrations: message, thought, toolCall. */\n hooks?: DispatchRunnerFunctionalHookRegistrations\n /** Optional observability hook registrations: lifecycle events + tool execution + error. */\n observers?: DispatchRunnerObservabilityHookRegistrations\n}\n\nconst dispatchInputSchema = validator.object<RawDispatchRunnerInput>({\n source: validator\n .any()\n .custom((value, helpers) => {\n if (value === undefined) return value\n if (isInstanceOf(value, 'TurnContext', TurnContext)) return value\n return helpers.error('any.invalid')\n })\n .optional(),\n raw: validator.object().unknown(true).optional(),\n executor: validator.function().required(),\n turnInputPipeline: validator.array().items(validator.function()).default([]),\n turnOutputPipeline: validator.array().items(validator.function()).default([]),\n hooks: validator.object().optional(),\n observers: validator.object().optional(),\n})\n\n/**\n * Orchestrates a single LLM execution dispatch — input pipeline → executor → output pipeline —\n * looped until middleware/executor signals completion via {@link @nhtio/adk!DispatchContext.ack} /\n * {@link @nhtio/adk!DispatchContext.nack} or the abort signal fires.\n *\n * @remarks\n * `DispatchRunner` has a private constructor and is invoked via the static `dispatch()`\n * method. Each dispatch creates a fresh single-use runner that is garbage-collected after the\n * call completes — matching the `@nhtio/hooks` GC rationale already baked into the context.\n *\n * The runner owns the relationship between an {@link @nhtio/adk!DispatchContext} and its parent\n * {@link @nhtio/adk!TurnContext} (when given a source). It subscribes to the context's mutation hooks,\n * queues `ContextDelta` entries, and flushes them to the parent's Sets at the end of every\n * iteration. Emits propagate from the context's hooks → the runner's hooks → (optionally) the\n * parent `TurnContext`'s emit methods → the `TurnRunner`'s buses.\n *\n * Two hook buses, mirroring `TurnRunner`'s pattern:\n *\n * - **Functional** (`hooks`): `message`, `thought`, `toolCall` — pipeline-affecting events\n * - **Observability** (`observers`): `iterationStart`, `iterationEnd`, `dispatchStart`,\n * `dispatchEnd`, `error`, `toolExecutionStart`, `toolExecutionEnd` — instrumentation only\n *\n * The runner has no `maxIterations`, no `maxToolCallChecksumRepeats`. Implementers use the\n * primitives — `ctx.iteration`, `ctx.toolCallCount(checksum)`, `ctx.ack()`, `ctx.nack()`,\n * `ctx.abortSignal` — to build any termination bounds they need in their own middleware.\n */\n/**\n * Module-private token gating direct construction of {@link DispatchRunner}. Callers must use\n * {@link DispatchRunner.dispatch}; the symbol is not exported, so external code cannot satisfy\n * the guard at runtime.\n */\nconst CONSTRUCT_TOKEN = Symbol('DispatchRunner.construct')\n\nexport class DispatchRunner {\n #functionalHooks: Hooks<DispatchRunnerFunctionalHooks>\n #observabilityHooks: Hooks<DispatchRunnerObservabilityHooks>\n // The Middleware holders are built once; a FRESH Runner is derived from each\n // per dispatch iteration. A Runner is single-use — its internal cursor\n // (#currentIndex) is never reset by run() — so reusing one Runner across\n // iterations silently no-ops every pipeline after the first. The dispatch loop\n // runs the input/output pipelines once PER iteration, so it must mint a new\n // Runner each time or the citation/quality gate (and all output middleware)\n // would only ever fire on iteration 0.\n #inputPipeline: Middleware<DispatchPipelineMiddlewareFn>\n #outputPipeline: Middleware<DispatchPipelineMiddlewareFn>\n #sourceCtx: TurnContext | undefined\n #deltaQueue: ContextDelta[]\n\n constructor(\n token: typeof CONSTRUCT_TOKEN,\n sourceCtx: TurnContext | undefined,\n turnInputPipeline: DispatchPipelineMiddlewareFn[],\n turnOutputPipeline: DispatchPipelineMiddlewareFn[],\n hooks: DispatchRunnerFunctionalHookRegistrations | undefined,\n observers: DispatchRunnerObservabilityHookRegistrations | undefined\n ) {\n if (token !== CONSTRUCT_TOKEN) {\n throw new E_INVALID_LLM_DISPATCH_INPUT()\n }\n this.#sourceCtx = sourceCtx\n this.#deltaQueue = []\n this.#functionalHooks = new Hooks<DispatchRunnerFunctionalHooks>()\n this.#observabilityHooks = new Hooks<DispatchRunnerObservabilityHooks>()\n\n const inputPipeline = new Middleware<DispatchPipelineMiddlewareFn>()\n const outputPipeline = new Middleware<DispatchPipelineMiddlewareFn>()\n const wrap =\n (fn: DispatchPipelineMiddlewareFn): DispatchPipelineMiddlewareFn =>\n (ctx, next) => {\n // Skip downstream user middlewares once an abort has been signalled. The\n // wrapper still calls next() so the pipeline reaches its terminal resolver\n // (keeping the short-circuit detector quiet); the original middleware body\n // does not run, so it has nothing to clean up.\n if (ctx.aborted) return next()\n return fn(ctx, next)\n }\n for (const fn of turnInputPipeline) inputPipeline.add(wrap(fn))\n for (const fn of turnOutputPipeline) outputPipeline.add(wrap(fn))\n // Hold the Middleware; derive a fresh Runner per iteration (see field docs).\n this.#inputPipeline = inputPipeline\n this.#outputPipeline = outputPipeline\n\n if (hooks) {\n for (const key of Object.keys(hooks) as (keyof DispatchRunnerFunctionalHooks)[]) {\n const entry = hooks[key]\n if (!entry) continue\n const handlers = Array.isArray(entry) ? entry : [entry]\n for (const h of handlers) this.#functionalHooks.add(key, h as any)\n }\n }\n if (observers) {\n for (const key of Object.keys(observers) as (keyof DispatchRunnerObservabilityHooks)[]) {\n const entry = observers[key]\n if (!entry) continue\n const handlers = Array.isArray(entry) ? entry : [entry]\n for (const h of handlers) this.#observabilityHooks.add(key, h as any)\n }\n }\n }\n\n /**\n * Returns `true` if `value` is a {@link DispatchRunner} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link DispatchRunner} instance.\n */\n public static isDispatchRunner(value: unknown): value is DispatchRunner {\n return isInstanceOf(value, 'DispatchRunner', DispatchRunner)\n }\n\n /**\n * Dispatches a single LLM execution.\n *\n * @remarks\n * Constructs an {@link @nhtio/adk!DispatchContext} (derived from `source` or from `raw`), runs the\n * iteration loop, and resolves when middleware/executor signals completion via `ctx.ack()` or\n * the abort signal fires. Rejects with the nack error when middleware/executor calls\n * `ctx.nack(err)`. Pipeline and executor errors are wrapped, surfaced on the observability\n * `error` hook, and re-thrown.\n *\n * @param input - The dispatch input. Provide either `source` (derived path) or `raw` (standalone).\n * @throws {@link @nhtio/adk!E_INVALID_LLM_DISPATCH_INPUT} when the input does not satisfy validation, or\n * when neither `source` nor `raw` is provided, or when both are provided.\n */\n public static async dispatch(input: RawDispatchRunnerInput): Promise<void> {\n let resolved: RawDispatchRunnerInput & {\n turnInputPipeline: DispatchPipelineMiddlewareFn[]\n turnOutputPipeline: DispatchPipelineMiddlewareFn[]\n }\n try {\n resolved = validateOrThrow(dispatchInputSchema, input, true) as typeof resolved\n } catch (err) {\n throw new E_INVALID_LLM_DISPATCH_INPUT({ cause: isError(err) ? err : undefined })\n }\n\n if (!resolved.source && !resolved.raw) {\n throw new E_INVALID_LLM_DISPATCH_INPUT()\n }\n if (resolved.source && resolved.raw) {\n throw new E_INVALID_LLM_DISPATCH_INPUT()\n }\n\n const runner = new DispatchRunner(\n CONSTRUCT_TOKEN,\n resolved.source,\n resolved.turnInputPipeline,\n resolved.turnOutputPipeline,\n resolved.hooks,\n resolved.observers\n )\n\n const llmCtx = runner.#buildContext(resolved.source, resolved.raw)\n runner.#wireContextHooks(llmCtx)\n\n await runner.#runDispatch(llmCtx, resolved.executor)\n }\n\n // ── Context construction ──────────────────────────────────────────────────\n\n #buildContext(\n source: TurnContext | undefined,\n raw: Omit<RawDispatchContext, 'hooks'> | undefined\n ): DispatchContext {\n if (source) {\n const ac = new AbortController()\n source.abortSignal.addEventListener('abort', () => ac.abort(), { once: true })\n\n const builtRaw: RawDispatchContext = {\n turnAbortController: ac,\n stash: source.stash.all(),\n systemPrompt: source.systemPrompt,\n standingInstructions: [...source.standingInstructions],\n memories: [...source.turnMemories],\n retrievables: [...source.turnRetrievables],\n messages: [...source.turnMessages],\n thoughts: [...source.turnThoughts],\n toolCalls: [...source.turnToolCalls],\n tools: source.tools.all(),\n fetchMemories: () => source.fetchMemories(),\n fetchRetrievables: () => source.fetchRetrievables(),\n fetchMessages: () => source.fetchMessages(),\n fetchThoughts: () => source.fetchThoughts(),\n fetchToolCalls: () => source.fetchToolCalls(),\n fetchTools: () => source.fetchTools(),\n refreshStandingInstructions: () => source.refreshStandingInstructions(),\n storeStandingInstruction: (_c, v) => source.storeStandingInstruction(v),\n mutateStandingInstruction: (_c, v) => source.mutateStandingInstruction(v),\n deleteStandingInstruction: (_c, v) => source.deleteStandingInstruction(v),\n storeMemory: (_c, v) => source.storeMemory(v),\n mutateMemory: (_c, v) => source.mutateMemory(v),\n deleteMemory: (_c, id) => source.deleteMemory(id),\n storeRetrievable: (_c, v) => source.storeRetrievable(v),\n mutateRetrievable: (_c, v) => source.mutateRetrievable(v),\n deleteRetrievable: (_c, id) => source.deleteRetrievable(id),\n storeMessage: (_c, v) => source.storeMessage(v),\n mutateMessage: (_c, v) => source.mutateMessage(v),\n deleteMessage: (_c, id) => source.deleteMessage(id),\n storeThought: (_c, v) => source.storeThought(v),\n mutateThought: (_c, v) => source.mutateThought(v),\n deleteThought: (_c, id) => source.deleteThought(id),\n storeToolCall: (_c, v) => source.storeToolCall(v),\n mutateToolCall: (_c, v) => source.mutateToolCall(v),\n deleteToolCall: (_c, id) => source.deleteToolCall(id),\n storeMediaBytes: (_c, id, bytes) => source.storeMediaBytes(id, bytes),\n storeRetrievableBytes: (_c, id, bytes) => source.storeRetrievableBytes(id, bytes),\n waitFor: source.waitFor,\n }\n return new DispatchContext(builtRaw)\n }\n\n // Standalone path — runner does not pass hooks (it registers its own forwarders below).\n return new DispatchContext(raw as RawDispatchContext)\n }\n\n // ── Wire forwarding handlers from ctx hooks to runner hooks ───────────────\n\n #wireContextHooks(llmCtx: DispatchContext): void {\n const ctxHooks = llmCtx._getHooks()\n\n // Functional forwarders: ctx → runner (functional) → (if source) → TurnContext\n ctxHooks.add('message', (c) => {\n void this.#functionalHooks.runner('message').run(c)\n if (this.#sourceCtx) this.#sourceCtx.emitMessage(c)\n })\n ctxHooks.add('thought', (c) => {\n void this.#functionalHooks.runner('thought').run(c)\n if (this.#sourceCtx) this.#sourceCtx.emitThought(c)\n })\n ctxHooks.add('toolCall', (c) => {\n void this.#functionalHooks.runner('toolCall').run(c)\n if (this.#sourceCtx) this.#sourceCtx.emitToolCall(c)\n })\n\n // Observability forwarders for tool execution lifecycle\n ctxHooks.add('toolExecutionStart', (e) => {\n void this.#observabilityHooks.runner('toolExecutionStart').run(e)\n if (this.#sourceCtx) this.#sourceCtx.emitToolExecutionStart(e)\n })\n ctxHooks.add('toolExecutionEnd', (e) => {\n void this.#observabilityHooks.runner('toolExecutionEnd').run(e)\n if (this.#sourceCtx) this.#sourceCtx.emitToolExecutionEnd(e)\n })\n\n // Mutation hooks → push to internal delta queue (only meaningful when source exists,\n // but registering unconditionally keeps the API uniform; queue is drained only in derived)\n ctxHooks.add('storedStandingInstruction', (v) => {\n this.#deltaQueue.push({ op: 'store', type: 'standingInstruction', value: v })\n })\n ctxHooks.add('mutatedStandingInstruction', (v) => {\n this.#deltaQueue.push({ op: 'mutate', type: 'standingInstruction', value: v })\n })\n ctxHooks.add('deletedStandingInstruction', (v) => {\n this.#deltaQueue.push({ op: 'delete', type: 'standingInstruction', value: v })\n })\n ctxHooks.add('storedMemory', (v) => {\n this.#deltaQueue.push({ op: 'store', type: 'memory', value: v })\n })\n ctxHooks.add('mutatedMemory', (v) => {\n this.#deltaQueue.push({ op: 'mutate', type: 'memory', value: v })\n })\n ctxHooks.add('deletedMemory', (id) => {\n this.#deltaQueue.push({ op: 'delete', type: 'memory', value: id })\n })\n ctxHooks.add('storedRetrievable', (v) => {\n this.#deltaQueue.push({ op: 'store', type: 'retrievable', value: v })\n })\n ctxHooks.add('mutatedRetrievable', (v) => {\n this.#deltaQueue.push({ op: 'mutate', type: 'retrievable', value: v })\n })\n ctxHooks.add('deletedRetrievable', (id) => {\n this.#deltaQueue.push({ op: 'delete', type: 'retrievable', value: id })\n })\n ctxHooks.add('storedMessage', (v) => {\n this.#deltaQueue.push({ op: 'store', type: 'message', value: v })\n })\n ctxHooks.add('mutatedMessage', (v) => {\n this.#deltaQueue.push({ op: 'mutate', type: 'message', value: v })\n })\n ctxHooks.add('deletedMessage', (id) => {\n this.#deltaQueue.push({ op: 'delete', type: 'message', value: id })\n })\n ctxHooks.add('storedThought', (v) => {\n this.#deltaQueue.push({ op: 'store', type: 'thought', value: v })\n })\n ctxHooks.add('mutatedThought', (v) => {\n this.#deltaQueue.push({ op: 'mutate', type: 'thought', value: v })\n })\n ctxHooks.add('deletedThought', (id) => {\n this.#deltaQueue.push({ op: 'delete', type: 'thought', value: id })\n })\n ctxHooks.add('storedToolCall', (v) => {\n this.#deltaQueue.push({ op: 'store', type: 'toolCall', value: v })\n })\n ctxHooks.add('mutatedToolCall', (v) => {\n this.#deltaQueue.push({ op: 'mutate', type: 'toolCall', value: v })\n })\n ctxHooks.add('deletedToolCall', (id) => {\n this.#deltaQueue.push({ op: 'delete', type: 'toolCall', value: id })\n })\n }\n\n // ── Helper builder ────────────────────────────────────────────────────────\n\n /**\n * Constructs an {@link @nhtio/adk!DispatchExecutorHelpers} instance bound to a single dispatch.\n *\n * @remarks\n * Per-id stream state lives on closure-captured `Map`s, so it persists across iterations of\n * the dispatch but cannot leak between dispatches (the runner itself is single-use and\n * garbage-collected after `dispatch()` returns).\n */\n #buildHelpers(ctx: DispatchContext): DispatchExecutorHelpers {\n const observabilityHooks = this.#observabilityHooks\n const makeLogEmitter =\n (level: DispatchExecutorLogLevel) =>\n (entry: DispatchExecutorLogEntry): void => {\n const event: LogEvent = {\n dispatchId: ctx.dispatchId,\n iteration: ctx.iteration,\n emittedAt: DateTime.now(),\n level,\n kind: entry.kind,\n message: entry.message,\n ...(entry.payload !== undefined ? { payload: entry.payload } : {}),\n }\n void observabilityHooks.runner('log').run(event)\n }\n const log: DispatchExecutorLogChannel = {\n trace: makeLogEmitter('trace'),\n debug: makeLogEmitter('debug'),\n info: makeLogEmitter('info'),\n warn: makeLogEmitter('warn'),\n error: makeLogEmitter('error'),\n }\n\n const messageStreams = new Map<\n string,\n { full: string; createdAt: DateTime; isComplete: boolean }\n >()\n const thoughtStreams = new Map<\n string,\n { full: string; createdAt: DateTime; isComplete: boolean }\n >()\n const toolCallStreams = new Map<\n string,\n {\n tool?: string\n args?: unknown\n checksum?: string\n results?: unknown\n isError: boolean\n isComplete: boolean\n createdAt: DateTime\n }\n >()\n\n const buildStream = (\n store: Map<string, { full: string; createdAt: DateTime; isComplete: boolean }>,\n id: string,\n deltaText: string,\n isComplete: boolean\n ): TurnStreamableContent => {\n let entry = store.get(id)\n const now = DateTime.now()\n if (!entry) {\n entry = { full: '', createdAt: now, isComplete: false }\n store.set(id, entry)\n }\n if (entry.isComplete) {\n throw new Error(`stream \"${id}\" is already complete; further chunks are not accepted`)\n }\n entry.full = entry.full + deltaText\n entry.isComplete = isComplete\n return {\n id,\n createdAt: entry.createdAt,\n updatedAt: now,\n full: entry.full,\n aDelta: deltaText,\n isComplete,\n ...(isComplete ? { completedAt: now } : {}),\n }\n }\n\n return {\n reportMessage: (id, deltaText, opts) => {\n const isComplete = opts?.isComplete ?? false\n ctx.emitMessage(buildStream(messageStreams, id, deltaText, isComplete))\n },\n reportThought: (id, deltaText, opts) => {\n const isComplete = opts?.isComplete ?? false\n ctx.emitThought(buildStream(thoughtStreams, id, deltaText, isComplete))\n },\n reportToolCall: (id, partial) => {\n let entry = toolCallStreams.get(id)\n const now = DateTime.now()\n if (!entry) {\n entry = { isError: false, isComplete: false, createdAt: now }\n toolCallStreams.set(id, entry)\n }\n if (entry.isComplete) {\n throw new Error(`tool call \"${id}\" is already complete; further updates are not accepted`)\n }\n if (partial.tool !== undefined) entry.tool = partial.tool\n if (partial.args !== undefined) entry.args = partial.args\n if (partial.results !== undefined) entry.results = partial.results\n if (partial.isError !== undefined) entry.isError = partial.isError\n if (partial.isComplete !== undefined) entry.isComplete = partial.isComplete\n\n // Compute checksum once tool + args are both set (or recompute if either changed)\n if (entry.tool !== undefined && entry.args !== undefined) {\n entry.checksum = sha256(canonicalStringify({ tool: entry.tool, args: entry.args }))\n }\n\n const content: TurnToolCallContent = {\n id,\n tool: entry.tool ?? '',\n args: entry.args,\n checksum: entry.checksum ?? '',\n createdAt: entry.createdAt,\n updatedAt: now,\n isComplete: entry.isComplete,\n isError: entry.isError,\n ...(entry.results !== undefined ? { results: entry.results } : {}),\n ...(entry.isComplete ? { completedAt: now } : {}),\n }\n ctx.emitToolCall(content)\n },\n log,\n }\n }\n\n // ── Iteration loop ────────────────────────────────────────────────────────\n\n async #runDispatch(llmCtx: DispatchContext, executor: DispatchExecutorFn): Promise<void> {\n const dispatchId = uuidv6()\n llmCtx._setDispatchId(dispatchId)\n\n const dispatchStartedAt = DateTime.now()\n void this.#observabilityHooks\n .runner('dispatchStart')\n .run({ dispatchId, startedAt: dispatchStartedAt })\n\n // Helpers are constructed once per dispatch so per-id streaming state is preserved across\n // iterations, and garbage-collected with the runner so cross-dispatch state can't leak.\n const helpers = this.#buildHelpers(llmCtx)\n\n let iteration = 0\n let dispatchError: Error | undefined\n\n try {\n while (!llmCtx.aborted && !llmCtx.isSignalled) {\n llmCtx._setIteration(iteration)\n const iterationStartedAt = DateTime.now()\n void this.#observabilityHooks\n .runner('iterationStart')\n .run({ dispatchId, iteration, startedAt: iterationStartedAt })\n\n await this.#runPipeline(this.#inputPipeline.runner(), llmCtx, 'input')\n if (llmCtx.aborted || llmCtx.isSignalled) {\n // ack mid-iteration flushes parent-mirror deltas accumulated so far;\n // nack / abort discards them so a partial iteration cannot leak\n // partial writes into the parent turn.\n if (llmCtx.isAcked && !llmCtx.aborted) {\n await this.#flush()\n } else {\n this.#deltaQueue.length = 0\n }\n break\n }\n\n try {\n await executor(llmCtx, helpers)\n } catch (err) {\n if (this.#isAbortError(err)) {\n this.#deltaQueue.length = 0\n break\n }\n const wrapped = new E_LLM_EXECUTION_EXECUTOR_ERROR({\n cause: isError(err) ? err : undefined,\n })\n void this.#observabilityHooks.runner('error').run(wrapped as unknown as BaseException)\n this.#deltaQueue.length = 0\n throw wrapped\n }\n\n if (llmCtx.aborted || llmCtx.isSignalled) {\n if (llmCtx.isAcked && !llmCtx.aborted) {\n await this.#flush()\n } else {\n this.#deltaQueue.length = 0\n }\n break\n }\n\n await this.#runPipeline(this.#outputPipeline.runner(), llmCtx, 'output')\n await this.#flush()\n\n const iterationEndedAt = DateTime.now()\n void this.#observabilityHooks.runner('iterationEnd').run({\n dispatchId,\n iteration,\n startedAt: iterationStartedAt,\n endedAt: iterationEndedAt,\n durationMs: iterationEndedAt.diff(iterationStartedAt).milliseconds,\n })\n\n iteration++\n }\n } catch (err) {\n dispatchError = isError(err) ? err : new Error(String(err))\n }\n\n const status: DispatchEndStatus = dispatchError\n ? 'nack'\n : llmCtx.nackError\n ? 'nack'\n : llmCtx.isAcked\n ? 'ack'\n : 'aborted'\n const finalError = dispatchError ?? llmCtx.nackError\n\n // Parity with the thrown-executor-error path: when the dispatch ends with\n // a nack whose cause we have not already emitted (i.e. `ctx.nack(error)`\n // was called explicitly, rather than the executor throwing), surface the\n // error on the observability `error` bus so observers see one unified\n // error stream regardless of how the nack was reached.\n if (!dispatchError && llmCtx.nackError) {\n const nackErr = llmCtx.nackError\n const wrapped = isInstanceOf(nackErr, 'BaseException')\n ? (nackErr as unknown as BaseException)\n : (new E_LLM_EXECUTION_EXECUTOR_ERROR({\n cause: isError(nackErr) ? nackErr : undefined,\n }) as unknown as BaseException)\n void this.#observabilityHooks.runner('error').run(wrapped)\n }\n\n const dispatchEndedAt = DateTime.now()\n void this.#observabilityHooks.runner('dispatchEnd').run({\n dispatchId,\n status,\n error: finalError,\n iterations: iteration,\n startedAt: dispatchStartedAt,\n endedAt: dispatchEndedAt,\n durationMs: dispatchEndedAt.diff(dispatchStartedAt).milliseconds,\n })\n\n if (finalError) throw finalError\n }\n\n async #runPipeline(\n pipeline: MiddlewareRunner<DispatchPipelineMiddlewareFn>,\n llmCtx: DispatchContext,\n label: 'input' | 'output'\n ): Promise<void> {\n let pipelineError: Error | undefined\n let reached = false\n await pipeline\n .errorHandler(async (error) => {\n if (this.#isAbortError(error)) return\n pipelineError = new E_DISPATCH_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n })\n .finalHandler(async () => {\n reached = true\n })\n .run((fn, next) => Promise.resolve(fn(llmCtx, next)))\n\n if (pipelineError) {\n void this.#observabilityHooks.runner('error').run(pipelineError as unknown as BaseException)\n throw pipelineError\n }\n\n if (!reached && !llmCtx.aborted && !llmCtx.isSignalled) {\n const shortCircuitError = new E_PIPELINE_SHORT_CIRCUITED([`dispatch-${label}`])\n void this.#observabilityHooks\n .runner('error')\n .run(shortCircuitError as unknown as BaseException)\n throw shortCircuitError\n }\n }\n\n #isAbortError(err: unknown): boolean {\n return isError(err) && isInstanceOf(err, 'AbortError')\n }\n\n async #flush(): Promise<void> {\n if (!this.#sourceCtx) {\n this.#deltaQueue.length = 0\n return\n }\n while (this.#deltaQueue.length > 0) {\n const delta = this.#deltaQueue.shift()!\n this.#applyDeltaToParent(delta)\n }\n }\n\n #applyDeltaToParent(delta: ContextDelta): void {\n const ctx = this.#sourceCtx!\n const { op, type, value } = delta\n\n if (type === 'standingInstruction') {\n const t = value as Tokenizable\n if (op === 'store' || op === 'mutate') ctx.standingInstructions.add(t)\n else ctx.standingInstructions.delete(t)\n return\n }\n if (type === 'memory') {\n if (op === 'store' || op === 'mutate') {\n ctx.turnMemories.add(value as Memory)\n } else {\n for (const m of ctx.turnMemories) {\n if ((m as any).id === (value as any)) {\n ctx.turnMemories.delete(m)\n break\n }\n }\n }\n return\n }\n if (type === 'retrievable') {\n if (op === 'store' || op === 'mutate') {\n ctx.turnRetrievables.add(value as Retrievable)\n } else {\n for (const r of ctx.turnRetrievables) {\n if ((r as any).id === (value as any)) {\n ctx.turnRetrievables.delete(r)\n break\n }\n }\n }\n return\n }\n if (type === 'message') {\n if (op === 'store' || op === 'mutate') {\n ctx.turnMessages.add(value as Message)\n } else {\n for (const m of ctx.turnMessages) {\n if ((m as any).id === (value as any)) {\n ctx.turnMessages.delete(m)\n break\n }\n }\n }\n return\n }\n if (type === 'thought') {\n if (op === 'store' || op === 'mutate') {\n ctx.turnThoughts.add(value as Thought)\n } else {\n for (const t of ctx.turnThoughts) {\n if ((t as any).id === (value as any)) {\n ctx.turnThoughts.delete(t)\n break\n }\n }\n }\n return\n }\n if (type === 'toolCall') {\n if (op === 'store' || op === 'mutate') {\n ctx.turnToolCalls.add(value as ToolCall)\n } else {\n for (const tc of ctx.turnToolCalls) {\n if ((tc as any).id === (value as any)) {\n ctx.turnToolCalls.delete(tc)\n break\n }\n }\n }\n return\n }\n }\n}\n\ntype DispatchEndStatus = 'ack' | 'nack' | 'aborted'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoEA,IAAa,oBAAoB,UAC9B,OAAuB;CACtB,qBAAqB,UAClB,aACC,UAAU,OAAO,EAAE,SAAS,eAAsB,GAClD,UAAU,SAAS,EAAE,SAAS,eAAsB,CACtD,EACC,SAAS;CACZ,OAAO,UAAU,OAAO,EAAE,QAAQ,UAAU,OAAO,GAAG,UAAU,IAAI,CAAC,EAAE,QAAQ,CAAC,CAAC;CACjF,cAAc,YAAY,OAAO,SAAS;CAC1C,sBAAsB,UAAU,MAAM,EAAE,MAAM,YAA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