import { Registry } from "../classes/registry"; import { Tokenizable } from "../classes/tokenizable"; import type { Tool } from "../classes/tool"; import type { Memory } from "../classes/memory"; import type { Message } from "../classes/message"; import type { Thought } from "../classes/thought"; import type { SpoolReader } from "./spool_reader"; import type { MediaReader } from "./media_reader"; import type { ToolCall } from "../classes/tool_call"; import type { ConduitBytes } from "./dispatch_context"; import type { Retrievable } from "../classes/retrievable"; import type { ToolRegistry } from "../classes/tool_registry"; import type { EmitMessageFn, EmitThoughtFn, EmitToolCallFn, EmitToolExecutionEndFn, EmitToolExecutionStartFn, OpenGateFn } from "../types/turn_runner"; /** * Plain input object supplied to {@link TurnContext} at construction time. * * @remarks * Validated against `turnContextSchema` before the `TurnContext` instance is created. * Fields will grow as the turn execution model takes shape (e.g. input message, tool * definitions, model client config). */ export interface RawTurnContext { /** `AbortController` whose signal can be used to cancel the turn mid-flight. */ turnAbortController: AbortController; /** A registry for arbitrary additional data to be added to the context as needed; initially empty. */ stash?: Record; /** The system prompt guiding the agent's behavior for this turn. */ systemPrompt: string | Tokenizable; /** Standing instructions for the agent, applied to every turn. */ standingInstructions: (string | Tokenizable)[]; } /** * A fully-resolved {@link RawTurnContext} where all optional fields have been filled in by the * schema (e.g. `stash` defaulted to `{}`). * * @remarks * This is the shape returned by `turnContextSchema` after validation — use it wherever a * guaranteed-present context is needed rather than the raw caller-supplied input. */ export type ResolvedTurnContext = Required; /** * Validator schema used to validate a {@link RawTurnContext} before constructing a {@link TurnContext}. * * @remarks * Validates all four fields of {@link RawTurnContext}: * - `turnAbortController` — required `AbortController` instance. * - `stash` — optional string-keyed object; defaults to `{}`. * - `systemPrompt` — required string or {@link @nhtio/adk!Tokenizable}, via {@link @nhtio/adk!Tokenizable.schema}. * - `standingInstructions` — optional array of strings or {@link @nhtio/adk!Tokenizable} instances, each * validated via {@link @nhtio/adk!Tokenizable.schema}; defaults to `[]`. * * Throws a `ValidationException` (via {@link validateOrThrow}) when validation fails. */ export declare const turnContextSchema: import("@nhtio/validation").ObjectSchema; /** * A function that retrieves the memories relevant to the current turn. * * @remarks * Receives the active {@link TurnContext} so implementations can filter or rank memories * based on turn-specific state (e.g. the system prompt, standing instructions, or stash). * May be synchronous or asynchronous. */ export type MemoryRetrievalFn = (ctx: TurnContext) => Memory[] | Promise; /** * A function that retrieves the retrievable (RAG) records relevant to the current turn. * * @remarks * Receives the active {@link TurnContext} so implementations can rank, filter, or compose * retrieval results against the turn-specific state (system prompt, standing instructions, etc.). * The retrieval middleware that produces these records is responsible for assigning each one's * `trustTier` — batteries MUST NOT auto-classify retrieved content. * May be synchronous or asynchronous. */ export type RetrievableRetrievalFn = (ctx: TurnContext) => Retrievable[] | Promise; /** * A function that retrieves the conversation messages relevant to the current turn. * * @remarks * Receives the active {@link TurnContext} so implementations can apply turn-aware filtering or * windowing. Returns only `user` and `assistant` {@link @nhtio/adk!Message} entries — system instructions * and tool results are not part of the persisted message history. * May be synchronous or asynchronous. */ export type MessageRetrievalFn = (ctx: TurnContext) => Message[] | Promise; /** * A function that retrieves the thought traces relevant to the current turn. * * @remarks * Receives the active {@link TurnContext} so implementations can apply turn-aware filtering or * attribution (e.g. filtering to a specific agent's identity in multi-agent conversations). * May be synchronous or asynchronous. */ export type ThoughtRetrievalFn = (ctx: TurnContext) => Thought[] | Promise; /** * A function that retrieves the tool call records relevant to the current turn. * * @remarks * Receives the active {@link TurnContext} so implementations can filter by completion state, * agent identity, or any other turn-specific criteria. * May be synchronous or asynchronous. */ export type ToolCallRetrievalFn = (ctx: TurnContext) => ToolCall[] | Promise; /** * A function that retrieves the tools available for the current turn. * * @remarks * Receives the active {@link TurnContext} so implementations can apply turn-aware filtering * (e.g. RBAC scopes, feature flags). May be synchronous or asynchronous. */ export type ToolsRetrievalFn = (ctx: TurnContext) => Tool[] | Promise; /** * A function that refreshes and returns the standing instructions for the current turn. * * @remarks * Called to re-derive standing instructions mid-turn when they may have changed. * May be synchronous or asynchronous. */ export type StandingInstructionsRefreshFn = (ctx: TurnContext) => (string | Tokenizable)[] | Promise<(string | Tokenizable)[]>; /** Stores a new standing instruction in the persistence layer. */ export type StandingInstructionStoreFn = (ctx: TurnContext, v: string | Tokenizable) => void | Promise; /** Updates an existing standing instruction in the persistence layer. */ export type StandingInstructionMutateFn = (ctx: TurnContext, v: string | Tokenizable) => void | Promise; /** Removes a standing instruction from the persistence layer. */ export type StandingInstructionDeleteFn = (ctx: TurnContext, v: string | Tokenizable) => void | Promise; /** Stores a new memory in the persistence layer. */ export type MemoryStoreFn = (ctx: TurnContext, v: Memory) => void | Promise; /** Updates an existing memory in the persistence layer. */ export type MemoryMutateFn = (ctx: TurnContext, v: Memory) => void | Promise; /** Removes a memory from the persistence layer by ID. */ export type MemoryDeleteFn = (ctx: TurnContext, id: string) => void | Promise; /** Stores a new retrievable record in the persistence layer. */ export type RetrievableStoreFn = (ctx: TurnContext, v: Retrievable) => void | Promise; /** Updates an existing retrievable record in the persistence layer. */ export type RetrievableMutateFn = (ctx: TurnContext, v: Retrievable) => void | Promise; /** Removes a retrievable record from the persistence layer by ID. */ export type RetrievableDeleteFn = (ctx: TurnContext, id: string) => void | Promise; /** Stores a new message in the persistence layer. */ export type MessageStoreFn = (ctx: TurnContext, v: Message) => void | Promise; /** Updates an existing message in the persistence layer. */ export type MessageMutateFn = (ctx: TurnContext, v: Message) => void | Promise; /** Removes a message from the persistence layer by ID. */ export type MessageDeleteFn = (ctx: TurnContext, id: string) => void | Promise; /** Stores a new thought in the persistence layer. */ export type ThoughtStoreFn = (ctx: TurnContext, v: Thought) => void | Promise; /** Updates an existing thought in the persistence layer. */ export type ThoughtMutateFn = (ctx: TurnContext, v: Thought) => void | Promise; /** Removes a thought from the persistence layer by ID. */ export type ThoughtDeleteFn = (ctx: TurnContext, id: string) => void | Promise; /** Stores a new tool call in the persistence layer. */ export type ToolCallStoreFn = (ctx: TurnContext, v: ToolCall) => void | Promise; /** Updates an existing tool call in the persistence layer. */ export type ToolCallMutateFn = (ctx: TurnContext, v: ToolCall) => void | Promise; /** Removes a tool call from the persistence layer by ID. */ export type ToolCallDeleteFn = (ctx: TurnContext, id: string) => void | Promise; /** Optionally persists a complete tool-call group replacement atomically. */ export type ToolCallGroupReplaceFn = (ctx: TurnContext, removedIds: readonly string[], replacements: readonly ToolCall[]) => void | Promise; /** * Persists tool-generated media bytes into consumer storage and returns a {@link @nhtio/adk!MediaReader}. * A byte-persistence conduit, not a mutation — returns a value and touches no turn state. */ export type MediaBytesStoreFn = (ctx: TurnContext, id: string, bytes: ConduitBytes) => MediaReader | Promise; /** * Persists extracted retrievable text bytes into consumer storage and returns a * {@link @nhtio/adk!SpoolReader}. A byte-persistence conduit, not a mutation. */ export type RetrievableBytesStoreFn = (ctx: TurnContext, id: string, bytes: ConduitBytes) => SpoolReader | Promise; /** * The validated, strongly-typed context object threaded through every middleware step in a * single agent turn. * * @remarks * Constructed from a {@link RawTurnContext} by {@link @nhtio/adk!TurnRunner.run}. Middleware functions * receive this object and use it to read and share state across pipeline steps. */ export declare class TurnContext { #private; /** * Returns `true` if `value` is a {@link TurnContext} instance. * * @remarks * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety. The ADK does not export the * `TurnContext` class itself as a constructable value — use this guard plus the * {@link TurnContext} type for runtime detection and TypeScript narrowing. * * @param value - The value to test. * @returns `true` when `value` is a {@link TurnContext} instance. */ static isTurnContext(value: unknown): value is TurnContext; /** Unique identifier for this turn, generated as a UUIDv6 at construction time. */ readonly id: string; /** `true` when the turn's `AbortController` signal has fired. */ readonly aborted: boolean; /** The `AbortSignal` from the turn's `AbortController`. */ readonly abortSignal: AbortSignal; /** * Aborts the turn's `AbortController` with the supplied reason. Middleware should call this * when refusing the turn — the runner reads `aborted` between every stage and short-circuits * cleanly: `turnEnd` still fires, no `error` event is emitted, and during dispatch * `dispatchEnd.status === 'aborted'` carries the operational signal. */ readonly abort: (reason?: unknown) => void; /** Arbitrary key-value store that middleware can read and write across pipeline steps. */ readonly stash: Registry; /** The system prompt guiding the agent's behaviour for this turn. */ readonly systemPrompt: Tokenizable; /** Standing instructions applied to every turn, in insertion order. */ readonly standingInstructions: Set; /** Memories loaded for this turn; populated by middleware after calling `fetchMemories()`. */ readonly turnMemories: Set; /** Retrievable records loaded for this turn; populated by middleware after calling `fetchRetrievables()`. */ readonly turnRetrievables: Set; /** Conversation messages loaded for this turn; populated by middleware after calling `fetchMessages()`. */ readonly turnMessages: Set; /** Thought traces loaded for this turn; populated by middleware after calling `fetchThoughts()`. */ readonly turnThoughts: Set; /** Tool call records loaded for this turn; populated by middleware after calling `fetchToolCalls()`. */ readonly turnToolCalls: Set; /** Fetches memories relevant to this turn; delegates to the callback supplied at construction. */ readonly fetchMemories: () => Memory[] | Promise; /** Fetches conversation messages relevant to this turn; delegates to the callback supplied at construction. */ readonly fetchMessages: () => Message[] | Promise; /** Fetches thought traces relevant to this turn; delegates to the callback supplied at construction. */ readonly fetchThoughts: () => Thought[] | Promise; /** Fetches tool call records relevant to this turn; delegates to the callback supplied at construction. */ readonly fetchToolCalls: () => ToolCall[] | Promise; /** Fetches tools available for this turn; delegates to the callback supplied at construction. */ readonly fetchTools: () => Tool[] | Promise; /** Refreshes and returns the standing instructions; delegates to the callback supplied at construction. */ readonly refreshStandingInstructions: () => (string | Tokenizable)[] | Promise<(string | Tokenizable)[]>; /** Stores a new standing instruction in the persistence layer. */ readonly storeStandingInstruction: (v: string | Tokenizable) => void | Promise; /** Updates an existing standing instruction in the persistence layer. */ readonly mutateStandingInstruction: (v: string | Tokenizable) => void | Promise; /** Removes a standing instruction from the persistence layer. */ readonly deleteStandingInstruction: (v: string | Tokenizable) => void | Promise; /** Stores a new memory in the persistence layer. */ readonly storeMemory: (v: Memory) => void | Promise; /** Updates an existing memory in the persistence layer. */ readonly mutateMemory: (v: Memory) => void | Promise; /** Removes a memory from the persistence layer by ID. */ readonly deleteMemory: (id: string) => void | Promise; /** Fetches retrievable records relevant to this turn; delegates to the callback supplied at construction. */ readonly fetchRetrievables: () => Retrievable[] | Promise; /** Stores a new retrievable record in the persistence layer. */ readonly storeRetrievable: (v: Retrievable) => Promise; /** Updates an existing retrievable record in the persistence layer. */ readonly mutateRetrievable: (v: Retrievable) => Promise; /** Removes a retrievable record from the persistence layer by ID. */ readonly deleteRetrievable: (id: string) => void | Promise; /** Stores a new message in the persistence layer. */ readonly storeMessage: (v: Message) => void | Promise; /** Updates an existing message in the persistence layer. */ readonly mutateMessage: (v: Message) => void | Promise; /** Removes a message from the persistence layer by ID. */ readonly deleteMessage: (id: string) => void | Promise; /** Stores a new thought in the persistence layer. */ readonly storeThought: (v: Thought) => void | Promise; /** Updates an existing thought in the persistence layer. */ readonly mutateThought: (v: Thought) => void | Promise; /** Removes a thought from the persistence layer by ID. */ readonly deleteThought: (id: string) => void | Promise; /** Stores a new tool call in the persistence layer. */ readonly storeToolCall: (v: ToolCall) => void | Promise; /** Updates an existing tool call in the persistence layer. */ readonly mutateToolCall: (v: ToolCall) => void | Promise; /** Removes a tool call from the persistence layer by ID. */ readonly deleteToolCall: (id: string) => void | Promise; /** Replaces a complete colliding tool-call group when storage supports it. */ readonly replaceToolCallGroup: (ids: readonly string[], replacements: readonly ToolCall[]) => Promise; /** * Persists tool-generated media bytes into consumer storage and returns a {@link @nhtio/adk!MediaReader}. * Low-level conduit — returns a value, touches no turn state; build a {@link @nhtio/adk!Media} from the * reader and persist the owning primitive separately. */ readonly storeMediaBytes: (id: string, bytes: ConduitBytes) => MediaReader | Promise; /** * Persists extracted retrievable text bytes into consumer storage and returns a * {@link @nhtio/adk!SpoolReader}. Wrap it in a {@link @nhtio/adk!SpooledArtifact} for `Retrievable.content` * and persist the record via {@link TurnContext.storeRetrievable} separately. */ readonly storeRetrievableBytes: (id: string, bytes: ConduitBytes) => SpoolReader | Promise; /** Emits a `message` event on the runner; may be called at any point during the turn. */ readonly emitMessage: EmitMessageFn; /** Emits a `thought` event on the runner; may be called at any point during the turn. */ readonly emitThought: EmitThoughtFn; /** Emits a `toolCall` event on the runner; may be called at any point during the turn. */ readonly emitToolCall: EmitToolCallFn; /** Emits a `toolExecutionStart` event on the observability bus; forwarded from `DispatchContext` by `DispatchRunner` when a tool is invoked inside a dispatch. */ readonly emitToolExecutionStart: EmitToolExecutionStartFn; /** Emits a `toolExecutionEnd` event on the observability bus; forwarded from `DispatchContext` by `DispatchRunner` when a tool finishes executing inside a dispatch. */ readonly emitToolExecutionEnd: EmitToolExecutionEndFn; /** Opens a turn gate and suspends until it resolves, rejects, times out, or is aborted. */ readonly waitFor: OpenGateFn; /** Turn-scoped tool registry constructed from the runner's baseline tools; middleware may trim or extend it. */ readonly tools: ToolRegistry; }