{"version":3,"file":"dispatch_runner-BZDXUe0G.mjs","names":["#turnToolCalls","#turnRetrievables","#doStoreRetrievable","#checkArtifactIdCollision","#doMutateRetrievable","#replaceById","#doStoreToolCall","#doMutateToolCall","#id","#turnAbortController","#stash","#systemPrompt","#standingInstructions","#turnMemories","#turnMessages","#turnThoughts","#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","#replaceToolCallGroup","#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","#doReplaceToolCallGroup","#replaceById","#checkArtifactIdCollision","#sourceCtx","#deltaQueue","#functionalHooks","#observabilityHooks","#inputPipeline","#outputPipeline","#buildContext","#wireContextHooks","#replaceById","#runDispatch","#buildHelpers","#forgeArtifactTools","#runPipeline","#flush","#isAbortError","#applyDeltaToParent"],"sources":["../src/lib/utils/retrievable_spool.ts","../src/lib/contracts/turn_runner_context.ts","../src/lib/contracts/dispatch_context.ts","../src/lib/dispatch_runner.ts"],"sourcesContent":["import { Tokenizable } from '../classes/tokenizable'\nimport { Retrievable } from '../classes/retrievable'\nimport { SpooledArtifact } from '../classes/spooled_artifact'\nimport type { SpoolReader } from '../contracts/spool_reader'\nimport type { ConduitBytes } from '../contracts/dispatch_context'\n\nexport interface RetrievableSpoolContext {\n  storeRetrievableBytes: (id: string, bytes: ConduitBytes) => SpoolReader | Promise<SpoolReader>\n  turnRetrievables: Set<Retrievable>\n}\n\nexport const computeTextHints = (text: string): { byteLength: number; lineCount: number } => ({\n  byteLength: new TextEncoder().encode(text).byteLength,\n  lineCount: text.length === 0 ? 0 : text.split('\\n').length,\n})\n\nexport async function autoSpoolRetrievable(\n  ctx: Pick<RetrievableSpoolContext, 'storeRetrievableBytes'>,\n  v: Retrievable\n): Promise<Retrievable> {\n  if (!Tokenizable.isTokenizable(v.content) || v.content.dynamic || v.inline) return v\n  const text = v.content.toString()\n  const hints = computeTextHints(text)\n  const reader = await ctx.storeRetrievableBytes(v.id, text)\n  const Ctor = v.artifactConstructor?.() ?? SpooledArtifact\n  const artifact = new Ctor(reader)\n  if (typeof (artifact as { _setSizeHints?: unknown })._setSizeHints === 'function') {\n    artifact._setSizeHints(hints)\n  }\n  // Do not spread the instance: its derived enumerable `sizeUnknown` getter is not a\n  // RawRetrievable field and strict validation intentionally rejects it.\n  return new Retrievable({\n    id: v.id,\n    content: artifact,\n    trustTier: v.trustTier,\n    source: v.source,\n    kind: v.kind,\n    score: v.score,\n    createdAt: v.createdAt,\n    updatedAt: v.updatedAt,\n    inline: v.inline,\n    artifactConstructor: v.artifactConstructor,\n  })\n}\n\nexport async function normalizeRetrievables(ctx: RetrievableSpoolContext): Promise<void> {\n  const records = await Promise.all(\n    [...ctx.turnRetrievables].map((r) => autoSpoolRetrievable(ctx, r))\n  )\n  ctx.turnRetrievables.clear()\n  for (const record of records) ctx.turnRetrievables.add(record)\n}\n\nexport function assertUniqueRetrievableIds(recs: ReadonlyArray<Pick<Retrievable, 'id'>>): void {\n  const seen = new Set<string>()\n  for (const record of recs) {\n    if (seen.has(record.id)) throw new Error(`Duplicate retrievable id: ${record.id}`)\n    seen.add(record.id)\n  }\n}\n","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, E_ARTIFACT_ID_COLLISION } from '../exceptions/runtime'\nimport { autoSpoolRetrievable, assertUniqueRetrievableIds } from '../utils/retrievable_spool'\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    // eslint-disable-next-line adk/require-validator-any-required -- map value type-arg: stash holds arbitrary values; disposition is set by .default({}) on the object\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/** Optionally persists a complete tool-call group replacement atomically. */\nexport type ToolCallGroupReplaceFn = (\n  ctx: TurnContext,\n  removedIds: readonly string[],\n  replacements: readonly ToolCall[]\n) => 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  /** Optionally persists a complete tool-call group replacement atomically. */\n  replaceToolCallGroup?: ToolCallGroupReplaceFn\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  #replaceById<T extends { id: string }>(set: Set<T>, id: string, replacement: T): Set<T> {\n    const next = new Set<T>()\n    let inserted = false\n    for (const existing of set) {\n      if (existing.id === id) {\n        if (!inserted) next.add(replacement)\n        inserted = true\n      } else next.add(existing)\n    }\n    if (!inserted) next.add(replacement)\n    return next\n  }\n\n  #checkArtifactIdCollision(id: string, source: 'retrievable' | 'toolCall'): void {\n    const other = source === 'retrievable' ? this.#turnToolCalls : this.#turnRetrievables\n    if ([...other].some((v) => v.id === id)) throw new E_ARTIFACT_ID_COLLISION([id])\n  }\n\n  async #doStoreRetrievable(i: TurnRunnerInjected, v: Retrievable): Promise<Retrievable> {\n    this.#checkArtifactIdCollision(v.id, 'retrievable')\n    const record = await autoSpoolRetrievable(this, v)\n    this.#turnRetrievables.add(record)\n    await i.storeRetrievable(this, record)\n    return record\n  }\n  async #doMutateRetrievable(i: TurnRunnerInjected, v: Retrievable): Promise<Retrievable> {\n    this.#checkArtifactIdCollision(v.id, 'retrievable')\n    const record = await autoSpoolRetrievable(this, v)\n    this.#turnRetrievables = this.#replaceById(this.#turnRetrievables, record.id, record)\n    await i.mutateRetrievable(this, record)\n    return record\n  }\n  async #doStoreToolCall(i: TurnRunnerInjected, v: ToolCall): Promise<void> {\n    this.#checkArtifactIdCollision(v.id, 'toolCall')\n    this.#turnToolCalls.add(v)\n    await i.storeToolCall(this, v)\n  }\n  async #doMutateToolCall(i: TurnRunnerInjected, v: ToolCall): Promise<void> {\n    this.#checkArtifactIdCollision(v.id, 'toolCall')\n    this.#turnToolCalls = this.#replaceById(this.#turnToolCalls, v.id, v)\n    await i.mutateToolCall(this, v)\n  }\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: async () => {\n          const recs = await injected.fetchRetrievables(this)\n          assertUniqueRetrievableIds(recs)\n          return Promise.all(recs.map((r) => autoSpoolRetrievable(this, r)))\n        },\n        enumerable: true,\n        configurable: false,\n        writable: false,\n      },\n      storeRetrievable: {\n        value: (v: Retrievable) => this.#doStoreRetrievable(injected, v),\n        enumerable: true,\n        configurable: false,\n        writable: false,\n      },\n      mutateRetrievable: {\n        value: (v: Retrievable) => this.#doMutateRetrievable(injected, 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) => this.#doStoreToolCall(injected, v),\n        enumerable: true,\n        configurable: false,\n        writable: false,\n      },\n      mutateToolCall: {\n        value: (v: ToolCall) => this.#doMutateToolCall(injected, 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      replaceToolCallGroup: {\n        value: async (ids: readonly string[], replacements: readonly ToolCall[]) => {\n          if (injected.replaceToolCallGroup) {\n            await injected.replaceToolCallGroup(this, ids, replacements)\n          } else {\n            // Degrade to the ordinary persistence conduits when no transaction is available. Carry\n            // the deletion progress out on the error: without it a failed repair tells a consumer\n            // only THAT it failed, leaving a partially mutated store with nothing to reconcile\n            // against. Mirrors DispatchContext's degraded path.\n            const deletedIds: string[] = []\n            try {\n              for (const id of ids) {\n                await injected.deleteToolCall(this, id)\n                deletedIds.push(id)\n              }\n              for (const replacement of replacements)\n                await injected.storeToolCall(this, replacement)\n            } catch (error) {\n              if (isError(error))\n                (error as Error & { deletedIds: string[] }).deletedIds = [...deletedIds]\n              throw error\n            }\n          }\n          // Persistence committed — now bring the in-memory collection in line, on BOTH paths.\n          // `#doStoreToolCall`/`#doMutateToolCall` maintain this Set; a group replacement that\n          // skipped it would leave the turn holding the colliding calls it just renamed away, and\n          // the next dispatch seeded from this turn would re-process them and diverge from what\n          // was persisted. Replacements land at the position of the first removed member so\n          // insertion order is preserved.\n          const removing = new Set(ids)\n          const next = new Set<ToolCall>()\n          let inserted = false\n          for (const tc of this.#turnToolCalls) {\n            if (removing.has(tc.id)) {\n              if (!inserted) {\n                for (const replacement of replacements) next.add(replacement)\n                inserted = true\n              }\n            } else next.add(tc)\n          }\n          if (!inserted) for (const replacement of replacements) next.add(replacement)\n          this.#turnToolCalls = next\n        },\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) => Promise<Retrievable>\n  /** Updates an existing retrievable record in the persistence layer. */\n  declare readonly mutateRetrievable: (v: Retrievable) => Promise<Retrievable>\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  /** Replaces a complete colliding tool-call group when storage supports it. */\n  declare readonly replaceToolCallGroup: (\n    ids: readonly string[],\n    replacements: readonly ToolCall[]\n  ) => 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 { autoSpoolRetrievable, assertUniqueRetrievableIds } from '../utils/retrievable_spool'\nimport {\n  E_INVALID_LLM_EXECUTION_CONTEXT,\n  E_LLM_EXECUTION_GATE_NOT_SUPPORTED,\n  E_LLM_EXECUTION_ALREADY_SIGNALLED,\n  E_ARTIFACT_ID_COLLISION,\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/** Atomically persists a replacement for a complete group of colliding tool calls. */\nexport type ToolCallGroupReplaceFn = (\n  ctx: DispatchContext,\n  removedIds: readonly string[],\n  replacements: readonly ToolCall[]\n) => 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  /** Optionally replaces a complete tool-call id group in one transaction. */\n  replaceToolCallGroup?: ToolCallGroupReplaceFn\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  // eslint-disable-next-line adk/require-validator-any-required -- map value type-arg: stash holds arbitrary values; disposition is set by .default({}) on the object\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  replaceToolCallGroup: validator.function().arity(3).optional(),\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  #replaceToolCallGroup: ToolCallGroupReplaceFn | undefined\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.#replaceToolCallGroup = resolved.replaceToolCallGroup\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: async () => {\n          const recs = await this.#fetchRetrievables(this)\n          assertUniqueRetrievableIds(recs)\n          return Promise.all(recs.map((r) => autoSpoolRetrievable(this, r)))\n        },\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      replaceToolCallGroup: {\n        value: (ids: readonly string[], replacements: readonly ToolCall[]) =>\n          this.#doReplaceToolCallGroup(ids, replacements),\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  /**\n   * Replaces every member of `set` sharing `id` with `replacement`, preserving the ORIGINAL\n   * insertion position of the first match rather than appending at the end.\n   *\n   * @remarks\n   * `Set.add()` compares by reference, not id — a mutated instance is a NEW object, so the stale\n   * instance(s) must be found and removed or they coexist with the replacement forever. ALL\n   * matches are removed, not just the first: `store*` never deduplicated ids either, so more than\n   * one stale copy can already exist before a mutation runs. Rebuilding the Set (rather than\n   * `delete` + `add`) additionally preserves insertion-order position: several adapters, and this\n   * battery's own {@link @nhtio/adk!buildOrderingTimeline}-style helpers, use Set iteration order\n   * as the deterministic tie-break for primitives sharing an identical timestamp — silently moving\n   * a mutated primitive to the end of iteration order would change that tie-break for no reason\n   * tied to the mutation's actual content.\n   */\n  #replaceById<T extends { id: string }>(set: Set<T>, id: string, replacement: T): Set<T> {\n    const next = new Set<T>()\n    let inserted = false\n    for (const existing of set) {\n      if ((existing as any).id === id) {\n        if (!inserted) {\n          next.add(replacement)\n          inserted = true\n        }\n        continue\n      }\n      next.add(existing)\n    }\n    if (!inserted) next.add(replacement)\n    return next\n  }\n\n  async #doMutateMemory(v: Memory): Promise<void> {\n    this.#turnMemories = this.#replaceById(this.#turnMemories, (v as any).id, 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  #checkArtifactIdCollision(id: string, source: 'retrievable' | 'toolCall'): void {\n    const other = source === 'retrievable' ? this.#turnToolCalls : this.#turnRetrievables\n    if ([...other].some((v) => v.id === id)) throw new E_ARTIFACT_ID_COLLISION([id])\n  }\n\n  async #doStoreRetrievable(v: Retrievable): Promise<Retrievable> {\n    this.#checkArtifactIdCollision(v.id, 'retrievable')\n    const record = await autoSpoolRetrievable(this, v)\n    this.#turnRetrievables.add(record)\n    await this.#storeRetrievable(this, record)\n    void this.#hooks.runner('storedRetrievable').run(record)\n    return record\n  }\n\n  async #doMutateRetrievable(v: Retrievable): Promise<Retrievable> {\n    this.#checkArtifactIdCollision(v.id, 'retrievable')\n    const record = await autoSpoolRetrievable(this, v)\n    this.#turnRetrievables = this.#replaceById(this.#turnRetrievables, record.id, record)\n    await this.#mutateRetrievable(this, record)\n    void this.#hooks.runner('mutatedRetrievable').run(record)\n    return record\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 = this.#replaceById(this.#turnMessages, (v as any).id, 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 = this.#replaceById(this.#turnThoughts, (v as any).id, 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.#checkArtifactIdCollision(v.id, 'toolCall')\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    this.#checkArtifactIdCollision(v.id, 'toolCall')\n    // Checksum is over tool+args, which the ORDINARY case does not change on mutation — but that\n    // is a convention, not an enforced invariant: a caller can construct a replacement with a\n    // different checksum (different tool/args). Reconcile #toolCallChecksums against every\n    // displaced instance's ACTUAL checksum (decrement) before crediting the replacement's\n    // (increment), the same way #doDeleteToolCall/#doStoreToolCall do — otherwise the map\n    // silently drifts out of sync with what #turnToolCalls really contains.\n    for (const tc of this.#turnToolCalls) {\n      if ((tc as any).id === (v as any).id) {\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      }\n    }\n    const prev = this.#toolCallChecksums.get(v.checksum) ?? 0\n    this.#toolCallChecksums.set(v.checksum, prev + 1)\n    this.#turnToolCalls = this.#replaceById(this.#turnToolCalls, (v as any).id, 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  /**\n   * Replaces an entire colliding id group. Persistence commits before local state is changed so a\n   * failed write cannot leave the context half-renamed. The fallback deletes every member before\n   * storing any replacement: a consumer-side `DELETE WHERE id` must not remove a newly stored row.\n   */\n  async #doReplaceToolCallGroup(\n    ids: readonly string[],\n    replacements: readonly ToolCall[]\n  ): Promise<void> {\n    if (this.#replaceToolCallGroup) {\n      await this.#replaceToolCallGroup(this, ids, replacements)\n    } else {\n      const deletedIds: string[] = []\n      try {\n        for (const id of ids) {\n          await this.#deleteToolCall(this, id)\n          deletedIds.push(id)\n        }\n        for (const replacement of replacements) await this.#storeToolCall(this, replacement)\n      } catch (error) {\n        if (isError(error)) {\n          ;(error as Error & { deletedIds: string[] }).deletedIds = [...deletedIds]\n        }\n        throw error\n      }\n    }\n\n    const idSet = new Set(ids)\n    const next = new Set<ToolCall>()\n    let inserted = false\n    for (const tc of this.#turnToolCalls) {\n      if (idSet.has(tc.id)) {\n        if (!inserted) {\n          for (const replacement of replacements) next.add(replacement)\n          inserted = true\n        }\n      } else next.add(tc)\n    }\n    if (!inserted) for (const replacement of replacements) next.add(replacement)\n    this.#turnToolCalls = next\n    // Recompute rather than reuse mutate/delete accounting: collisions can double-count a checksum.\n    this.#toolCallChecksums = new Map()\n    for (const tc of this.#turnToolCalls) {\n      this.#toolCallChecksums.set(tc.checksum, (this.#toolCallChecksums.get(tc.checksum) ?? 0) + 1)\n    }\n    for (const id of ids) void this.#hooks.runner('deletedToolCall').run(id)\n    for (const replacement of replacements)\n      void this.#hooks.runner('storedToolCall').run(replacement)\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<Retrievable>\n  /** Updates an existing retrievable record in the local Set and persistence layer. */\n  declare readonly mutateRetrievable: (v: Retrievable) => Promise<Retrievable>\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  /** Replaces a complete colliding tool-call group and persists the replacement. */\n  declare readonly replaceToolCallGroup: (\n    ids: readonly string[],\n    replacements: readonly ToolCall[]\n  ) => 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 { ToolRegistry } from './classes/tool_registry'\nimport { canonicalStringify } from './utils/canonical_json'\nimport { SpooledArtifact } from './classes/spooled_artifact'\nimport { TurnContext } from './contracts/turn_runner_context'\nimport { DispatchContext } from './contracts/dispatch_context'\nimport { normalizeRetrievables } from './utils/retrievable_spool'\nimport { runWithEstimationWarnings } from './utils/estimation_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 { EstimationWarning } from './utils/estimation_context'\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  WarningEvent,\n  GenerationStats,\n  GenerationStatsEvent,\n  ContextDelta,\n  DispatchRunnerFunctionalHooks,\n  DispatchRunnerObservabilityHooks,\n  DispatchRunnerFunctionalHookRegistrations,\n  DispatchRunnerObservabilityHookRegistrations,\n} from './types/dispatch_runner'\n\n/**\n * Normalise a thrown/nacked value into an `Error` suitable for use as an exception `cause`. A strict\n * `Error` (per {@link isError}, which is cross-realm-safe) passes through unchanged; anything else — a\n * string, a plain object, a cross-realm error whose `instanceof Error` is false, a WASM/DOM value — is\n * wrapped in a real `Error` whose message is the value's best string form, with the original preserved on\n * `.cause`. This guarantees an `E_LLM_EXECUTION_EXECUTOR_ERROR` (or any wrapper) always carries a\n * meaningful, Error-shaped cause: the true failure is never reduced to the generic default message, and\n * downstream root-cause unwrapping / `isError` checks keep working.\n */\nconst toErrorCause = (value: unknown): Error => {\n  if (isError(value)) return value\n  let text: string\n  try {\n    text =\n      typeof value === 'string'\n        ? value\n        : value === undefined\n          ? 'undefined'\n          : (JSON.stringify(value) ?? String(value))\n  } catch {\n    text = String(value)\n  }\n  return new Error(`non-Error thrown by executor: ${text}`, { cause: value })\n}\n\n/**\n * Build an {@link @nhtio/adk!E_LLM_EXECUTION_EXECUTOR_ERROR} whose own `message` names the underlying\n * failure, with the original preserved on `.cause`.\n *\n * @remarks\n * The cause CHAIN being intact is not the same as the failure being diagnosable: the overwhelmingly\n * common consumer habit is to log `err.message`, and a static wrapper text gives such a caller no\n * signal at all — not even the category of failure. A client-side validation error inside a battery\n * looked identical to a transport failure, an engine abort, or a bug in the executor itself.\n *\n * The static text is kept as the PREFIX so existing log greps and string matches keep working; the\n * cause text is joined to it with `: ` — the static text's own trailing period is dropped first, so the\n * result reads as one sentence instead of two run together. Appending is skipped when the cause adds\n * nothing (no message, or a message identical to the prefix) so the common case is byte-for-byte\n * unchanged.\n *\n * `cause.message` is NOT assumed to be a string, and coercing it is NOT assumed to succeed. `isError`\n * (and therefore `toErrorCause`) accepts anything Error-SHAPED via a cross-realm prototype check and\n * never validates `message`'s type, so a duck-typed or cross-realm error can carry a non-string\n * `message`. Two ways that bites, both verified:\n * - a bare `.trim()` on a non-string throws a TypeError;\n * - even a type-guarded `String()` throws when `message` is an object with a hostile\n *   `toString`/`Symbol.toPrimitive`.\n *\n * Either one escapes this helper, so NO wrapper is returned: the `runner('error')` observability hook\n * never fires and both the executor error and its cause chain are lost — the exact failure class this\n * helper exists to make diagnosable. Enrichment is therefore best-effort: any failure to derive text\n * falls back to the bare static message, because a wrapper with a terse message beats no wrapper.\n *\n * `message` is assigned post-construction rather than passed in: the exception is produced by\n * `createException`, whose constructor takes only {@link @nhtio/adk!ExceptionOptions} (no message\n * override), and widening that public signature is not worth the reach of this change.\n */\nconst executorError = (value: unknown): BaseException => {\n  const cause = toErrorCause(value)\n  const wrapped = new E_LLM_EXECUTION_EXECUTOR_ERROR({ cause }) as unknown as BaseException\n  const base = wrapped.message\n  let detail = ''\n  try {\n    const rawDetail: unknown = cause.message\n    detail = (typeof rawDetail === 'string' ? rawDetail : String(rawDetail ?? '')).trim()\n  } catch {\n    // Hostile `message` (throwing toString / Symbol.toPrimitive). Keep the static text and move on —\n    // never let enrichment be the reason the caller loses the real error.\n    detail = ''\n  }\n  if (detail.length > 0 && detail !== base) {\n    wrapped.message = `${base.replace(/\\.$/, '')}: ${detail}`\n  }\n  return wrapped\n}\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\n/**\n * Runs a single dispatch iteration of an agentic turn: it drives the executor through the\n * input/output middleware pipelines, emitting functional and observability hook events along the\n * way. Construction is gated — obtain one via the static {@link DispatchRunner.dispatch} entry\n * point rather than `new`.\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  /**\n   * Construction is gated by an internal sentinel `token` — call the static\n   * {@link DispatchRunner.dispatch} entry point instead of `new`.\n   *\n   * @internal\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({\n        cause: isError(err) ? err : undefined,\n      })\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    await normalizeRetrievables(llmCtx)\n    if (resolved.source) {\n      // Write the now-spooled records back onto the source TurnContext's own working set, so a\n      // subsequent dispatch from the same TurnContext reuses the existing artifact handle instead\n      // of re-encoding and re-storing the same plain-string content from scratch every time.\n      for (const record of llmCtx.turnRetrievables) {\n        runner.#replaceById(resolved.source.turnRetrievables, record.id, record)\n      }\n    }\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(), {\n        once: true,\n      })\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: async (_c, v) => {\n          return source.storeRetrievable(v) as unknown as Promise<void>\n        },\n        mutateRetrievable: async (_c, v) => {\n          return source.mutateRetrievable(v) as unknown as Promise<void>\n        },\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        replaceToolCallGroup: (_c, ids, replacements) =>\n          source.replaceToolCallGroup(ids, replacements),\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({\n        op: 'store',\n        type: 'standingInstruction',\n        value: v,\n      })\n    })\n    ctxHooks.add('mutatedStandingInstruction', (v) => {\n      this.#deltaQueue.push({\n        op: 'mutate',\n        type: 'standingInstruction',\n        value: v,\n      })\n    })\n    ctxHooks.add('deletedStandingInstruction', (v) => {\n      this.#deltaQueue.push({\n        op: 'delete',\n        type: 'standingInstruction',\n        value: v,\n      })\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 reportGenerationStats = (stats: GenerationStats): void => {\n      const event: GenerationStatsEvent = {\n        ...stats,\n        dispatchId: ctx.dispatchId,\n        iteration: ctx.iteration,\n        emittedAt: DateTime.now(),\n      }\n      void observabilityHooks.runner('generationStats').run(event)\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      reportGenerationStats,\n    }\n  }\n\n  // ── Iteration loop ────────────────────────────────────────────────────────\n\n  /**\n   * Forge artifact-reader tools from the current turn's tool-call results and register them into\n   * `ctx.tools`, so the forged readers are first-class members of the tool set the whole dispatch-input plane\n   * sees (budget passes, gates, observability). This is the GENERATION step — deterministic and generic;\n   * batteries own only REPRESENTATION (rendering the declarations + resolving the model's calls).\n   *\n   * Called once per iteration before the input pipeline. Idempotent within a dispatch by construction:\n   * 1. `pruneEphemeral()` drops the previous iteration's forged readers (whose `callId` enum is now stale —\n   *    new tool calls made last iteration must widen the enum).\n   * 2. Collect the unique `SpooledArtifact` subclasses across `turnToolCalls` results, covering BOTH a single\n   *    artifact result and an array-of-artifacts result.\n   * 3. `forgeTools(ctx)` per ctor, merged with `onCollision:'keep'` so a JSON subclass's base+JSON readers\n   *    win over a plain base forge of the same names (the subclass already composes base+JSON).\n   * 4. Register each forged tool into `ctx.tools` (`overwrite:true` → idempotent re-register within a run).\n   * 5. Bind ephemeral pruning to `ack` exactly once per dispatch (the forged tools are `ephemeral:true`, so\n   *    they are pruned when the dispatch acks — the lifecycle is unchanged from the battery-local era).\n   */\n  #forgeArtifactTools(ctx: DispatchContext): void {\n    // 1. Drop stale forged readers from a prior iteration (their callId enum excludes newer calls).\n    ctx.tools.pruneEphemeral()\n\n    // 2. Collect unique SpooledArtifact subclasses producing this turn's results (single OR array results).\n    const ctors = new Set<{ forgeTools: (c: DispatchContext) => ToolRegistry }>()\n    for (const tc of ctx.turnToolCalls) {\n      const results = (tc as { results?: unknown }).results\n      const items = Array.isArray(results) ? results : [results]\n      for (const item of items) {\n        if (!SpooledArtifact.isSpooledArtifact(item)) continue\n        const ctor = (item as SpooledArtifact).constructor as unknown as {\n          forgeTools?: (c: DispatchContext) => ToolRegistry\n        }\n        if (typeof ctor.forgeTools === 'function') {\n          ctors.add(ctor as { forgeTools: (c: DispatchContext) => ToolRegistry })\n        }\n      }\n    }\n    for (const retrievable of ctx.turnRetrievables) {\n      if (retrievable.inline || !SpooledArtifact.isSpooledArtifact(retrievable.content)) continue\n      const ctor = (retrievable.content as SpooledArtifact).constructor as unknown as {\n        forgeTools?: (c: DispatchContext) => ToolRegistry\n      }\n      if (typeof ctor.forgeTools === 'function') {\n        ctors.add(ctor as { forgeTools: (c: DispatchContext) => ToolRegistry })\n      }\n    }\n    if (ctors.size === 0) return\n\n    // 3. Forge each subclass's readers and combine. 'keep' = the first registry's tool wins on a name\n    //    collision (a JSON subclass forge composes base+JSON already, so keep it over a plain base forge).\n    const forged = ToolRegistry.merge(\n      [...ctors].map((c) => c.forgeTools(ctx)),\n      { onCollision: 'keep' }\n    )\n    if (forged.all().length === 0) return\n\n    // 4. Register the forged readers into ctx.tools so every downstream consumer (middleware, the executor's\n    //    representation step) sees the SAME set. overwrite:true keeps this idempotent across iterations.\n    for (const tool of forged.all()) {\n      ctx.tools.register(tool, true)\n      if (forged.hidden().some((h) => h.name === tool.name)) ctx.tools.hide(tool.name)\n    }\n\n    // 5. Ephemeral prune fires on ack; bind exactly once per dispatch (iteration 0) to avoid stacking\n    //    onAck subscriptions across iterations.\n    if (ctx.iteration === 0) ctx.tools.bindContext(ctx)\n  }\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    // Publish this dispatch's warn-sink for the duration of the run so a token estimation performed\n    // anywhere within (an executor's overflow guard, a pipeline, a gate) can DEGRADE-and-warn instead of\n    // throwing — the estimator reads the ambient sink (see utils/estimation_context). A dispatch is the\n    // INNERMOST scope, so when it runs inside a TurnRunner this sink (which carries dispatchId/iteration)\n    // takes precedence over the turn's. Non-fatal: `warning`, never `error`.\n    const emitEstimationWarning = (w: EstimationWarning): void => {\n      const event: WarningEvent = {\n        dispatchId: llmCtx.dispatchId,\n        iteration: llmCtx.iteration,\n        emittedAt: DateTime.now(),\n        source: 'dispatch-runner',\n        kind: 'token-estimation-degraded',\n        message: `token estimation for encoding \"${String(w.encoding)}\" failed; fell back to a char-based estimate`,\n        error: w.error,\n        payload: { encoding: w.encoding, textPreview: w.textPreview },\n      }\n      void this.#observabilityHooks.runner('warning').run(event)\n    }\n\n    await runWithEstimationWarnings(emitEstimationWarning, async () => {\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          // Forge artifact-reader tools into ctx.tools BEFORE the input pipeline, so the forged readers are\n          // first-class members of the tool set that ALL input middleware (budget/subtractive passes, gates,\n          // observability taps) can measure, evaluate, and mutate — not a battery-local set invisible to the\n          // dispatch-input plane. Runs per-iteration because ctx.turnToolCalls grows across iterations (an\n          // artifact produced in iteration N only appears in N+1). Generation is a generic core concern;\n          // batteries keep only REPRESENTATION (rendering declarations + resolving calls) and read ctx.tools.\n          this.#forgeArtifactTools(llmCtx)\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            // Preserve the thrown value as the cause — ALWAYS, even when it is not a strict `Error`. An\n            // executor can reject with a non-Error (a string, a cross-realm error that fails `instanceof`,\n            // a WASM/DOM value); the old `isError(err) ? err : undefined` DROPPED those, leaving a\n            // cause-less wrapper whose only text was the generic \"…callback threw an error.\" — so the real\n            // failure was unrecoverable and undiagnosable downstream. `toErrorCause` normalises any\n            // non-Error into a real Error carrying its stringified value, keeping the `.cause` chain\n            // Error-shaped for `isError`/root-cause unwrapping — and `executorError` additionally names\n            // the failure in the wrapper's OWN message, for the many callers that only log `.message`.\n            const wrapped = executorError(err)\n            void this.#observabilityHooks.runner('error').run(wrapped)\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          : // Preserve a non-BaseException nack value as the cause too (see the executor-throw path):\n            // a raw string / cross-realm error must not be dropped to a cause-less generic wrapper.\n            executorError(nackErr)\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\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  /**\n   * Replaces every member of `set` sharing `id` with `replacement`, preserving the ORIGINAL\n   * insertion position of the first match rather than appending at the end.\n   *\n   * @remarks\n   * `Set.add()` compares by reference, not id — a mutated instance is a NEW object, so the stale\n   * instance(s) must be removed or they coexist with the replacement forever (this is the exact\n   * defect {@link @nhtio/adk!DispatchContext}'s own `#doMutate*` methods were fixed to avoid — a\n   * child dispatch context's mutation is otherwise correctly deduplicated locally, but flushing\n   * that mutation BACK to this parent `TurnContext`'s Sets via `#applyDeltaToParent` re-introduces\n   * the identical bug if this method just appended). `set` is rebuilt in place via `clear()` +\n   * re-add, rather than reassigned, since `TurnContext` exposes no setter for these Sets — only\n   * `set.add`/`set.delete` are available to a caller outside the class.\n   */\n  #replaceById<T extends { id: string }>(set: Set<T>, id: string, replacement: T): void {\n    const rebuilt: T[] = []\n    let inserted = false\n    for (const existing of set) {\n      if ((existing as any).id === id) {\n        if (!inserted) {\n          rebuilt.push(replacement)\n          inserted = true\n        }\n        continue\n      }\n      rebuilt.push(existing)\n    }\n    if (!inserted) rebuilt.push(replacement)\n    set.clear()\n    for (const item of rebuilt) set.add(item)\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') ctx.turnMemories.add(value as Memory)\n      else if (op === 'mutate') {\n        const v = value as Memory\n        this.#replaceById(ctx.turnMemories, (v as any).id, v)\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') ctx.turnRetrievables.add(value as Retrievable)\n      else if (op === 'mutate') {\n        const v = value as Retrievable\n        this.#replaceById(ctx.turnRetrievables, (v as any).id, v)\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') ctx.turnMessages.add(value as Message)\n      else if (op === 'mutate') {\n        const v = value as Message\n        this.#replaceById(ctx.turnMessages, (v as any).id, v)\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') ctx.turnThoughts.add(value as Thought)\n      else if (op === 'mutate') {\n        const v = value as Thought\n        this.#replaceById(ctx.turnThoughts, (v as any).id, v)\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') ctx.turnToolCalls.add(value as ToolCall)\n      else if (op === 'mutate') {\n        const v = value as ToolCall\n        this.#replaceById(ctx.turnToolCalls, (v as any).id, v)\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":";;;;;;;;;;;;AAWA,IAAa,oBAAoB,UAA6D;CAC5F,YAAY,IAAI,YAAY,EAAE,OAAO,IAAI,EAAE;CAC3C,WAAW,KAAK,WAAW,IAAI,IAAI,KAAK,MAAM,IAAI,EAAE;AACtD;AAEA,eAAsB,qBACpB,KACA,GACsB;CACtB,IAAI,CAAC,YAAY,cAAc,EAAE,OAAO,KAAK,EAAE,QAAQ,WAAW,EAAE,QAAQ,OAAO;CACnF,MAAM,OAAO,EAAE,QAAQ,SAAS;CAChC,MAAM,QAAQ,iBAAiB,IAAI;CACnC,MAAM,SAAS,MAAM,IAAI,sBAAsB,EAAE,IAAI,IAAI;CAEzD,MAAM,WAAW,MADJ,EAAE,sBAAsB,MAA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