@nhtio/adk 0.1.0-master-445a9ed0 → 1.20260529.0

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 (170) hide show
  1. package/batteries/llm/openai_chat_completions/adapter.cjs +10 -9
  2. package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -1
  3. package/batteries/llm/openai_chat_completions/adapter.mjs +8 -8
  4. package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -1
  5. package/batteries/llm/openai_chat_completions/exceptions.cjs +1 -1
  6. package/batteries/llm/openai_chat_completions/helpers.cjs +16 -16
  7. package/batteries/llm/openai_chat_completions/helpers.cjs.map +1 -1
  8. package/batteries/llm/openai_chat_completions/helpers.d.ts +10 -10
  9. package/batteries/llm/openai_chat_completions/helpers.mjs +16 -16
  10. package/batteries/llm/openai_chat_completions/helpers.mjs.map +1 -1
  11. package/batteries/llm/openai_chat_completions/types.d.ts +6 -26
  12. package/batteries/llm/openai_chat_completions/validation.cjs +1 -3
  13. package/batteries/llm/openai_chat_completions/validation.cjs.map +1 -1
  14. package/batteries/llm/openai_chat_completions/validation.mjs +0 -2
  15. package/batteries/llm/openai_chat_completions/validation.mjs.map +1 -1
  16. package/batteries/llm/webllm_chat_completions/adapter.cjs +10 -9
  17. package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -1
  18. package/batteries/llm/webllm_chat_completions/adapter.mjs +8 -8
  19. package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -1
  20. package/batteries/llm/webllm_chat_completions/exceptions.cjs +1 -1
  21. package/batteries/llm/webllm_chat_completions/validation.cjs +1 -3
  22. package/batteries/llm/webllm_chat_completions/validation.cjs.map +1 -1
  23. package/batteries/llm/webllm_chat_completions/validation.mjs +0 -2
  24. package/batteries/llm/webllm_chat_completions/validation.mjs.map +1 -1
  25. package/batteries/storage/flydrive/index.d.ts +4 -10
  26. package/batteries/storage/flydrive.cjs +3 -12
  27. package/batteries/storage/flydrive.cjs.map +1 -1
  28. package/batteries/storage/flydrive.mjs +2 -11
  29. package/batteries/storage/flydrive.mjs.map +1 -1
  30. package/batteries/storage/in_memory/index.d.ts +17 -31
  31. package/batteries/storage/in_memory.cjs +30 -89
  32. package/batteries/storage/in_memory.cjs.map +1 -1
  33. package/batteries/storage/in_memory.mjs +30 -89
  34. package/batteries/storage/in_memory.mjs.map +1 -1
  35. package/batteries/storage/opfs/index.d.ts +4 -10
  36. package/batteries/storage/opfs.cjs +5 -55
  37. package/batteries/storage/opfs.cjs.map +1 -1
  38. package/batteries/storage/opfs.mjs +4 -54
  39. package/batteries/storage/opfs.mjs.map +1 -1
  40. package/batteries/tools/color.cjs +3 -3
  41. package/batteries/tools/color.mjs +2 -2
  42. package/batteries/tools/comparison.cjs +4 -3
  43. package/batteries/tools/comparison.cjs.map +1 -1
  44. package/batteries/tools/comparison.mjs +2 -2
  45. package/batteries/tools/data_structure.cjs +4 -3
  46. package/batteries/tools/data_structure.cjs.map +1 -1
  47. package/batteries/tools/data_structure.mjs +2 -2
  48. package/batteries/tools/datetime_extended.cjs +4 -4
  49. package/batteries/tools/datetime_extended.mjs +2 -2
  50. package/batteries/tools/datetime_math.cjs +3 -3
  51. package/batteries/tools/datetime_math.mjs +2 -2
  52. package/batteries/tools/encoding.cjs +4 -3
  53. package/batteries/tools/encoding.cjs.map +1 -1
  54. package/batteries/tools/encoding.mjs +2 -2
  55. package/batteries/tools/formatting.cjs +4 -3
  56. package/batteries/tools/formatting.cjs.map +1 -1
  57. package/batteries/tools/formatting.mjs +2 -2
  58. package/batteries/tools/geo_basics.cjs +3 -3
  59. package/batteries/tools/geo_basics.mjs +2 -2
  60. package/batteries/tools/math.cjs +4 -3
  61. package/batteries/tools/math.cjs.map +1 -1
  62. package/batteries/tools/math.mjs +2 -2
  63. package/batteries/tools/memory.cjs +7 -6
  64. package/batteries/tools/memory.cjs.map +1 -1
  65. package/batteries/tools/memory.mjs +5 -5
  66. package/batteries/tools/parsing.cjs +6 -5
  67. package/batteries/tools/parsing.cjs.map +1 -1
  68. package/batteries/tools/parsing.mjs +3 -3
  69. package/batteries/tools/retrievables.cjs +11 -11
  70. package/batteries/tools/retrievables.cjs.map +1 -1
  71. package/batteries/tools/retrievables.mjs +9 -10
  72. package/batteries/tools/retrievables.mjs.map +1 -1
  73. package/batteries/tools/standing_instructions.cjs +5 -4
  74. package/batteries/tools/standing_instructions.cjs.map +1 -1
  75. package/batteries/tools/standing_instructions.mjs +3 -3
  76. package/batteries/tools/statistics.cjs +5 -4
  77. package/batteries/tools/statistics.cjs.map +1 -1
  78. package/batteries/tools/statistics.mjs +3 -3
  79. package/batteries/tools/string_processing.cjs +4 -3
  80. package/batteries/tools/string_processing.cjs.map +1 -1
  81. package/batteries/tools/string_processing.mjs +2 -2
  82. package/batteries/tools/structured_data.cjs +4 -3
  83. package/batteries/tools/structured_data.cjs.map +1 -1
  84. package/batteries/tools/structured_data.mjs +2 -2
  85. package/batteries/tools/text_analysis.cjs +4 -4
  86. package/batteries/tools/text_analysis.mjs +3 -3
  87. package/batteries/tools/text_comparison.cjs +3 -3
  88. package/batteries/tools/text_comparison.mjs +2 -2
  89. package/batteries/tools/time.cjs +3 -3
  90. package/batteries/tools/time.mjs +2 -2
  91. package/batteries/tools/unit_conversion.cjs +3 -3
  92. package/batteries/tools/unit_conversion.mjs +2 -2
  93. package/batteries/tools.cjs +1 -1
  94. package/batteries/tools.mjs +1 -1
  95. package/batteries.cjs +1 -1
  96. package/batteries.mjs +1 -1
  97. package/chunk-KmRHZBOW.js +35 -0
  98. package/{common-aFmr9Oqs.mjs → common-DeZaonK1.mjs} +10 -76
  99. package/common-DeZaonK1.mjs.map +1 -0
  100. package/{common-BJ6V6dsH.js → common-Od8edUXU.js} +12 -89
  101. package/common-Od8edUXU.js.map +1 -0
  102. package/common.cjs +7 -9
  103. package/common.d.ts +0 -8
  104. package/common.mjs +7 -7
  105. package/{dispatch_runner-OimGCkk7.mjs → dispatch_runner-9j6bXHL3.mjs} +2 -34
  106. package/dispatch_runner-9j6bXHL3.mjs.map +1 -0
  107. package/{dispatch_runner-BWYNxmnp.js → dispatch_runner-CsoH0nld.js} +6 -37
  108. package/dispatch_runner-CsoH0nld.js.map +1 -0
  109. package/dispatch_runner.cjs +1 -1
  110. package/dispatch_runner.mjs +1 -1
  111. package/{exceptions-CSqzbL1N.js → exceptions-D5YrO9Vm.js} +2 -2
  112. package/{exceptions-CSqzbL1N.js.map → exceptions-D5YrO9Vm.js.map} +1 -1
  113. package/exceptions.cjs +2 -2
  114. package/factories.cjs +1 -1
  115. package/forge.cjs +4 -4
  116. package/forge.mjs +3 -3
  117. package/guards.cjs +9 -9
  118. package/guards.mjs +7 -7
  119. package/index.cjs +13 -13
  120. package/index.cjs.map +1 -1
  121. package/index.d.ts +1 -1
  122. package/index.mjs +10 -10
  123. package/index.mjs.map +1 -1
  124. package/lib/classes/retrievable.d.ts +4 -47
  125. package/lib/contracts/dispatch_context.d.ts +0 -44
  126. package/lib/contracts/turn_runner_config.d.ts +1 -5
  127. package/lib/contracts/turn_runner_context.d.ts +0 -25
  128. package/package.json +74 -74
  129. package/{runtime-BUDWyd-R.js → runtime-BJVkrGQe.js} +2 -2
  130. package/{runtime-BUDWyd-R.js.map → runtime-BJVkrGQe.js.map} +1 -1
  131. package/skills/adk-assembly/SKILL.md +2 -2
  132. package/{spooled_artifact-B_tVDDdB.mjs → spooled_artifact-C5ZtGxuJ.mjs} +2 -2
  133. package/{spooled_artifact-B_tVDDdB.mjs.map → spooled_artifact-C5ZtGxuJ.mjs.map} +1 -1
  134. package/{spooled_artifact-CFstzlqX.js → spooled_artifact-Cm9Te22K.js} +6 -5
  135. package/{spooled_artifact-CFstzlqX.js.map → spooled_artifact-Cm9Te22K.js.map} +1 -1
  136. package/spooled_artifact.cjs +2 -2
  137. package/spooled_artifact.mjs +2 -2
  138. package/{spooled_markdown_artifact-DWWak35I.mjs → spooled_markdown_artifact-BpUJol0W.mjs} +2 -2
  139. package/{spooled_markdown_artifact-DWWak35I.mjs.map → spooled_markdown_artifact-BpUJol0W.mjs.map} +1 -1
  140. package/{spooled_markdown_artifact-DK-T8Hy6.js → spooled_markdown_artifact-RRB113sy.js} +7 -6
  141. package/{spooled_markdown_artifact-DK-T8Hy6.js.map → spooled_markdown_artifact-RRB113sy.js.map} +1 -1
  142. package/{thought-DDqjQu3m.mjs → thought-CDb457b4.mjs} +2 -2
  143. package/{thought-DDqjQu3m.mjs.map → thought-CDb457b4.mjs.map} +1 -1
  144. package/{thought-DTsFRGdE.js → thought-DuN2PgdO.js} +6 -5
  145. package/{thought-DTsFRGdE.js.map → thought-DuN2PgdO.js.map} +1 -1
  146. package/{tool-cwJyEHI9.js → tool-COSeH8I6.js} +5 -4
  147. package/{tool-cwJyEHI9.js.map → tool-COSeH8I6.js.map} +1 -1
  148. package/{tool-q4LskG7K.mjs → tool-D2WB1EA1.mjs} +1 -1
  149. package/{tool-q4LskG7K.mjs.map → tool-D2WB1EA1.mjs.map} +1 -1
  150. package/{tool_call-BKIdAAoY.mjs → tool_call-BKyyxGaZ.mjs} +2 -2
  151. package/{tool_call-BKIdAAoY.mjs.map → tool_call-BKyyxGaZ.mjs.map} +1 -1
  152. package/{tool_call-3T0xTXlD.js → tool_call-DFgzcVcU.js} +6 -5
  153. package/{tool_call-3T0xTXlD.js.map → tool_call-DFgzcVcU.js.map} +1 -1
  154. package/{tool_registry-snPjF0zJ.js → tool_registry-Dkfprsck.js} +5 -39
  155. package/{tool_registry-snPjF0zJ.js.map → tool_registry-Dkfprsck.js.map} +1 -1
  156. package/{turn_runner-BScT8OgA.js → turn_runner-CMm2BHdX.js} +7 -10
  157. package/turn_runner-CMm2BHdX.js.map +1 -0
  158. package/{turn_runner-DRBLN2Y_.mjs → turn_runner-y7eyEcJH.mjs} +3 -7
  159. package/turn_runner-y7eyEcJH.mjs.map +1 -0
  160. package/turn_runner.cjs +1 -1
  161. package/turn_runner.mjs +1 -1
  162. package/types.d.ts +2 -2
  163. package/CHANGELOG.md +0 -49
  164. package/common-BJ6V6dsH.js.map +0 -1
  165. package/common-aFmr9Oqs.mjs.map +0 -1
  166. package/dispatch_runner-BWYNxmnp.js.map +0 -1
  167. package/dispatch_runner-OimGCkk7.mjs.map +0 -1
  168. package/lib/contracts/byte_store.d.ts +0 -93
  169. package/turn_runner-BScT8OgA.js.map +0 -1
  170. package/turn_runner-DRBLN2Y_.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"dispatch_runner-OimGCkk7.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,YAAY,MAAM,EAAE,QAAQ,CAAC,CAAC;AAC9E,CAAC,EACA,SAAS;;;;;;;;;AAwPZ,IAAa,cAAb,MAAa,YAAY;;;;;;;;;;;;CAYvB,OAAc,cAAc,OAAsC;EAChE,OAAO,aAAa,OAAO,eAAe,WAAW;CACvD;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;;;;;;;;CAUA,YAAY,KAAqB,UAA8B;EAC7D,IAAI;GACF,MAAM,gBAAqC,mBAAmB,KAAK,IAAI;EACzE,SAAS,KAAK;GACZ,MAAM,IAAI,uBAAuB,EAAE,OAAO,QAAQ,GAAG,IAAI,MAAM,KAAA,EAAU,CAAC;EAC5E;EACA,KAAKA,MAAM,GAAO;EAClB,KAAKC,uBAAuB,IAAI;EAChC,KAAKC,SAAS,IAAI,SAAS,IAAI,KAAK;EACpC,KAAKC,gBAAgB,YAAY,cAAc,IAAI,YAAY,IAC3D,IAAI,eACJ,IAAI,YAAY,IAAI,YAAY;EACpC,KAAKC,wBAAwB,IAAI,KAC9B,IAAI,wBAAwB,CAAC,GAAG,KAAK,UACpC,YAAY,cA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;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,93 +0,0 @@
1
- import type { SpoolReader } from "./spool_reader";
2
- import type { MediaReader } from "./media_reader";
3
- /**
4
- * Unified "give bytes, get a reader" persistence contract.
5
- *
6
- * @remarks
7
- * For the purposes of storage there is no meaningful distinction between text and binary — bytes
8
- * are bytes. `ByteStore` is the single low-level shape every ADK storage layer implements: hand it
9
- * bytes under an `id`, get back a replayable reader `R`; read or delete by the same `id` later. The
10
- * generic `R` is the reader the store hands out — different reader contracts (line-indexed
11
- * {@link @nhtio/adk!SpoolReader} vs binary-streamed {@link @nhtio/adk!MediaReader}) are
12
- * distinguished by the `R` instantiation, not by separate store interfaces. See the {@link SpoolStore}
13
- * and {@link MediaStore} aliases for the two concrete semantics.
14
- *
15
- * `write` accepts a `string`, a `Uint8Array`, or a `ReadableStream<Uint8Array>`. The stream form is
16
- * the point of the contract: a durable store can persist an arbitrarily large payload straight to
17
- * disk/object storage without first materializing it in memory. **String input is encoded as
18
- * UTF-8.** The returned reader is only guaranteed readable once the `write` result has resolved.
19
- *
20
- * All three methods may be synchronous or asynchronous so that in-memory implementations are not
21
- * forced to pay promise overhead while I/O-backed implementations stay async. Note that any
22
- * implementation accepting a `ReadableStream` must return a `Promise` for that input — draining a
23
- * stream cannot be synchronous.
24
- */
25
- export interface ByteStore<R> {
26
- /**
27
- * Persists `bytes` under `id` and returns a reader over them.
28
- *
29
- * @remarks
30
- * Re-writing the same `id` replaces the prior entry. `string` input is encoded as UTF-8;
31
- * `Uint8Array` and `ReadableStream<Uint8Array>` are stored byte-faithfully. Stream input
32
- * necessarily resolves asynchronously.
33
- *
34
- * @param id - Identifier used to retrieve or delete the bytes later.
35
- * @param bytes - The payload, as a `string`, `Uint8Array`, or `ReadableStream<Uint8Array>`.
36
- * @returns A reader over the stored bytes (or a `Promise` of one).
37
- */
38
- write(id: string, bytes: string | Uint8Array | ReadableStream<Uint8Array>): R | Promise<R>;
39
- /**
40
- * Returns a reader over the bytes previously written under `id`, or `undefined` if no entry
41
- * exists.
42
- *
43
- * @param id - Identifier supplied to a prior {@link ByteStore.write} call.
44
- * @returns A reader over the stored bytes, `undefined`, or a `Promise` of either.
45
- */
46
- read(id: string): R | undefined | Promise<R | undefined>;
47
- /**
48
- * Removes the entry under `id`.
49
- *
50
- * @param id - Identifier whose entry should be removed.
51
- * @returns `true` if an entry existed and was removed; `false` otherwise (or a `Promise` of one).
52
- */
53
- delete(id: string): boolean | Promise<boolean>;
54
- }
55
- /**
56
- * A {@link ByteStore} that hands out line-indexed text readers ({@link @nhtio/adk!SpoolReader}).
57
- *
58
- * @remarks
59
- * The store backing tool-output artifacts. Stored bytes are decoded as UTF-8 text for line-oriented
60
- * reads; binary input is stored byte-faithfully but `SpoolReader.readAll()` interprets it as text,
61
- * so opaque binary belongs in a {@link MediaStore} / `Media`, not here.
62
- */
63
- export type SpoolStore = ByteStore<SpoolReader>;
64
- /**
65
- * A {@link ByteStore} that hands out binary-streamed readers ({@link @nhtio/adk!MediaReader}).
66
- *
67
- * @remarks
68
- * The store backing persisted media bytes. Stored bytes are opaque and replayable via
69
- * `MediaReader.stream()`; no text decoding is implied.
70
- */
71
- export type MediaStore = ByteStore<MediaReader>;
72
- /**
73
- * Validator schema used to validate a {@link ByteStore} value.
74
- *
75
- * @remarks
76
- * Because `ByteStore` is a structural interface with no associated constructor, validation is
77
- * duck-typed: the value must be non-null with `write`, `read`, and `delete` present as callable
78
- * properties. Arity is not enforced — implementations may add optional parameters beyond the
79
- * contract. The reader type `R` cannot be checked structurally here; conformance of the reader is
80
- * the caller's concern at the point of use.
81
- */
82
- export declare const byteStoreSchema: import("@nhtio/validation").AnySchema<any>;
83
- /**
84
- * Returns `true` if `value` implements the {@link ByteStore} interface.
85
- *
86
- * @remarks
87
- * Duck-typed: checks that `value` is non-null with `write`, `read`, and `delete` as callable
88
- * functions. Does not use `instanceof` — there is no `ByteStore` constructor.
89
- *
90
- * @param value - The value to test.
91
- * @returns `true` when `value` conforms to the {@link ByteStore} interface.
92
- */
93
- export declare const implementsByteStore: <R = unknown>(value: unknown) => value is ByteStore<R>;
@@ -1 +0,0 @@
1
- {"version":3,"file":"turn_runner-BScT8OgA.js","names":["#id","#turnId","#reason","#payload","#createdAt","#settled","#schema","#controller","#promise","#resolve","#reject","#config","#inputRunner","#outputRunner","#functionalEmitter","#observabilityEmitter"],"sources":["../src/lib/classes/turn_gate.ts","../src/lib/contracts/turn_runner_config.ts","../src/lib/turn_runner.ts"],"sourcesContent":["import { DateTime } from 'luxon'\nimport { validator } from '@nhtio/validation'\nimport { validateOrThrow } from '../utils/validation'\nimport { isInstanceOf, isError, isObject } from '../utils/guards'\nimport {\n E_TURN_GATE_ABORTED,\n E_TURN_GATE_TIMEOUT,\n E_INVALID_TURN_GATE_RESOLUTION,\n E_INVALID_INITIAL_TURN_GATE_VALUE,\n} from '../exceptions/runtime'\nimport type { Schema } from '@nhtio/validation'\n\n/**\n * Plain input object supplied to {@link TurnGate} at construction time.\n *\n * @remarks\n * `turnId` and `abortSignal` are injected by the runner — callers constructing a gate via\n * `ctx.waitFor()` never supply them directly.\n *\n * `abortSignal` is `AbortSignal` (not `AbortController`) because the gate reacts to turn-level\n * cancellation but cannot trigger it. The gate owns its own internal `AbortController` for\n * `gate.abort()`.\n */\nexport interface RawTurnGate {\n /** Stable unique identifier for this gate. */\n id: string\n /** The ID of the turn that opened this gate. */\n turnId: string\n /** Human-readable label describing why this gate was opened (e.g. `'tool_approval'`). */\n reason: string\n /** Arbitrary data supplied to the gate opener; passed through to `turnGateOpen` listeners. */\n payload: unknown\n /** Optional validator schema for the resolution value. When present, `resolve()` validates before settling. */\n schema?: Schema\n /** Optional timeout in milliseconds. When elapsed the gate self-rejects with {@link @nhtio/adk!E_TURN_GATE_TIMEOUT}. */\n timeout?: number\n /** The turn's abort signal. When fired the gate self-rejects with {@link @nhtio/adk!E_TURN_GATE_ABORTED}. */\n abortSignal?: AbortSignal\n /** When this gate was created. */\n createdAt: string | number | Date | DateTime\n}\n\n/**\n * Fully-resolved {@link RawTurnGate} after schema validation.\n *\n * @internal\n */\ninterface ResolvedTurnGate {\n id: string\n turnId: string\n reason: string\n payload: unknown\n schema?: Schema\n timeout?: number\n abortSignal?: AbortSignal\n createdAt: DateTime\n}\n\n/**\n * Validator schema used to validate a {@link RawTurnGate} before constructing a {@link TurnGate}.\n *\n * @remarks\n * - `schema` and `abortSignal` are validated as opaque passthrough values.\n * - `timeout` must be a positive integer when provided.\n */\nconst rawTurnGateSchema = validator.object<RawTurnGate>({\n id: validator.string().required(),\n turnId: validator.string().required(),\n reason: validator.string().required(),\n payload: validator.any().required(),\n schema: validator\n .any()\n .custom((value, helpers) => {\n if (value === undefined || value === null) return undefined\n if (typeof (value as any).validate === 'function') return value\n return helpers.error('any.invalid')\n })\n .optional(),\n timeout: validator.number().integer().min(1).optional(),\n abortSignal: validator\n .any()\n .custom((value, helpers) => {\n if (value === undefined || value === null) return undefined\n // eslint-disable-next-line adk/use-is-instance-of -- native built-in; AbortSignal cross-realm is handled by the duck-type fallback below\n if (typeof AbortSignal !== 'undefined' && value instanceof AbortSignal) return value\n if (\n isObject(value) &&\n typeof (value as any).aborted === 'boolean' &&\n typeof (value as any).addEventListener === 'function'\n ) {\n return value\n }\n return helpers.error('any.invalid')\n })\n .optional(),\n createdAt: validator.datetime().required(),\n})\n\n/**\n * A cooperative suspension gate that blocks a turn's middleware pipeline until resolved, rejected,\n * aborted, or timed out.\n *\n * @typeParam T - The expected type of the resolution value.\n *\n * @remarks\n * Created exclusively via `ctx.waitFor()` — middleware never constructs a gate directly.\n * The gate emits `turnGateOpen` on the runner's observability bus at creation time and\n * `turnGateClosed` when it settles.\n *\n * Resolution is validated against an optional schema before the internal promise is settled.\n * A validation failure throws {@link @nhtio/adk!E_INVALID_TURN_GATE_RESOLUTION} **synchronously in the\n * caller's context** — the promise is NOT settled and the gate remains open.\n */\nexport class TurnGate<T = unknown> {\n /**\n * Validator schema that accepts a {@link RawTurnGate} object.\n *\n * @remarks\n * Reusable fragment for any schema that needs to validate or nest a gate entry.\n */\n public static schema = rawTurnGateSchema\n\n /**\n * Returns `true` if `value` is a {@link TurnGate} 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 TurnGate} instance.\n */\n public static isTurnGate(value: unknown): value is TurnGate {\n return isInstanceOf(value, 'TurnGate', TurnGate)\n }\n\n declare readonly id: string\n declare readonly turnId: string\n declare readonly reason: string\n declare readonly payload: unknown\n declare readonly createdAt: DateTime\n declare readonly isSettled: boolean\n\n #id: string\n #turnId: string\n #reason: string\n #payload: unknown\n #createdAt: DateTime\n #settled: boolean\n #schema: Schema | undefined\n #controller: AbortController\n #resolve!: (value: T) => void\n #reject!: (reason: unknown) => void\n #promise: Promise<T>\n\n /**\n * @param raw - The raw gate input validated against `rawTurnGateSchema`.\n * @throws {@link @nhtio/adk!E_INVALID_INITIAL_TURN_GATE_VALUE} when `raw` does not satisfy the schema.\n */\n constructor(raw: RawTurnGate) {\n let resolved: ResolvedTurnGate\n try {\n resolved = validateOrThrow<ResolvedTurnGate>(rawTurnGateSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_TURN_GATE_VALUE({ cause: isError(err) ? err : undefined })\n }\n\n this.#id = resolved.id\n this.#turnId = resolved.turnId\n this.#reason = resolved.reason\n this.#payload = resolved.payload\n this.#createdAt = resolved.createdAt\n this.#settled = false\n this.#schema = resolved.schema\n this.#controller = new AbortController()\n\n this.#promise = new Promise<T>((resolve, reject) => {\n this.#resolve = resolve\n this.#reject = reject\n })\n\n // Wire the internal abort controller\n const onAbort = () => {\n if (!this.#settled) {\n this.#settled = true\n this.#reject(new E_TURN_GATE_ABORTED())\n }\n }\n\n this.#controller.signal.addEventListener('abort', onAbort, { once: true })\n\n // Wire the external turn abort signal\n if (resolved.abortSignal) {\n if (resolved.abortSignal.aborted) {\n // Already aborted — reject immediately after construction\n queueMicrotask(() => onAbort())\n } else {\n resolved.abortSignal.addEventListener('abort', onAbort, { once: true })\n // Clean up the external listener once the gate settles via another path\n this.#promise.then(\n () => resolved.abortSignal!.removeEventListener('abort', onAbort),\n () => resolved.abortSignal!.removeEventListener('abort', onAbort)\n )\n }\n }\n\n // Wire the timeout\n if (resolved.timeout !== undefined) {\n const timer = setTimeout(() => {\n if (!this.#settled) {\n this.#settled = true\n this.#reject(new E_TURN_GATE_TIMEOUT())\n }\n }, resolved.timeout)\n\n this.#promise.then(\n () => clearTimeout(timer),\n () => clearTimeout(timer)\n )\n }\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n turnId: {\n get: () => this.#turnId,\n enumerable: true,\n configurable: false,\n },\n reason: {\n get: () => this.#reason,\n enumerable: true,\n configurable: false,\n },\n payload: {\n get: () => this.#payload,\n enumerable: true,\n configurable: false,\n },\n createdAt: {\n get: () => this.#createdAt,\n enumerable: true,\n configurable: false,\n },\n isSettled: {\n get: () => this.#settled,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Resolves the gate with `value`, unblocking the awaiting middleware.\n *\n * @remarks\n * If a schema was provided at construction, `value` is validated synchronously before the\n * promise is settled. A validation failure throws {@link @nhtio/adk!E_INVALID_TURN_GATE_RESOLUTION}\n * in the caller's context — the promise is NOT settled and the gate remains open.\n *\n * No-ops if the gate is already settled.\n *\n * @param value - The resolution value. Must satisfy the gate's schema when one was provided.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_GATE_RESOLUTION} when `value` fails schema validation.\n */\n resolve(value: unknown): void {\n if (this.#settled) return\n if (this.#schema !== undefined) {\n try {\n value = validateOrThrow(this.#schema, value, true)\n } catch (err) {\n throw new E_INVALID_TURN_GATE_RESOLUTION({\n cause: isError(err) ? err : undefined,\n })\n }\n }\n this.#settled = true\n this.#resolve(value as T)\n }\n\n /**\n * Rejects the gate with `error`, unblocking the awaiting middleware with a rejection.\n *\n * @remarks\n * No-ops if the gate is already settled.\n *\n * @param error - The rejection reason.\n */\n reject(error: Error): void {\n if (this.#settled) return\n this.#settled = true\n this.#reject(error)\n }\n\n /**\n * Aborts the gate by firing the internal `AbortController`, which rejects the promise with\n * {@link @nhtio/adk!E_TURN_GATE_ABORTED}.\n *\n * @remarks\n * No-ops if the gate is already settled. Distinct from the turn-level abort signal — this\n * allows callers to cancel a specific gate without aborting the whole turn.\n */\n abort(): void {\n if (this.#settled) return\n this.#controller.abort()\n }\n\n /**\n * Returns the internal promise. Called by `ctx.waitFor()` to block the middleware pipeline.\n *\n * @internal\n */\n _promise(): Promise<T> {\n return this.#promise\n }\n}\n","import { Tool } from '../classes/tool'\nimport { validator } from '@nhtio/validation'\nimport type { TurnPipelineMiddlewareFn } from '../types/turn_runner'\nimport type { DispatchPipelineMiddlewareFn, DispatchExecutorFn } from '../types/dispatch_runner'\nimport type {\n MemoryRetrievalFn,\n MessageRetrievalFn,\n ThoughtRetrievalFn,\n ToolCallRetrievalFn,\n ToolsRetrievalFn,\n StandingInstructionsRefreshFn,\n StandingInstructionStoreFn,\n StandingInstructionMutateFn,\n StandingInstructionDeleteFn,\n MemoryStoreFn,\n MemoryMutateFn,\n MemoryDeleteFn,\n RetrievableRetrievalFn,\n RetrievableStoreFn,\n RetrievableMutateFn,\n RetrievableDeleteFn,\n MessageStoreFn,\n MessageMutateFn,\n MessageDeleteFn,\n ThoughtStoreFn,\n ThoughtMutateFn,\n ThoughtDeleteFn,\n ToolCallStoreFn,\n ToolCallMutateFn,\n ToolCallDeleteFn,\n MediaBytesStoreFn,\n RetrievableBytesStoreFn,\n} from './turn_runner_context'\n\n/**\n * Configuration supplied to {@link @nhtio/adk!TurnRunner} at construction time.\n *\n * @remarks\n * Validated against `turnRunnerConfigSchema` at construction — a misconfigured runner throws\n * immediately rather than failing on the first turn.\n *\n * All fetch and mutation callbacks are required: they are injected into each {@link @nhtio/adk!TurnContext}\n * so middleware can call fetch, refresh, and persistence methods directly on the context without\n * coupling to the runner.\n *\n * `tools` is optional at the caller level and defaults to `[]` after schema resolution — a runner\n * with no baseline tools is valid.\n */\nexport interface TurnRunnerConfig {\n /** Performs the LLM API/SDK call for each iteration of the dispatch loop; receives the active {@link @nhtio/adk!DispatchContext} and an {@link @nhtio/adk!DispatchExecutorHelpers} object for managing per-id stream state. */\n executorCallback: DispatchExecutorFn\n /** Called once per turn to supply memories; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchMemoriesCallback: MemoryRetrievalFn\n /** Called once per turn to supply conversation history; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchMessagesCallback: MessageRetrievalFn\n /** Called once per turn to supply thought traces; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchThoughtsCallback: ThoughtRetrievalFn\n /** Called once per turn to supply tool call records; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchToolCallsCallback: ToolCallRetrievalFn\n /** Called to supply available tools; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchToolsCallback: ToolsRetrievalFn\n /** Called to refresh and return standing instructions; receives the active {@link @nhtio/adk!TurnContext}. */\n refreshStandingInstructionsCallback: StandingInstructionsRefreshFn\n /** Persists a new standing instruction. */\n storeStandingInstructionCallback: StandingInstructionStoreFn\n /** Updates an existing standing instruction in the persistence layer. */\n mutateStandingInstructionCallback: StandingInstructionMutateFn\n /** Removes a standing instruction from the persistence layer. */\n deleteStandingInstructionCallback: StandingInstructionDeleteFn\n /** Persists a new memory. */\n storeMemoryCallback: MemoryStoreFn\n /** Updates an existing memory in the persistence layer. */\n mutateMemoryCallback: MemoryMutateFn\n /** Removes a memory from the persistence layer by ID. */\n deleteMemoryCallback: MemoryDeleteFn\n /** Called once per turn to supply retrievable (RAG) records; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchRetrievablesCallback: RetrievableRetrievalFn\n /** Persists a new retrievable record. */\n storeRetrievableCallback: RetrievableStoreFn\n /** Updates an existing retrievable record in the persistence layer. */\n mutateRetrievableCallback: RetrievableMutateFn\n /** Removes a retrievable record from the persistence layer by ID. */\n deleteRetrievableCallback: RetrievableDeleteFn\n /** Persists a new message. */\n storeMessageCallback: MessageStoreFn\n /** Updates an existing message in the persistence layer. */\n mutateMessageCallback: MessageMutateFn\n /** Removes a message from the persistence layer by ID. */\n deleteMessageCallback: MessageDeleteFn\n /** Persists a new thought. */\n storeThoughtCallback: ThoughtStoreFn\n /** Updates an existing thought in the persistence layer. */\n mutateThoughtCallback: ThoughtMutateFn\n /** Removes a thought from the persistence layer by ID. */\n deleteThoughtCallback: ThoughtDeleteFn\n /** Persists a new tool call. */\n storeToolCallCallback: ToolCallStoreFn\n /** Updates an existing tool call in the persistence layer. */\n mutateToolCallCallback: ToolCallMutateFn\n /** Removes a tool call from the persistence layer by ID. */\n deleteToolCallCallback: ToolCallDeleteFn\n /** Persists tool-generated media bytes into consumer storage; returns a `MediaReader`. */\n storeMediaBytesCallback: MediaBytesStoreFn\n /** Persists extracted retrievable text bytes into consumer storage; returns a `SpoolReader`. */\n storeRetrievableBytesCallback: RetrievableBytesStoreFn\n /** Baseline tools available on every turn. Middleware may trim or extend this per-turn via `ctx.tools`. Defaults to `[]`. */\n tools?: Tool[]\n /** Turn-level input middleware, executed in order against the {@link @nhtio/adk!TurnContext} before the LLM dispatch. Defaults to `[]`. */\n turnInputPipeline?: TurnPipelineMiddlewareFn[]\n /** Turn-level output middleware, executed in order against the {@link @nhtio/adk!TurnContext} after the LLM dispatch resolves successfully. Defaults to `[]`. */\n turnOutputPipeline?: TurnPipelineMiddlewareFn[]\n /** LLM-iteration input middleware, executed in order against the {@link @nhtio/adk!DispatchContext} before the executor on each iteration. Defaults to `[]`. */\n dispatchInputPipeline?: DispatchPipelineMiddlewareFn[]\n /** LLM-iteration output middleware, executed in order against the {@link @nhtio/adk!DispatchContext} after the executor on each iteration. Defaults to `[]`. */\n dispatchOutputPipeline?: DispatchPipelineMiddlewareFn[]\n}\n\n/**\n * Fully-resolved {@link TurnRunnerConfig} after schema validation.\n *\n * @remarks\n * All optional fields are guaranteed present (e.g. `tools` defaults to `[]`). The runner stores\n * this type internally so field access never needs to guard for undefined.\n */\nexport type ResolvedTurnRunnerConfig = Required<TurnRunnerConfig>\n\n/**\n * Validator schema used to validate a {@link TurnRunnerConfig} at {@link @nhtio/adk!TurnRunner} construction time.\n *\n * @remarks\n * Validates that all callbacks are functions of the correct arity, and that `tools` — when\n * provided — is an array of valid {@link @nhtio/adk!Tool} instances. Defaults `tools` to `[]`.\n *\n * Throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} (via the {@link @nhtio/adk!TurnRunner} constructor) when\n * validation fails.\n */\nexport const turnRunnerConfigSchema = validator.object<TurnRunnerConfig>({\n executorCallback: validator.function().required(),\n fetchMemoriesCallback: validator.function().arity(1).required(),\n fetchMessagesCallback: validator.function().arity(1).required(),\n fetchThoughtsCallback: validator.function().arity(1).required(),\n fetchToolCallsCallback: validator.function().arity(1).required(),\n fetchToolsCallback: validator.function().arity(1).required(),\n refreshStandingInstructionsCallback: validator.function().arity(1).required(),\n storeStandingInstructionCallback: validator.function().arity(2).required(),\n mutateStandingInstructionCallback: validator.function().arity(2).required(),\n deleteStandingInstructionCallback: validator.function().arity(2).required(),\n storeMemoryCallback: validator.function().arity(2).required(),\n mutateMemoryCallback: validator.function().arity(2).required(),\n deleteMemoryCallback: validator.function().arity(2).required(),\n fetchRetrievablesCallback: validator.function().arity(1).required(),\n storeRetrievableCallback: validator.function().arity(2).required(),\n mutateRetrievableCallback: validator.function().arity(2).required(),\n deleteRetrievableCallback: validator.function().arity(2).required(),\n storeMessageCallback: validator.function().arity(2).required(),\n mutateMessageCallback: validator.function().arity(2).required(),\n deleteMessageCallback: validator.function().arity(2).required(),\n storeThoughtCallback: validator.function().arity(2).required(),\n mutateThoughtCallback: validator.function().arity(2).required(),\n deleteThoughtCallback: validator.function().arity(2).required(),\n storeToolCallCallback: validator.function().arity(2).required(),\n mutateToolCallCallback: validator.function().arity(2).required(),\n deleteToolCallCallback: validator.function().arity(2).required(),\n storeMediaBytesCallback: validator.function().arity(3).required(),\n storeRetrievableBytesCallback: validator.function().arity(3).required(),\n tools: validator\n .array()\n .items(\n validator.any().custom((value: unknown, helpers: { error: (code: string) => unknown }) => {\n if (Tool.isTool(value)) return value\n return helpers.error('any.invalid')\n })\n )\n .default([]),\n turnInputPipeline: validator.array().items(validator.function()).default([]),\n turnOutputPipeline: validator.array().items(validator.function()).default([]),\n dispatchInputPipeline: validator.array().items(validator.function()).default([]),\n dispatchOutputPipeline: validator.array().items(validator.function()).default([]),\n})\n","import { DateTime } from 'luxon'\nimport { Middleware } from '@nhtio/middleware'\nimport { TurnGate } from './classes/turn_gate'\nimport { DispatchRunner } from './dispatch_runner'\nimport { ToolRegistry } from './classes/tool_registry'\nimport { isInstanceOf, isError } from './utils/guards'\nimport { TypedEventEmitter } from '@nhtio/tiny-typed-emitter'\nimport { passesSchema, validateOrThrow } from './utils/validation'\nimport { turnRunnerConfigSchema } from './contracts/turn_runner_config'\nimport { TurnContext, RawTurnContext } from './contracts/turn_runner_context'\nimport {\n E_INVALID_TURN_RUNNER_CONFIG,\n E_INPUT_PIPELINE_ERROR,\n E_OUTPUT_PIPELINE_ERROR,\n E_PIPELINE_SHORT_CIRCUITED,\n} from './exceptions/runtime'\nimport type { Runner } from '@nhtio/middleware'\nimport type { RawTurnGate } from './classes/turn_gate'\nimport type { ResolvedTurnRunnerConfig, TurnRunnerConfig } from './contracts/turn_runner_config'\nimport type {\n OpenGateFn,\n TurnEvents,\n TurnEvent,\n TurnEventListener,\n TurnPipelineMiddlewareFn,\n TurnObservabilityEvents,\n TurnObservabilityEvent,\n TurnObservabilityEventListener,\n} from './types/turn_runner'\n\nexport type {\n TurnPipelineMiddlewareFn,\n TurnStreamableContent,\n TurnToolCallContent,\n TurnStartEvent,\n TurnEndEvent,\n TurnGateClosedEvent,\n ToolExecutionStartEvent,\n ToolExecutionEndEvent,\n EmitMessageFn,\n EmitThoughtFn,\n EmitToolCallFn,\n EmitToolExecutionStartFn,\n EmitToolExecutionEndFn,\n OpenGateFn,\n TurnEvents,\n TurnEvent,\n TurnEventListener,\n TurnObservabilityEvents,\n TurnObservabilityEvent,\n TurnObservabilityEventListener,\n} from './types/turn_runner'\n\n/**\n * Executes a single agent turn through paired input and output middleware pipelines.\n *\n * @remarks\n * Construction validates `config` eagerly and throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} if it\n * does not satisfy the schema — fail-fast so misconfiguration surfaces before any turn runs.\n *\n * Each call to {@link TurnRunner.run} threads a {@link @nhtio/adk!TurnContext} through the input pipeline,\n * invokes the model, then threads the result through the output pipeline. Middleware on each side\n * can read and mutate the context for pre- and post-processing (e.g. message normalisation, tool\n * call dispatch, response filtering).\n *\n * **Two event buses:**\n * - Functional bus (`on` / `off` / `once`): `message`, `thought`, `toolCall` — pipeline-affecting\n * events that middleware raises throughout turn execution.\n * - Observability bus (`observe` / `unobserve` / `observeOnce`): `turnStart`, `turnEnd`,\n * `turnGateOpen`, `turnGateClosed`, `error` — instrumentation-only events that monitor execution\n * without participating in it.\n *\n * Streaming content is surfaced via `message` and `thought` events; tool call lifecycle via\n * `toolCall`; non-fatal pipeline errors via the observability `error` event; gate lifecycle via\n * `turnGateOpen` and `turnGateClosed` — all throughout execution.\n *\n * @example\n * ```ts\n * const runner = new TurnRunner({\n * fetchMemoriesCallback: async (ctx) => memoryStore.query(ctx),\n * fetchMessagesCallback: async (ctx) => messageStore.history(ctx),\n * fetchThoughtsCallback: async (ctx) => thoughtStore.history(ctx),\n * fetchToolCallsCallback: async (ctx) => toolCallStore.history(ctx),\n * })\n * // Functional bus — pipeline events\n * runner.on('message', (chunk) => process.stdout.write(chunk.aDelta))\n * // Observability bus — instrumentation\n * runner.observe('error', (err) => console.error(err.toString()))\n * runner.observe('turnStart', ({ turnId }) => console.log('turn started', turnId))\n * runner.observe('turnGateOpen', (gate) => {\n * if (gate.reason === 'tool_approval') {\n * gate.resolve(true) // approve immediately for this example\n * }\n * })\n * await runner.run({\n * turnAbortController: new AbortController(),\n * systemPrompt: 'You are a helpful assistant.',\n * standingInstructions: [],\n * })\n * ```\n */\nexport class TurnRunner {\n /**\n * Returns `true` if `value` is a {@link TurnRunner} 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 TurnRunner} instance.\n */\n public static isTurnRunner(value: unknown): value is TurnRunner {\n return isInstanceOf(value, 'TurnRunner', TurnRunner)\n }\n\n #config: ResolvedTurnRunnerConfig\n #inputRunner: Runner<TurnPipelineMiddlewareFn>\n #outputRunner: Runner<TurnPipelineMiddlewareFn>\n #functionalEmitter: TypedEventEmitter<TurnEvents>\n #observabilityEmitter: TypedEventEmitter<TurnObservabilityEvents>\n\n /**\n * @param config - Construction-time configuration validated against {@link turnRunnerConfigSchema}.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} when `config` does not satisfy the schema.\n */\n constructor(config: TurnRunnerConfig) {\n const isValid = passesSchema(turnRunnerConfigSchema, config)\n if (!isValid) {\n throw new E_INVALID_TURN_RUNNER_CONFIG()\n }\n // Store the resolved config so optional fields (e.g. tools) are always present.\n this.#config = validateOrThrow<ResolvedTurnRunnerConfig>(turnRunnerConfigSchema, config, true)\n const turnInputPipeline = new Middleware<TurnPipelineMiddlewareFn>()\n const turnOutputPipeline = new Middleware<TurnPipelineMiddlewareFn>()\n const wrap =\n (fn: TurnPipelineMiddlewareFn): TurnPipelineMiddlewareFn =>\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 this.#config.turnInputPipeline) turnInputPipeline.add(wrap(fn))\n for (const fn of this.#config.turnOutputPipeline) turnOutputPipeline.add(wrap(fn))\n this.#inputRunner = turnInputPipeline.runner()\n this.#outputRunner = turnOutputPipeline.runner()\n this.#functionalEmitter = new TypedEventEmitter<TurnEvents>()\n this.#observabilityEmitter = new TypedEventEmitter<TurnObservabilityEvents>()\n }\n\n // ── Functional bus ───────────────────────────────────────────────────────\n\n /**\n * Removes a previously registered functional listener for `event`.\n *\n * @param event - The event to stop listening to.\n * @param listener - The listener function to remove.\n * @returns `this` for chaining.\n */\n off<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.off(event, listener)\n return this\n }\n\n /**\n * Registers a persistent functional listener for `event`.\n *\n * @param event - The event to listen to.\n * @param listener - The function to call on each emission.\n * @returns `this` for chaining.\n */\n on<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.on(event, listener)\n return this\n }\n\n /**\n * Registers a one-time functional listener for `event` that is automatically removed after the\n * first emission.\n *\n * @param event - The event to listen to.\n * @param listener - The function to call on the next emission.\n * @returns `this` for chaining.\n */\n once<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.once(event, listener)\n return this\n }\n\n // ── Observability bus ────────────────────────────────────────────────────\n\n /**\n * Removes a previously registered observability listener for `event`.\n *\n * @param event - The event to stop observing.\n * @param listener - The listener function to remove.\n * @returns `this` for chaining.\n */\n unobserve<K>(\n event: TurnObservabilityEvent<K>,\n listener: TurnObservabilityEventListener<K>\n ): this {\n this.#observabilityEmitter.off(event, listener)\n return this\n }\n\n /**\n * Registers a persistent observability listener for `event`.\n *\n * @remarks\n * Use the observability bus (`observe` / `unobserve` / `observeOnce`) for instrumentation:\n * turn lifecycle, gate lifecycle, and non-fatal errors. Use the functional bus (`on` / `off` /\n * `once`) for pipeline-affecting events: `message`, `thought`, `toolCall`.\n *\n * @param event - The event to observe.\n * @param listener - The function to call on each emission.\n * @returns `this` for chaining.\n */\n observe<K>(event: TurnObservabilityEvent<K>, listener: TurnObservabilityEventListener<K>): this {\n this.#observabilityEmitter.on(event, listener)\n return this\n }\n\n /**\n * Registers a one-time observability listener for `event` that is automatically removed after\n * the first emission.\n *\n * @param event - The event to observe once.\n * @param listener - The function to call on the next emission.\n * @returns `this` for chaining.\n */\n observeOnce<K>(\n event: TurnObservabilityEvent<K>,\n listener: TurnObservabilityEventListener<K>\n ): this {\n this.#observabilityEmitter.once(event, listener)\n return this\n }\n\n // ── Turn execution ───────────────────────────────────────────────────────\n\n /**\n * Executes a single agent turn against the provided raw context.\n *\n * @remarks\n * Returns `Promise<void>` intentionally — all meaningful output surfaces via events, not return\n * values. Register listeners before calling `run`: observability events (`turnStart`, `turnEnd`)\n * bracket execution; functional events (`message`, `thought`, `toolCall`) fire throughout;\n * observability `error` carries non-fatal pipeline failures; `turnGateOpen` and `turnGateClosed`\n * fire when middleware suspends via `ctx.waitFor()`. Awaiting this method only tells you the\n * pipeline has finished, not what it produced.\n *\n * Constructs a validated {@link @nhtio/adk!TurnContext} from `context` (throwing\n * {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} on failure), then runs the input middleware pipeline.\n * Abort signals are silently swallowed.\n *\n * @param context - Raw input validated and wrapped into a {@link @nhtio/adk!TurnContext} before execution.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} when `context` does not satisfy the schema.\n */\n async run(context: RawTurnContext): Promise<void> {\n const abortController = context.turnAbortController ?? new AbortController()\n\n // Forward declaration so openGate can reference turnContext.id before it is assigned.\n let turnContextId: string\n\n const openGate: OpenGateFn = <T>(raw: Omit<RawTurnGate, 'turnId' | 'abortSignal'>) => {\n const gate = new TurnGate<T>({\n ...raw,\n turnId: turnContextId,\n abortSignal: abortController.signal,\n })\n this.#observabilityEmitter.emit('turnGateOpen', gate)\n const promise = gate._promise()\n promise.then(\n () => {\n this.#observabilityEmitter.emit('turnGateClosed', {\n gateId: gate.id,\n turnId: gate.turnId,\n result: 'resolved',\n settledAt: DateTime.now(),\n })\n },\n (err: unknown) => {\n let result: 'rejected' | 'aborted' | 'timeout' = 'rejected'\n if (isInstanceOf(err, 'E_TURN_GATE_ABORTED')) result = 'aborted'\n else if (isInstanceOf(err, 'E_TURN_GATE_TIMEOUT')) result = 'timeout'\n this.#observabilityEmitter.emit('turnGateClosed', {\n gateId: gate.id,\n turnId: gate.turnId,\n result,\n settledAt: DateTime.now(),\n })\n }\n )\n return promise\n }\n\n const tools = new ToolRegistry(this.#config.tools)\n\n const turnContext = new TurnContext(\n { ...context, turnAbortController: abortController },\n {\n fetchMemories: this.#config.fetchMemoriesCallback,\n fetchMessages: this.#config.fetchMessagesCallback,\n fetchThoughts: this.#config.fetchThoughtsCallback,\n fetchToolCalls: this.#config.fetchToolCallsCallback,\n fetchTools: this.#config.fetchToolsCallback,\n refreshStandingInstructions: this.#config.refreshStandingInstructionsCallback,\n storeStandingInstruction: this.#config.storeStandingInstructionCallback,\n mutateStandingInstruction: this.#config.mutateStandingInstructionCallback,\n deleteStandingInstruction: this.#config.deleteStandingInstructionCallback,\n storeMemory: this.#config.storeMemoryCallback,\n mutateMemory: this.#config.mutateMemoryCallback,\n deleteMemory: this.#config.deleteMemoryCallback,\n fetchRetrievables: this.#config.fetchRetrievablesCallback,\n storeRetrievable: this.#config.storeRetrievableCallback,\n mutateRetrievable: this.#config.mutateRetrievableCallback,\n deleteRetrievable: this.#config.deleteRetrievableCallback,\n storeMessage: this.#config.storeMessageCallback,\n mutateMessage: this.#config.mutateMessageCallback,\n deleteMessage: this.#config.deleteMessageCallback,\n storeThought: this.#config.storeThoughtCallback,\n mutateThought: this.#config.mutateThoughtCallback,\n deleteThought: this.#config.deleteThoughtCallback,\n storeToolCall: this.#config.storeToolCallCallback,\n mutateToolCall: this.#config.mutateToolCallCallback,\n deleteToolCall: this.#config.deleteToolCallCallback,\n storeMediaBytes: this.#config.storeMediaBytesCallback,\n storeRetrievableBytes: this.#config.storeRetrievableBytesCallback,\n emitMessage: (content) => this.#functionalEmitter.emit('message', content),\n emitThought: (content) => this.#functionalEmitter.emit('thought', content),\n emitToolCall: (content) => this.#functionalEmitter.emit('toolCall', content),\n emitToolExecutionStart: (event) =>\n this.#observabilityEmitter.emit('toolExecutionStart', event),\n emitToolExecutionEnd: (event) => this.#observabilityEmitter.emit('toolExecutionEnd', event),\n openGate,\n tools,\n }\n )\n\n turnContextId = turnContext.id\n\n const startedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnStart', { turnId: turnContext.id, startedAt })\n\n const emitTurnEnd = () => {\n const endedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnEnd', {\n turnId: turnContext.id,\n startedAt,\n endedAt,\n durationMs: endedAt.diff(startedAt).milliseconds,\n })\n }\n\n // 1. Input pipeline\n let inputFailed = false\n let inputReached = false\n await this.#inputRunner\n .errorHandler(async (error) => {\n if (!isError(error) || !isInstanceOf(error, 'AbortError')) {\n inputFailed = true\n const err = new E_INPUT_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n this.#observabilityEmitter.emit('error', err)\n }\n })\n .finalHandler(async () => {\n inputReached = true\n })\n .run((fn, next) => Promise.resolve(fn(turnContext, next)))\n\n if (!inputReached && !inputFailed && !turnContext.aborted) {\n inputFailed = true\n const err = new E_PIPELINE_SHORT_CIRCUITED(['turn-input'])\n this.#observabilityEmitter.emit('error', err)\n }\n\n if (inputFailed || turnContext.aborted) {\n emitTurnEnd()\n return\n }\n\n // 2. LLM execution dispatch\n let dispatchFailed = false\n try {\n await DispatchRunner.dispatch({\n source: turnContext,\n executor: this.#config.executorCallback,\n turnInputPipeline: this.#config.dispatchInputPipeline,\n turnOutputPipeline: this.#config.dispatchOutputPipeline,\n observers: {\n dispatchStart: [\n (e) => {\n this.#observabilityEmitter.emit('dispatchStart', e)\n },\n ],\n dispatchEnd: [\n (e) => {\n this.#observabilityEmitter.emit('dispatchEnd', e)\n },\n ],\n iterationStart: [\n (e) => {\n this.#observabilityEmitter.emit('iterationStart', e)\n },\n ],\n iterationEnd: [\n (e) => {\n this.#observabilityEmitter.emit('iterationEnd', e)\n },\n ],\n log: [\n (e) => {\n this.#observabilityEmitter.emit('log', e)\n },\n ],\n },\n })\n } catch (err) {\n dispatchFailed = true\n const wrapped = isInstanceOf(err, 'BaseException') ? (err as InstanceType<typeof Error>) : err\n this.#observabilityEmitter.emit('error', wrapped as any)\n }\n\n if (dispatchFailed || turnContext.aborted) {\n emitTurnEnd()\n return\n }\n\n // 3. Output pipeline\n let outputFailed = false\n let outputReached = false\n await this.#outputRunner\n .errorHandler(async (error) => {\n if (!isError(error) || !isInstanceOf(error, 'AbortError')) {\n outputFailed = true\n const err = new E_OUTPUT_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n this.#observabilityEmitter.emit('error', err)\n }\n })\n .finalHandler(async () => {\n outputReached = true\n })\n .run((fn, next) => Promise.resolve(fn(turnContext, next)))\n\n if (!outputReached && !outputFailed && !turnContext.aborted) {\n const err = new E_PIPELINE_SHORT_CIRCUITED(['turn-output'])\n this.#observabilityEmitter.emit('error', err)\n }\n\n emitTurnEnd()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiEA,IAAM,oBAAoB,kBAAA,UAAU,OAAoB;CACtD,IAAI,kBAAA,UAAU,OAAO,EAAE,SAAS;CAChC,QAAQ,kBAAA,UAAU,OAAO,EAAE,SAAS;CACpC,QAAQ,kBAAA,UAAU,OAAO,EAAE,SAAS;CACpC,SAAS,kBAAA,UAAU,IAAI,EAAE,SAAS;CAClC,QAAQ,kBAAA,UACL,IAAI,EACJ,QAAQ,OAAO,YAAY;EAC1B,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,KAAA;EAClD,IAAI,OAAQ,MAAc,aAAa,YAAY,OAAO;EAC1D,OAAO,QAAQ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