@nhtio/adk 0.1.0-master-445a9ed0 → 1.20260529.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/batteries/llm/openai_chat_completions/adapter.cjs +10 -9
- package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -1
- package/batteries/llm/openai_chat_completions/adapter.mjs +8 -8
- package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -1
- package/batteries/llm/openai_chat_completions/exceptions.cjs +1 -1
- package/batteries/llm/openai_chat_completions/helpers.cjs +16 -16
- package/batteries/llm/openai_chat_completions/helpers.cjs.map +1 -1
- package/batteries/llm/openai_chat_completions/helpers.d.ts +10 -10
- package/batteries/llm/openai_chat_completions/helpers.mjs +16 -16
- package/batteries/llm/openai_chat_completions/helpers.mjs.map +1 -1
- package/batteries/llm/openai_chat_completions/types.d.ts +6 -26
- package/batteries/llm/openai_chat_completions/validation.cjs +1 -3
- package/batteries/llm/openai_chat_completions/validation.cjs.map +1 -1
- package/batteries/llm/openai_chat_completions/validation.mjs +0 -2
- package/batteries/llm/openai_chat_completions/validation.mjs.map +1 -1
- package/batteries/llm/webllm_chat_completions/adapter.cjs +10 -9
- package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -1
- package/batteries/llm/webllm_chat_completions/adapter.mjs +8 -8
- package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -1
- package/batteries/llm/webllm_chat_completions/exceptions.cjs +1 -1
- package/batteries/llm/webllm_chat_completions/validation.cjs +1 -3
- package/batteries/llm/webllm_chat_completions/validation.cjs.map +1 -1
- package/batteries/llm/webllm_chat_completions/validation.mjs +0 -2
- package/batteries/llm/webllm_chat_completions/validation.mjs.map +1 -1
- package/batteries/storage/flydrive/index.d.ts +4 -10
- package/batteries/storage/flydrive.cjs +3 -12
- package/batteries/storage/flydrive.cjs.map +1 -1
- package/batteries/storage/flydrive.mjs +2 -11
- package/batteries/storage/flydrive.mjs.map +1 -1
- package/batteries/storage/in_memory/index.d.ts +17 -31
- package/batteries/storage/in_memory.cjs +30 -89
- package/batteries/storage/in_memory.cjs.map +1 -1
- package/batteries/storage/in_memory.mjs +30 -89
- package/batteries/storage/in_memory.mjs.map +1 -1
- package/batteries/storage/opfs/index.d.ts +4 -10
- package/batteries/storage/opfs.cjs +5 -55
- package/batteries/storage/opfs.cjs.map +1 -1
- package/batteries/storage/opfs.mjs +4 -54
- package/batteries/storage/opfs.mjs.map +1 -1
- package/batteries/tools/color.cjs +3 -3
- package/batteries/tools/color.mjs +2 -2
- package/batteries/tools/comparison.cjs +4 -3
- package/batteries/tools/comparison.cjs.map +1 -1
- package/batteries/tools/comparison.mjs +2 -2
- package/batteries/tools/data_structure.cjs +4 -3
- package/batteries/tools/data_structure.cjs.map +1 -1
- package/batteries/tools/data_structure.mjs +2 -2
- package/batteries/tools/datetime_extended.cjs +4 -4
- package/batteries/tools/datetime_extended.mjs +2 -2
- package/batteries/tools/datetime_math.cjs +3 -3
- package/batteries/tools/datetime_math.mjs +2 -2
- package/batteries/tools/encoding.cjs +4 -3
- package/batteries/tools/encoding.cjs.map +1 -1
- package/batteries/tools/encoding.mjs +2 -2
- package/batteries/tools/formatting.cjs +4 -3
- package/batteries/tools/formatting.cjs.map +1 -1
- package/batteries/tools/formatting.mjs +2 -2
- package/batteries/tools/geo_basics.cjs +3 -3
- package/batteries/tools/geo_basics.mjs +2 -2
- package/batteries/tools/math.cjs +4 -3
- package/batteries/tools/math.cjs.map +1 -1
- package/batteries/tools/math.mjs +2 -2
- package/batteries/tools/memory.cjs +7 -6
- package/batteries/tools/memory.cjs.map +1 -1
- package/batteries/tools/memory.mjs +5 -5
- package/batteries/tools/parsing.cjs +6 -5
- package/batteries/tools/parsing.cjs.map +1 -1
- package/batteries/tools/parsing.mjs +3 -3
- package/batteries/tools/retrievables.cjs +11 -11
- package/batteries/tools/retrievables.cjs.map +1 -1
- package/batteries/tools/retrievables.mjs +9 -10
- package/batteries/tools/retrievables.mjs.map +1 -1
- package/batteries/tools/standing_instructions.cjs +5 -4
- package/batteries/tools/standing_instructions.cjs.map +1 -1
- package/batteries/tools/standing_instructions.mjs +3 -3
- package/batteries/tools/statistics.cjs +5 -4
- package/batteries/tools/statistics.cjs.map +1 -1
- package/batteries/tools/statistics.mjs +3 -3
- package/batteries/tools/string_processing.cjs +4 -3
- package/batteries/tools/string_processing.cjs.map +1 -1
- package/batteries/tools/string_processing.mjs +2 -2
- package/batteries/tools/structured_data.cjs +4 -3
- package/batteries/tools/structured_data.cjs.map +1 -1
- package/batteries/tools/structured_data.mjs +2 -2
- package/batteries/tools/text_analysis.cjs +4 -4
- package/batteries/tools/text_analysis.mjs +3 -3
- package/batteries/tools/text_comparison.cjs +3 -3
- package/batteries/tools/text_comparison.mjs +2 -2
- package/batteries/tools/time.cjs +3 -3
- package/batteries/tools/time.mjs +2 -2
- package/batteries/tools/unit_conversion.cjs +3 -3
- package/batteries/tools/unit_conversion.mjs +2 -2
- package/batteries/tools.cjs +1 -1
- package/batteries/tools.mjs +1 -1
- package/batteries.cjs +1 -1
- package/batteries.mjs +1 -1
- package/chunk-KmRHZBOW.js +35 -0
- package/{common-aFmr9Oqs.mjs → common-DeZaonK1.mjs} +10 -76
- package/common-DeZaonK1.mjs.map +1 -0
- package/{common-BJ6V6dsH.js → common-Od8edUXU.js} +12 -89
- package/common-Od8edUXU.js.map +1 -0
- package/common.cjs +7 -9
- package/common.d.ts +0 -8
- package/common.mjs +7 -7
- package/{dispatch_runner-OimGCkk7.mjs → dispatch_runner-9j6bXHL3.mjs} +2 -34
- package/dispatch_runner-9j6bXHL3.mjs.map +1 -0
- package/{dispatch_runner-BWYNxmnp.js → dispatch_runner-CsoH0nld.js} +6 -37
- package/dispatch_runner-CsoH0nld.js.map +1 -0
- package/dispatch_runner.cjs +1 -1
- package/dispatch_runner.mjs +1 -1
- package/{exceptions-CSqzbL1N.js → exceptions-D5YrO9Vm.js} +2 -2
- package/{exceptions-CSqzbL1N.js.map → exceptions-D5YrO9Vm.js.map} +1 -1
- package/exceptions.cjs +2 -2
- package/factories.cjs +1 -1
- package/forge.cjs +4 -4
- package/forge.mjs +3 -3
- package/guards.cjs +9 -9
- package/guards.mjs +7 -7
- package/index.cjs +13 -13
- package/index.cjs.map +1 -1
- package/index.d.ts +1 -1
- package/index.mjs +10 -10
- package/index.mjs.map +1 -1
- package/lib/classes/retrievable.d.ts +4 -47
- package/lib/contracts/dispatch_context.d.ts +0 -44
- package/lib/contracts/turn_runner_config.d.ts +1 -5
- package/lib/contracts/turn_runner_context.d.ts +0 -25
- package/package.json +74 -74
- package/{runtime-BUDWyd-R.js → runtime-BJVkrGQe.js} +2 -2
- package/{runtime-BUDWyd-R.js.map → runtime-BJVkrGQe.js.map} +1 -1
- package/skills/adk-assembly/SKILL.md +2 -2
- package/{spooled_artifact-B_tVDDdB.mjs → spooled_artifact-C5ZtGxuJ.mjs} +2 -2
- package/{spooled_artifact-B_tVDDdB.mjs.map → spooled_artifact-C5ZtGxuJ.mjs.map} +1 -1
- package/{spooled_artifact-CFstzlqX.js → spooled_artifact-Cm9Te22K.js} +6 -5
- package/{spooled_artifact-CFstzlqX.js.map → spooled_artifact-Cm9Te22K.js.map} +1 -1
- package/spooled_artifact.cjs +2 -2
- package/spooled_artifact.mjs +2 -2
- package/{spooled_markdown_artifact-DWWak35I.mjs → spooled_markdown_artifact-BpUJol0W.mjs} +2 -2
- package/{spooled_markdown_artifact-DWWak35I.mjs.map → spooled_markdown_artifact-BpUJol0W.mjs.map} +1 -1
- package/{spooled_markdown_artifact-DK-T8Hy6.js → spooled_markdown_artifact-RRB113sy.js} +7 -6
- package/{spooled_markdown_artifact-DK-T8Hy6.js.map → spooled_markdown_artifact-RRB113sy.js.map} +1 -1
- package/{thought-DDqjQu3m.mjs → thought-CDb457b4.mjs} +2 -2
- package/{thought-DDqjQu3m.mjs.map → thought-CDb457b4.mjs.map} +1 -1
- package/{thought-DTsFRGdE.js → thought-DuN2PgdO.js} +6 -5
- package/{thought-DTsFRGdE.js.map → thought-DuN2PgdO.js.map} +1 -1
- package/{tool-cwJyEHI9.js → tool-COSeH8I6.js} +5 -4
- package/{tool-cwJyEHI9.js.map → tool-COSeH8I6.js.map} +1 -1
- package/{tool-q4LskG7K.mjs → tool-D2WB1EA1.mjs} +1 -1
- package/{tool-q4LskG7K.mjs.map → tool-D2WB1EA1.mjs.map} +1 -1
- package/{tool_call-BKIdAAoY.mjs → tool_call-BKyyxGaZ.mjs} +2 -2
- package/{tool_call-BKIdAAoY.mjs.map → tool_call-BKyyxGaZ.mjs.map} +1 -1
- package/{tool_call-3T0xTXlD.js → tool_call-DFgzcVcU.js} +6 -5
- package/{tool_call-3T0xTXlD.js.map → tool_call-DFgzcVcU.js.map} +1 -1
- package/{tool_registry-snPjF0zJ.js → tool_registry-Dkfprsck.js} +5 -39
- package/{tool_registry-snPjF0zJ.js.map → tool_registry-Dkfprsck.js.map} +1 -1
- package/{turn_runner-BScT8OgA.js → turn_runner-CMm2BHdX.js} +7 -10
- package/turn_runner-CMm2BHdX.js.map +1 -0
- package/{turn_runner-DRBLN2Y_.mjs → turn_runner-y7eyEcJH.mjs} +3 -7
- package/turn_runner-y7eyEcJH.mjs.map +1 -0
- package/turn_runner.cjs +1 -1
- package/turn_runner.mjs +1 -1
- package/types.d.ts +2 -2
- package/CHANGELOG.md +0 -49
- package/common-BJ6V6dsH.js.map +0 -1
- package/common-aFmr9Oqs.mjs.map +0 -1
- package/dispatch_runner-BWYNxmnp.js.map +0 -1
- package/dispatch_runner-OimGCkk7.mjs.map +0 -1
- package/lib/contracts/byte_store.d.ts +0 -93
- package/turn_runner-BScT8OgA.js.map +0 -1
- package/turn_runner-DRBLN2Y_.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"turn_runner-CMm2BHdX.js","names":["#id","#turnId","#reason","#payload","#createdAt","#settled","#schema","#controller","#promise","#resolve","#reject","#config","#inputRunner","#outputRunner","#functionalEmitter","#observabilityEmitter"],"sources":["../src/lib/classes/turn_gate.ts","../src/lib/contracts/turn_runner_config.ts","../src/lib/turn_runner.ts"],"sourcesContent":["import { DateTime } from 'luxon'\nimport { validator } from '@nhtio/validation'\nimport { validateOrThrow } from '../utils/validation'\nimport { isInstanceOf, isError, isObject } from '../utils/guards'\nimport {\n E_TURN_GATE_ABORTED,\n E_TURN_GATE_TIMEOUT,\n E_INVALID_TURN_GATE_RESOLUTION,\n E_INVALID_INITIAL_TURN_GATE_VALUE,\n} from '../exceptions/runtime'\nimport type { Schema } from '@nhtio/validation'\n\n/**\n * Plain input object supplied to {@link TurnGate} at construction time.\n *\n * @remarks\n * `turnId` and `abortSignal` are injected by the runner — callers constructing a gate via\n * `ctx.waitFor()` never supply them directly.\n *\n * `abortSignal` is `AbortSignal` (not `AbortController`) because the gate reacts to turn-level\n * cancellation but cannot trigger it. The gate owns its own internal `AbortController` for\n * `gate.abort()`.\n */\nexport interface RawTurnGate {\n /** Stable unique identifier for this gate. */\n id: string\n /** The ID of the turn that opened this gate. */\n turnId: string\n /** Human-readable label describing why this gate was opened (e.g. `'tool_approval'`). */\n reason: string\n /** Arbitrary data supplied to the gate opener; passed through to `turnGateOpen` listeners. */\n payload: unknown\n /** Optional validator schema for the resolution value. When present, `resolve()` validates before settling. */\n schema?: Schema\n /** Optional timeout in milliseconds. When elapsed the gate self-rejects with {@link @nhtio/adk!E_TURN_GATE_TIMEOUT}. */\n timeout?: number\n /** The turn's abort signal. When fired the gate self-rejects with {@link @nhtio/adk!E_TURN_GATE_ABORTED}. */\n abortSignal?: AbortSignal\n /** When this gate was created. */\n createdAt: string | number | Date | DateTime\n}\n\n/**\n * Fully-resolved {@link RawTurnGate} after schema validation.\n *\n * @internal\n */\ninterface ResolvedTurnGate {\n id: string\n turnId: string\n reason: string\n payload: unknown\n schema?: Schema\n timeout?: number\n abortSignal?: AbortSignal\n createdAt: DateTime\n}\n\n/**\n * Validator schema used to validate a {@link RawTurnGate} before constructing a {@link TurnGate}.\n *\n * @remarks\n * - `schema` and `abortSignal` are validated as opaque passthrough values.\n * - `timeout` must be a positive integer when provided.\n */\nconst rawTurnGateSchema = validator.object<RawTurnGate>({\n id: validator.string().required(),\n turnId: validator.string().required(),\n reason: validator.string().required(),\n payload: validator.any().required(),\n schema: validator\n .any()\n .custom((value, helpers) => {\n if (value === undefined || value === null) return undefined\n if (typeof (value as any).validate === 'function') return value\n return helpers.error('any.invalid')\n })\n .optional(),\n timeout: validator.number().integer().min(1).optional(),\n abortSignal: validator\n .any()\n .custom((value, helpers) => {\n if (value === undefined || value === null) return undefined\n // eslint-disable-next-line adk/use-is-instance-of -- native built-in; AbortSignal cross-realm is handled by the duck-type fallback below\n if (typeof AbortSignal !== 'undefined' && value instanceof AbortSignal) return value\n if (\n isObject(value) &&\n typeof (value as any).aborted === 'boolean' &&\n typeof (value as any).addEventListener === 'function'\n ) {\n return value\n }\n return helpers.error('any.invalid')\n })\n .optional(),\n createdAt: validator.datetime().required(),\n})\n\n/**\n * A cooperative suspension gate that blocks a turn's middleware pipeline until resolved, rejected,\n * aborted, or timed out.\n *\n * @typeParam T - The expected type of the resolution value.\n *\n * @remarks\n * Created exclusively via `ctx.waitFor()` — middleware never constructs a gate directly.\n * The gate emits `turnGateOpen` on the runner's observability bus at creation time and\n * `turnGateClosed` when it settles.\n *\n * Resolution is validated against an optional schema before the internal promise is settled.\n * A validation failure throws {@link @nhtio/adk!E_INVALID_TURN_GATE_RESOLUTION} **synchronously in the\n * caller's context** — the promise is NOT settled and the gate remains open.\n */\nexport class TurnGate<T = unknown> {\n /**\n * Validator schema that accepts a {@link RawTurnGate} object.\n *\n * @remarks\n * Reusable fragment for any schema that needs to validate or nest a gate entry.\n */\n public static schema = rawTurnGateSchema\n\n /**\n * Returns `true` if `value` is a {@link TurnGate} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link TurnGate} instance.\n */\n public static isTurnGate(value: unknown): value is TurnGate {\n return isInstanceOf(value, 'TurnGate', TurnGate)\n }\n\n declare readonly id: string\n declare readonly turnId: string\n declare readonly reason: string\n declare readonly payload: unknown\n declare readonly createdAt: DateTime\n declare readonly isSettled: boolean\n\n #id: string\n #turnId: string\n #reason: string\n #payload: unknown\n #createdAt: DateTime\n #settled: boolean\n #schema: Schema | undefined\n #controller: AbortController\n #resolve!: (value: T) => void\n #reject!: (reason: unknown) => void\n #promise: Promise<T>\n\n /**\n * @param raw - The raw gate input validated against `rawTurnGateSchema`.\n * @throws {@link @nhtio/adk!E_INVALID_INITIAL_TURN_GATE_VALUE} when `raw` does not satisfy the schema.\n */\n constructor(raw: RawTurnGate) {\n let resolved: ResolvedTurnGate\n try {\n resolved = validateOrThrow<ResolvedTurnGate>(rawTurnGateSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_TURN_GATE_VALUE({ cause: isError(err) ? err : undefined })\n }\n\n this.#id = resolved.id\n this.#turnId = resolved.turnId\n this.#reason = resolved.reason\n this.#payload = resolved.payload\n this.#createdAt = resolved.createdAt\n this.#settled = false\n this.#schema = resolved.schema\n this.#controller = new AbortController()\n\n this.#promise = new Promise<T>((resolve, reject) => {\n this.#resolve = resolve\n this.#reject = reject\n })\n\n // Wire the internal abort controller\n const onAbort = () => {\n if (!this.#settled) {\n this.#settled = true\n this.#reject(new E_TURN_GATE_ABORTED())\n }\n }\n\n this.#controller.signal.addEventListener('abort', onAbort, { once: true })\n\n // Wire the external turn abort signal\n if (resolved.abortSignal) {\n if (resolved.abortSignal.aborted) {\n // Already aborted — reject immediately after construction\n queueMicrotask(() => onAbort())\n } else {\n resolved.abortSignal.addEventListener('abort', onAbort, { once: true })\n // Clean up the external listener once the gate settles via another path\n this.#promise.then(\n () => resolved.abortSignal!.removeEventListener('abort', onAbort),\n () => resolved.abortSignal!.removeEventListener('abort', onAbort)\n )\n }\n }\n\n // Wire the timeout\n if (resolved.timeout !== undefined) {\n const timer = setTimeout(() => {\n if (!this.#settled) {\n this.#settled = true\n this.#reject(new E_TURN_GATE_TIMEOUT())\n }\n }, resolved.timeout)\n\n this.#promise.then(\n () => clearTimeout(timer),\n () => clearTimeout(timer)\n )\n }\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n turnId: {\n get: () => this.#turnId,\n enumerable: true,\n configurable: false,\n },\n reason: {\n get: () => this.#reason,\n enumerable: true,\n configurable: false,\n },\n payload: {\n get: () => this.#payload,\n enumerable: true,\n configurable: false,\n },\n createdAt: {\n get: () => this.#createdAt,\n enumerable: true,\n configurable: false,\n },\n isSettled: {\n get: () => this.#settled,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Resolves the gate with `value`, unblocking the awaiting middleware.\n *\n * @remarks\n * If a schema was provided at construction, `value` is validated synchronously before the\n * promise is settled. A validation failure throws {@link @nhtio/adk!E_INVALID_TURN_GATE_RESOLUTION}\n * in the caller's context — the promise is NOT settled and the gate remains open.\n *\n * No-ops if the gate is already settled.\n *\n * @param value - The resolution value. Must satisfy the gate's schema when one was provided.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_GATE_RESOLUTION} when `value` fails schema validation.\n */\n resolve(value: unknown): void {\n if (this.#settled) return\n if (this.#schema !== undefined) {\n try {\n value = validateOrThrow(this.#schema, value, true)\n } catch (err) {\n throw new E_INVALID_TURN_GATE_RESOLUTION({\n cause: isError(err) ? err : undefined,\n })\n }\n }\n this.#settled = true\n this.#resolve(value as T)\n }\n\n /**\n * Rejects the gate with `error`, unblocking the awaiting middleware with a rejection.\n *\n * @remarks\n * No-ops if the gate is already settled.\n *\n * @param error - The rejection reason.\n */\n reject(error: Error): void {\n if (this.#settled) return\n this.#settled = true\n this.#reject(error)\n }\n\n /**\n * Aborts the gate by firing the internal `AbortController`, which rejects the promise with\n * {@link @nhtio/adk!E_TURN_GATE_ABORTED}.\n *\n * @remarks\n * No-ops if the gate is already settled. Distinct from the turn-level abort signal — this\n * allows callers to cancel a specific gate without aborting the whole turn.\n */\n abort(): void {\n if (this.#settled) return\n this.#controller.abort()\n }\n\n /**\n * Returns the internal promise. Called by `ctx.waitFor()` to block the middleware pipeline.\n *\n * @internal\n */\n _promise(): Promise<T> {\n return this.#promise\n }\n}\n","import { Tool } from '../classes/tool'\nimport { validator } from '@nhtio/validation'\nimport type { TurnPipelineMiddlewareFn } from '../types/turn_runner'\nimport type { DispatchPipelineMiddlewareFn, DispatchExecutorFn } from '../types/dispatch_runner'\nimport type {\n MemoryRetrievalFn,\n MessageRetrievalFn,\n ThoughtRetrievalFn,\n ToolCallRetrievalFn,\n ToolsRetrievalFn,\n StandingInstructionsRefreshFn,\n StandingInstructionStoreFn,\n StandingInstructionMutateFn,\n StandingInstructionDeleteFn,\n MemoryStoreFn,\n MemoryMutateFn,\n MemoryDeleteFn,\n RetrievableRetrievalFn,\n RetrievableStoreFn,\n RetrievableMutateFn,\n RetrievableDeleteFn,\n MessageStoreFn,\n MessageMutateFn,\n MessageDeleteFn,\n ThoughtStoreFn,\n ThoughtMutateFn,\n ThoughtDeleteFn,\n ToolCallStoreFn,\n ToolCallMutateFn,\n ToolCallDeleteFn,\n} from './turn_runner_context'\n\n/**\n * Configuration supplied to {@link @nhtio/adk!TurnRunner} at construction time.\n *\n * @remarks\n * Validated against `turnRunnerConfigSchema` at construction — a misconfigured runner throws\n * immediately rather than failing on the first turn.\n *\n * All fetch and mutation callbacks are required: they are injected into each {@link @nhtio/adk!TurnContext}\n * so middleware can call fetch, refresh, and persistence methods directly on the context without\n * coupling to the runner.\n *\n * `tools` is optional at the caller level and defaults to `[]` after schema resolution — a runner\n * with no baseline tools is valid.\n */\nexport interface TurnRunnerConfig {\n /** Performs the LLM API/SDK call for each iteration of the dispatch loop; receives the active {@link @nhtio/adk!DispatchContext} and an {@link @nhtio/adk!DispatchExecutorHelpers} object for managing per-id stream state. */\n executorCallback: DispatchExecutorFn\n /** Called once per turn to supply memories; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchMemoriesCallback: MemoryRetrievalFn\n /** Called once per turn to supply conversation history; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchMessagesCallback: MessageRetrievalFn\n /** Called once per turn to supply thought traces; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchThoughtsCallback: ThoughtRetrievalFn\n /** Called once per turn to supply tool call records; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchToolCallsCallback: ToolCallRetrievalFn\n /** Called to supply available tools; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchToolsCallback: ToolsRetrievalFn\n /** Called to refresh and return standing instructions; receives the active {@link @nhtio/adk!TurnContext}. */\n refreshStandingInstructionsCallback: StandingInstructionsRefreshFn\n /** Persists a new standing instruction. */\n storeStandingInstructionCallback: StandingInstructionStoreFn\n /** Updates an existing standing instruction in the persistence layer. */\n mutateStandingInstructionCallback: StandingInstructionMutateFn\n /** Removes a standing instruction from the persistence layer. */\n deleteStandingInstructionCallback: StandingInstructionDeleteFn\n /** Persists a new memory. */\n storeMemoryCallback: MemoryStoreFn\n /** Updates an existing memory in the persistence layer. */\n mutateMemoryCallback: MemoryMutateFn\n /** Removes a memory from the persistence layer by ID. */\n deleteMemoryCallback: MemoryDeleteFn\n /** Called once per turn to supply retrievable (RAG) records; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchRetrievablesCallback: RetrievableRetrievalFn\n /** Persists a new retrievable record. */\n storeRetrievableCallback: RetrievableStoreFn\n /** Updates an existing retrievable record in the persistence layer. */\n mutateRetrievableCallback: RetrievableMutateFn\n /** Removes a retrievable record from the persistence layer by ID. */\n deleteRetrievableCallback: RetrievableDeleteFn\n /** Persists a new message. */\n storeMessageCallback: MessageStoreFn\n /** Updates an existing message in the persistence layer. */\n mutateMessageCallback: MessageMutateFn\n /** Removes a message from the persistence layer by ID. */\n deleteMessageCallback: MessageDeleteFn\n /** Persists a new thought. */\n storeThoughtCallback: ThoughtStoreFn\n /** Updates an existing thought in the persistence layer. */\n mutateThoughtCallback: ThoughtMutateFn\n /** Removes a thought from the persistence layer by ID. */\n deleteThoughtCallback: ThoughtDeleteFn\n /** Persists a new tool call. */\n storeToolCallCallback: ToolCallStoreFn\n /** Updates an existing tool call in the persistence layer. */\n mutateToolCallCallback: ToolCallMutateFn\n /** Removes a tool call from the persistence layer by ID. */\n deleteToolCallCallback: ToolCallDeleteFn\n /** Baseline tools available on every turn. Middleware may trim or extend this per-turn via `ctx.tools`. Defaults to `[]`. */\n tools?: Tool[]\n /** Turn-level input middleware, executed in order against the {@link @nhtio/adk!TurnContext} before the LLM dispatch. Defaults to `[]`. */\n turnInputPipeline?: TurnPipelineMiddlewareFn[]\n /** Turn-level output middleware, executed in order against the {@link @nhtio/adk!TurnContext} after the LLM dispatch resolves successfully. Defaults to `[]`. */\n turnOutputPipeline?: TurnPipelineMiddlewareFn[]\n /** LLM-iteration input middleware, executed in order against the {@link @nhtio/adk!DispatchContext} before the executor on each iteration. Defaults to `[]`. */\n dispatchInputPipeline?: DispatchPipelineMiddlewareFn[]\n /** LLM-iteration output middleware, executed in order against the {@link @nhtio/adk!DispatchContext} after the executor on each iteration. Defaults to `[]`. */\n dispatchOutputPipeline?: DispatchPipelineMiddlewareFn[]\n}\n\n/**\n * Fully-resolved {@link TurnRunnerConfig} after schema validation.\n *\n * @remarks\n * All optional fields are guaranteed present (e.g. `tools` defaults to `[]`). The runner stores\n * this type internally so field access never needs to guard for undefined.\n */\nexport type ResolvedTurnRunnerConfig = Required<TurnRunnerConfig>\n\n/**\n * Validator schema used to validate a {@link TurnRunnerConfig} at {@link @nhtio/adk!TurnRunner} construction time.\n *\n * @remarks\n * Validates that all callbacks are functions of the correct arity, and that `tools` — when\n * provided — is an array of valid {@link @nhtio/adk!Tool} instances. Defaults `tools` to `[]`.\n *\n * Throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} (via the {@link @nhtio/adk!TurnRunner} constructor) when\n * validation fails.\n */\nexport const turnRunnerConfigSchema = validator.object<TurnRunnerConfig>({\n executorCallback: validator.function().required(),\n fetchMemoriesCallback: validator.function().arity(1).required(),\n fetchMessagesCallback: validator.function().arity(1).required(),\n fetchThoughtsCallback: validator.function().arity(1).required(),\n fetchToolCallsCallback: validator.function().arity(1).required(),\n fetchToolsCallback: validator.function().arity(1).required(),\n refreshStandingInstructionsCallback: validator.function().arity(1).required(),\n storeStandingInstructionCallback: validator.function().arity(2).required(),\n mutateStandingInstructionCallback: validator.function().arity(2).required(),\n deleteStandingInstructionCallback: validator.function().arity(2).required(),\n storeMemoryCallback: validator.function().arity(2).required(),\n mutateMemoryCallback: validator.function().arity(2).required(),\n deleteMemoryCallback: validator.function().arity(2).required(),\n fetchRetrievablesCallback: validator.function().arity(1).required(),\n storeRetrievableCallback: validator.function().arity(2).required(),\n mutateRetrievableCallback: validator.function().arity(2).required(),\n deleteRetrievableCallback: validator.function().arity(2).required(),\n storeMessageCallback: validator.function().arity(2).required(),\n mutateMessageCallback: validator.function().arity(2).required(),\n deleteMessageCallback: validator.function().arity(2).required(),\n storeThoughtCallback: validator.function().arity(2).required(),\n mutateThoughtCallback: validator.function().arity(2).required(),\n deleteThoughtCallback: validator.function().arity(2).required(),\n storeToolCallCallback: validator.function().arity(2).required(),\n mutateToolCallCallback: validator.function().arity(2).required(),\n deleteToolCallCallback: validator.function().arity(2).required(),\n tools: validator\n .array()\n .items(\n validator.any().custom((value: unknown, helpers: { error: (code: string) => unknown }) => {\n if (Tool.isTool(value)) return value\n return helpers.error('any.invalid')\n })\n )\n .default([]),\n turnInputPipeline: validator.array().items(validator.function()).default([]),\n turnOutputPipeline: validator.array().items(validator.function()).default([]),\n dispatchInputPipeline: validator.array().items(validator.function()).default([]),\n dispatchOutputPipeline: validator.array().items(validator.function()).default([]),\n})\n","import { DateTime } from 'luxon'\nimport { Middleware } from '@nhtio/middleware'\nimport { TurnGate } from './classes/turn_gate'\nimport { DispatchRunner } from './dispatch_runner'\nimport { ToolRegistry } from './classes/tool_registry'\nimport { isInstanceOf, isError } from './utils/guards'\nimport { TypedEventEmitter } from '@nhtio/tiny-typed-emitter'\nimport { passesSchema, validateOrThrow } from './utils/validation'\nimport { turnRunnerConfigSchema } from './contracts/turn_runner_config'\nimport { TurnContext, RawTurnContext } from './contracts/turn_runner_context'\nimport {\n E_INVALID_TURN_RUNNER_CONFIG,\n E_INPUT_PIPELINE_ERROR,\n E_OUTPUT_PIPELINE_ERROR,\n E_PIPELINE_SHORT_CIRCUITED,\n} from './exceptions/runtime'\nimport type { Runner } from '@nhtio/middleware'\nimport type { RawTurnGate } from './classes/turn_gate'\nimport type { ResolvedTurnRunnerConfig, TurnRunnerConfig } from './contracts/turn_runner_config'\nimport type {\n OpenGateFn,\n TurnEvents,\n TurnEvent,\n TurnEventListener,\n TurnPipelineMiddlewareFn,\n TurnObservabilityEvents,\n TurnObservabilityEvent,\n TurnObservabilityEventListener,\n} from './types/turn_runner'\n\nexport type {\n TurnPipelineMiddlewareFn,\n TurnStreamableContent,\n TurnToolCallContent,\n TurnStartEvent,\n TurnEndEvent,\n TurnGateClosedEvent,\n ToolExecutionStartEvent,\n ToolExecutionEndEvent,\n EmitMessageFn,\n EmitThoughtFn,\n EmitToolCallFn,\n EmitToolExecutionStartFn,\n EmitToolExecutionEndFn,\n OpenGateFn,\n TurnEvents,\n TurnEvent,\n TurnEventListener,\n TurnObservabilityEvents,\n TurnObservabilityEvent,\n TurnObservabilityEventListener,\n} from './types/turn_runner'\n\n/**\n * Executes a single agent turn through paired input and output middleware pipelines.\n *\n * @remarks\n * Construction validates `config` eagerly and throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} if it\n * does not satisfy the schema — fail-fast so misconfiguration surfaces before any turn runs.\n *\n * Each call to {@link TurnRunner.run} threads a {@link @nhtio/adk!TurnContext} through the input pipeline,\n * invokes the model, then threads the result through the output pipeline. Middleware on each side\n * can read and mutate the context for pre- and post-processing (e.g. message normalisation, tool\n * call dispatch, response filtering).\n *\n * **Two event buses:**\n * - Functional bus (`on` / `off` / `once`): `message`, `thought`, `toolCall` — pipeline-affecting\n * events that middleware raises throughout turn execution.\n * - Observability bus (`observe` / `unobserve` / `observeOnce`): `turnStart`, `turnEnd`,\n * `turnGateOpen`, `turnGateClosed`, `error` — instrumentation-only events that monitor execution\n * without participating in it.\n *\n * Streaming content is surfaced via `message` and `thought` events; tool call lifecycle via\n * `toolCall`; non-fatal pipeline errors via the observability `error` event; gate lifecycle via\n * `turnGateOpen` and `turnGateClosed` — all throughout execution.\n *\n * @example\n * ```ts\n * const runner = new TurnRunner({\n * fetchMemoriesCallback: async (ctx) => memoryStore.query(ctx),\n * fetchMessagesCallback: async (ctx) => messageStore.history(ctx),\n * fetchThoughtsCallback: async (ctx) => thoughtStore.history(ctx),\n * fetchToolCallsCallback: async (ctx) => toolCallStore.history(ctx),\n * })\n * // Functional bus — pipeline events\n * runner.on('message', (chunk) => process.stdout.write(chunk.aDelta))\n * // Observability bus — instrumentation\n * runner.observe('error', (err) => console.error(err.toString()))\n * runner.observe('turnStart', ({ turnId }) => console.log('turn started', turnId))\n * runner.observe('turnGateOpen', (gate) => {\n * if (gate.reason === 'tool_approval') {\n * gate.resolve(true) // approve immediately for this example\n * }\n * })\n * await runner.run({\n * turnAbortController: new AbortController(),\n * systemPrompt: 'You are a helpful assistant.',\n * standingInstructions: [],\n * })\n * ```\n */\nexport class TurnRunner {\n /**\n * Returns `true` if `value` is a {@link TurnRunner} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link TurnRunner} instance.\n */\n public static isTurnRunner(value: unknown): value is TurnRunner {\n return isInstanceOf(value, 'TurnRunner', TurnRunner)\n }\n\n #config: ResolvedTurnRunnerConfig\n #inputRunner: Runner<TurnPipelineMiddlewareFn>\n #outputRunner: Runner<TurnPipelineMiddlewareFn>\n #functionalEmitter: TypedEventEmitter<TurnEvents>\n #observabilityEmitter: TypedEventEmitter<TurnObservabilityEvents>\n\n /**\n * @param config - Construction-time configuration validated against {@link turnRunnerConfigSchema}.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} when `config` does not satisfy the schema.\n */\n constructor(config: TurnRunnerConfig) {\n const isValid = passesSchema(turnRunnerConfigSchema, config)\n if (!isValid) {\n throw new E_INVALID_TURN_RUNNER_CONFIG()\n }\n // Store the resolved config so optional fields (e.g. tools) are always present.\n this.#config = validateOrThrow<ResolvedTurnRunnerConfig>(turnRunnerConfigSchema, config, true)\n const turnInputPipeline = new Middleware<TurnPipelineMiddlewareFn>()\n const turnOutputPipeline = new Middleware<TurnPipelineMiddlewareFn>()\n const wrap =\n (fn: TurnPipelineMiddlewareFn): TurnPipelineMiddlewareFn =>\n (ctx, next) => {\n // Skip downstream user middlewares once an abort has been signalled. The\n // wrapper still calls next() so the pipeline reaches its terminal resolver\n // (keeping the short-circuit detector quiet); the original middleware body\n // does not run, so it has nothing to clean up.\n if (ctx.aborted) return next()\n return fn(ctx, next)\n }\n for (const fn of this.#config.turnInputPipeline) turnInputPipeline.add(wrap(fn))\n for (const fn of this.#config.turnOutputPipeline) turnOutputPipeline.add(wrap(fn))\n this.#inputRunner = turnInputPipeline.runner()\n this.#outputRunner = turnOutputPipeline.runner()\n this.#functionalEmitter = new TypedEventEmitter<TurnEvents>()\n this.#observabilityEmitter = new TypedEventEmitter<TurnObservabilityEvents>()\n }\n\n // ── Functional bus ───────────────────────────────────────────────────────\n\n /**\n * Removes a previously registered functional listener for `event`.\n *\n * @param event - The event to stop listening to.\n * @param listener - The listener function to remove.\n * @returns `this` for chaining.\n */\n off<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.off(event, listener)\n return this\n }\n\n /**\n * Registers a persistent functional listener for `event`.\n *\n * @param event - The event to listen to.\n * @param listener - The function to call on each emission.\n * @returns `this` for chaining.\n */\n on<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.on(event, listener)\n return this\n }\n\n /**\n * Registers a one-time functional listener for `event` that is automatically removed after the\n * first emission.\n *\n * @param event - The event to listen to.\n * @param listener - The function to call on the next emission.\n * @returns `this` for chaining.\n */\n once<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.once(event, listener)\n return this\n }\n\n // ── Observability bus ────────────────────────────────────────────────────\n\n /**\n * Removes a previously registered observability listener for `event`.\n *\n * @param event - The event to stop observing.\n * @param listener - The listener function to remove.\n * @returns `this` for chaining.\n */\n unobserve<K>(\n event: TurnObservabilityEvent<K>,\n listener: TurnObservabilityEventListener<K>\n ): this {\n this.#observabilityEmitter.off(event, listener)\n return this\n }\n\n /**\n * Registers a persistent observability listener for `event`.\n *\n * @remarks\n * Use the observability bus (`observe` / `unobserve` / `observeOnce`) for instrumentation:\n * turn lifecycle, gate lifecycle, and non-fatal errors. Use the functional bus (`on` / `off` /\n * `once`) for pipeline-affecting events: `message`, `thought`, `toolCall`.\n *\n * @param event - The event to observe.\n * @param listener - The function to call on each emission.\n * @returns `this` for chaining.\n */\n observe<K>(event: TurnObservabilityEvent<K>, listener: TurnObservabilityEventListener<K>): this {\n this.#observabilityEmitter.on(event, listener)\n return this\n }\n\n /**\n * Registers a one-time observability listener for `event` that is automatically removed after\n * the first emission.\n *\n * @param event - The event to observe once.\n * @param listener - The function to call on the next emission.\n * @returns `this` for chaining.\n */\n observeOnce<K>(\n event: TurnObservabilityEvent<K>,\n listener: TurnObservabilityEventListener<K>\n ): this {\n this.#observabilityEmitter.once(event, listener)\n return this\n }\n\n // ── Turn execution ───────────────────────────────────────────────────────\n\n /**\n * Executes a single agent turn against the provided raw context.\n *\n * @remarks\n * Returns `Promise<void>` intentionally — all meaningful output surfaces via events, not return\n * values. Register listeners before calling `run`: observability events (`turnStart`, `turnEnd`)\n * bracket execution; functional events (`message`, `thought`, `toolCall`) fire throughout;\n * observability `error` carries non-fatal pipeline failures; `turnGateOpen` and `turnGateClosed`\n * fire when middleware suspends via `ctx.waitFor()`. Awaiting this method only tells you the\n * pipeline has finished, not what it produced.\n *\n * Constructs a validated {@link @nhtio/adk!TurnContext} from `context` (throwing\n * {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} on failure), then runs the input middleware pipeline.\n * Abort signals are silently swallowed.\n *\n * @param context - Raw input validated and wrapped into a {@link @nhtio/adk!TurnContext} before execution.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} when `context` does not satisfy the schema.\n */\n async run(context: RawTurnContext): Promise<void> {\n const abortController = context.turnAbortController ?? new AbortController()\n\n // Forward declaration so openGate can reference turnContext.id before it is assigned.\n let turnContextId: string\n\n const openGate: OpenGateFn = <T>(raw: Omit<RawTurnGate, 'turnId' | 'abortSignal'>) => {\n const gate = new TurnGate<T>({\n ...raw,\n turnId: turnContextId,\n abortSignal: abortController.signal,\n })\n this.#observabilityEmitter.emit('turnGateOpen', gate)\n const promise = gate._promise()\n promise.then(\n () => {\n this.#observabilityEmitter.emit('turnGateClosed', {\n gateId: gate.id,\n turnId: gate.turnId,\n result: 'resolved',\n settledAt: DateTime.now(),\n })\n },\n (err: unknown) => {\n let result: 'rejected' | 'aborted' | 'timeout' = 'rejected'\n if (isInstanceOf(err, 'E_TURN_GATE_ABORTED')) result = 'aborted'\n else if (isInstanceOf(err, 'E_TURN_GATE_TIMEOUT')) result = 'timeout'\n this.#observabilityEmitter.emit('turnGateClosed', {\n gateId: gate.id,\n turnId: gate.turnId,\n result,\n settledAt: DateTime.now(),\n })\n }\n )\n return promise\n }\n\n const tools = new ToolRegistry(this.#config.tools)\n\n const turnContext = new TurnContext(\n { ...context, turnAbortController: abortController },\n {\n fetchMemories: this.#config.fetchMemoriesCallback,\n fetchMessages: this.#config.fetchMessagesCallback,\n fetchThoughts: this.#config.fetchThoughtsCallback,\n fetchToolCalls: this.#config.fetchToolCallsCallback,\n fetchTools: this.#config.fetchToolsCallback,\n refreshStandingInstructions: this.#config.refreshStandingInstructionsCallback,\n storeStandingInstruction: this.#config.storeStandingInstructionCallback,\n mutateStandingInstruction: this.#config.mutateStandingInstructionCallback,\n deleteStandingInstruction: this.#config.deleteStandingInstructionCallback,\n storeMemory: this.#config.storeMemoryCallback,\n mutateMemory: this.#config.mutateMemoryCallback,\n deleteMemory: this.#config.deleteMemoryCallback,\n fetchRetrievables: this.#config.fetchRetrievablesCallback,\n storeRetrievable: this.#config.storeRetrievableCallback,\n mutateRetrievable: this.#config.mutateRetrievableCallback,\n deleteRetrievable: this.#config.deleteRetrievableCallback,\n storeMessage: this.#config.storeMessageCallback,\n mutateMessage: this.#config.mutateMessageCallback,\n deleteMessage: this.#config.deleteMessageCallback,\n storeThought: this.#config.storeThoughtCallback,\n mutateThought: this.#config.mutateThoughtCallback,\n deleteThought: this.#config.deleteThoughtCallback,\n storeToolCall: this.#config.storeToolCallCallback,\n mutateToolCall: this.#config.mutateToolCallCallback,\n deleteToolCall: this.#config.deleteToolCallCallback,\n emitMessage: (content) => this.#functionalEmitter.emit('message', content),\n emitThought: (content) => this.#functionalEmitter.emit('thought', content),\n emitToolCall: (content) => this.#functionalEmitter.emit('toolCall', content),\n emitToolExecutionStart: (event) =>\n this.#observabilityEmitter.emit('toolExecutionStart', event),\n emitToolExecutionEnd: (event) => this.#observabilityEmitter.emit('toolExecutionEnd', event),\n openGate,\n tools,\n }\n )\n\n turnContextId = turnContext.id\n\n const startedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnStart', { turnId: turnContext.id, startedAt })\n\n const emitTurnEnd = () => {\n const endedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnEnd', {\n turnId: turnContext.id,\n startedAt,\n endedAt,\n durationMs: endedAt.diff(startedAt).milliseconds,\n })\n }\n\n // 1. Input pipeline\n let inputFailed = false\n let inputReached = false\n await this.#inputRunner\n .errorHandler(async (error) => {\n if (!isError(error) || !isInstanceOf(error, 'AbortError')) {\n inputFailed = true\n const err = new E_INPUT_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n this.#observabilityEmitter.emit('error', err)\n }\n })\n .finalHandler(async () => {\n inputReached = true\n })\n .run((fn, next) => Promise.resolve(fn(turnContext, next)))\n\n if (!inputReached && !inputFailed && !turnContext.aborted) {\n inputFailed = true\n const err = new E_PIPELINE_SHORT_CIRCUITED(['turn-input'])\n this.#observabilityEmitter.emit('error', err)\n }\n\n if (inputFailed || turnContext.aborted) {\n emitTurnEnd()\n return\n }\n\n // 2. LLM execution dispatch\n let dispatchFailed = false\n try {\n await DispatchRunner.dispatch({\n source: turnContext,\n executor: this.#config.executorCallback,\n turnInputPipeline: this.#config.dispatchInputPipeline,\n turnOutputPipeline: this.#config.dispatchOutputPipeline,\n observers: {\n dispatchStart: [\n (e) => {\n this.#observabilityEmitter.emit('dispatchStart', e)\n },\n ],\n dispatchEnd: [\n (e) => {\n this.#observabilityEmitter.emit('dispatchEnd', e)\n },\n ],\n iterationStart: [\n (e) => {\n this.#observabilityEmitter.emit('iterationStart', e)\n },\n ],\n iterationEnd: [\n (e) => {\n this.#observabilityEmitter.emit('iterationEnd', e)\n },\n ],\n log: [\n (e) => {\n this.#observabilityEmitter.emit('log', e)\n },\n ],\n },\n })\n } catch (err) {\n dispatchFailed = true\n const wrapped = isInstanceOf(err, 'BaseException') ? (err as InstanceType<typeof Error>) : err\n this.#observabilityEmitter.emit('error', wrapped as any)\n }\n\n if (dispatchFailed || turnContext.aborted) {\n emitTurnEnd()\n return\n }\n\n // 3. Output pipeline\n let outputFailed = false\n let outputReached = false\n await this.#outputRunner\n .errorHandler(async (error) => {\n if (!isError(error) || !isInstanceOf(error, 'AbortError')) {\n outputFailed = true\n const err = new E_OUTPUT_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n this.#observabilityEmitter.emit('error', err)\n }\n })\n .finalHandler(async () => {\n outputReached = true\n })\n .run((fn, next) => Promise.resolve(fn(turnContext, next)))\n\n if (!outputReached && !outputFailed && !turnContext.aborted) {\n const err = new E_PIPELINE_SHORT_CIRCUITED(['turn-output'])\n this.#observabilityEmitter.emit('error', err)\n }\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AS,QAAQ,QAAQ,GAAG,aAAa,IAAI,CAAC,CAAC;EAE3D,IAAI,CAAC,iBAAiB,CAAC,gBAAgB,CAAC,YAAY,SAAS;GAC3D,MAAM,MAAM,IAAI,gBAAA,2BAA2B,CAAC,aAAa,CAAC;GAC1D,KAAKA,sBAAsB,KAAK,SAAS,GAAG;EAC9C;EAEA,YAAY;CACd;AACF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { a as validateOrThrow, i as passesSchema } from "./exceptions-NrzIHw_R.mjs";
|
|
2
2
|
import { c as isObject, o as isError, s as isInstanceOf, t as ToolRegistry } from "./tool_registry-DqLOyGyG.mjs";
|
|
3
3
|
import { O as E_TURN_GATE_ABORTED, T as E_PIPELINE_SHORT_CIRCUITED, _ as E_INVALID_TURN_GATE_RESOLUTION, f as E_INVALID_INITIAL_TURN_GATE_VALUE, k as E_TURN_GATE_TIMEOUT, n as E_INPUT_PIPELINE_ERROR, v as E_INVALID_TURN_RUNNER_CONFIG, w as E_OUTPUT_PIPELINE_ERROR } from "./runtime-CrEPIFgr.mjs";
|
|
4
|
-
import { t as Tool } from "./tool-
|
|
5
|
-
import { r as TurnContext, t as DispatchRunner } from "./dispatch_runner-
|
|
4
|
+
import { t as Tool } from "./tool-D2WB1EA1.mjs";
|
|
5
|
+
import { r as TurnContext, t as DispatchRunner } from "./dispatch_runner-9j6bXHL3.mjs";
|
|
6
6
|
import { validator } from "@nhtio/validation";
|
|
7
7
|
import { DateTime } from "luxon";
|
|
8
8
|
import { Middleware } from "@nhtio/middleware";
|
|
@@ -253,8 +253,6 @@ var turnRunnerConfigSchema = validator.object({
|
|
|
253
253
|
storeToolCallCallback: validator.function().arity(2).required(),
|
|
254
254
|
mutateToolCallCallback: validator.function().arity(2).required(),
|
|
255
255
|
deleteToolCallCallback: validator.function().arity(2).required(),
|
|
256
|
-
storeMediaBytesCallback: validator.function().arity(3).required(),
|
|
257
|
-
storeRetrievableBytesCallback: validator.function().arity(3).required(),
|
|
258
256
|
tools: validator.array().items(validator.any().custom((value, helpers) => {
|
|
259
257
|
if (Tool.isTool(value)) return value;
|
|
260
258
|
return helpers.error("any.invalid");
|
|
@@ -504,8 +502,6 @@ var TurnRunner = class TurnRunner {
|
|
|
504
502
|
storeToolCall: this.#config.storeToolCallCallback,
|
|
505
503
|
mutateToolCall: this.#config.mutateToolCallCallback,
|
|
506
504
|
deleteToolCall: this.#config.deleteToolCallCallback,
|
|
507
|
-
storeMediaBytes: this.#config.storeMediaBytesCallback,
|
|
508
|
-
storeRetrievableBytes: this.#config.storeRetrievableBytesCallback,
|
|
509
505
|
emitMessage: (content) => this.#functionalEmitter.emit("message", content),
|
|
510
506
|
emitThought: (content) => this.#functionalEmitter.emit("thought", content),
|
|
511
507
|
emitToolCall: (content) => this.#functionalEmitter.emit("toolCall", content),
|
|
@@ -604,4 +600,4 @@ var TurnRunner = class TurnRunner {
|
|
|
604
600
|
//#endregion
|
|
605
601
|
export { TurnGate as n, TurnRunner as t };
|
|
606
602
|
|
|
607
|
-
//# sourceMappingURL=turn_runner-
|
|
603
|
+
//# sourceMappingURL=turn_runner-y7eyEcJH.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"turn_runner-y7eyEcJH.mjs","names":["#id","#turnId","#reason","#payload","#createdAt","#settled","#schema","#controller","#promise","#resolve","#reject","#config","#inputRunner","#outputRunner","#functionalEmitter","#observabilityEmitter"],"sources":["../src/lib/classes/turn_gate.ts","../src/lib/contracts/turn_runner_config.ts","../src/lib/turn_runner.ts"],"sourcesContent":["import { DateTime } from 'luxon'\nimport { validator } from '@nhtio/validation'\nimport { validateOrThrow } from '../utils/validation'\nimport { isInstanceOf, isError, isObject } from '../utils/guards'\nimport {\n E_TURN_GATE_ABORTED,\n E_TURN_GATE_TIMEOUT,\n E_INVALID_TURN_GATE_RESOLUTION,\n E_INVALID_INITIAL_TURN_GATE_VALUE,\n} from '../exceptions/runtime'\nimport type { Schema } from '@nhtio/validation'\n\n/**\n * Plain input object supplied to {@link TurnGate} at construction time.\n *\n * @remarks\n * `turnId` and `abortSignal` are injected by the runner — callers constructing a gate via\n * `ctx.waitFor()` never supply them directly.\n *\n * `abortSignal` is `AbortSignal` (not `AbortController`) because the gate reacts to turn-level\n * cancellation but cannot trigger it. The gate owns its own internal `AbortController` for\n * `gate.abort()`.\n */\nexport interface RawTurnGate {\n /** Stable unique identifier for this gate. */\n id: string\n /** The ID of the turn that opened this gate. */\n turnId: string\n /** Human-readable label describing why this gate was opened (e.g. `'tool_approval'`). */\n reason: string\n /** Arbitrary data supplied to the gate opener; passed through to `turnGateOpen` listeners. */\n payload: unknown\n /** Optional validator schema for the resolution value. When present, `resolve()` validates before settling. */\n schema?: Schema\n /** Optional timeout in milliseconds. When elapsed the gate self-rejects with {@link @nhtio/adk!E_TURN_GATE_TIMEOUT}. */\n timeout?: number\n /** The turn's abort signal. When fired the gate self-rejects with {@link @nhtio/adk!E_TURN_GATE_ABORTED}. */\n abortSignal?: AbortSignal\n /** When this gate was created. */\n createdAt: string | number | Date | DateTime\n}\n\n/**\n * Fully-resolved {@link RawTurnGate} after schema validation.\n *\n * @internal\n */\ninterface ResolvedTurnGate {\n id: string\n turnId: string\n reason: string\n payload: unknown\n schema?: Schema\n timeout?: number\n abortSignal?: AbortSignal\n createdAt: DateTime\n}\n\n/**\n * Validator schema used to validate a {@link RawTurnGate} before constructing a {@link TurnGate}.\n *\n * @remarks\n * - `schema` and `abortSignal` are validated as opaque passthrough values.\n * - `timeout` must be a positive integer when provided.\n */\nconst rawTurnGateSchema = validator.object<RawTurnGate>({\n id: validator.string().required(),\n turnId: validator.string().required(),\n reason: validator.string().required(),\n payload: validator.any().required(),\n schema: validator\n .any()\n .custom((value, helpers) => {\n if (value === undefined || value === null) return undefined\n if (typeof (value as any).validate === 'function') return value\n return helpers.error('any.invalid')\n })\n .optional(),\n timeout: validator.number().integer().min(1).optional(),\n abortSignal: validator\n .any()\n .custom((value, helpers) => {\n if (value === undefined || value === null) return undefined\n // eslint-disable-next-line adk/use-is-instance-of -- native built-in; AbortSignal cross-realm is handled by the duck-type fallback below\n if (typeof AbortSignal !== 'undefined' && value instanceof AbortSignal) return value\n if (\n isObject(value) &&\n typeof (value as any).aborted === 'boolean' &&\n typeof (value as any).addEventListener === 'function'\n ) {\n return value\n }\n return helpers.error('any.invalid')\n })\n .optional(),\n createdAt: validator.datetime().required(),\n})\n\n/**\n * A cooperative suspension gate that blocks a turn's middleware pipeline until resolved, rejected,\n * aborted, or timed out.\n *\n * @typeParam T - The expected type of the resolution value.\n *\n * @remarks\n * Created exclusively via `ctx.waitFor()` — middleware never constructs a gate directly.\n * The gate emits `turnGateOpen` on the runner's observability bus at creation time and\n * `turnGateClosed` when it settles.\n *\n * Resolution is validated against an optional schema before the internal promise is settled.\n * A validation failure throws {@link @nhtio/adk!E_INVALID_TURN_GATE_RESOLUTION} **synchronously in the\n * caller's context** — the promise is NOT settled and the gate remains open.\n */\nexport class TurnGate<T = unknown> {\n /**\n * Validator schema that accepts a {@link RawTurnGate} object.\n *\n * @remarks\n * Reusable fragment for any schema that needs to validate or nest a gate entry.\n */\n public static schema = rawTurnGateSchema\n\n /**\n * Returns `true` if `value` is a {@link TurnGate} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link TurnGate} instance.\n */\n public static isTurnGate(value: unknown): value is TurnGate {\n return isInstanceOf(value, 'TurnGate', TurnGate)\n }\n\n declare readonly id: string\n declare readonly turnId: string\n declare readonly reason: string\n declare readonly payload: unknown\n declare readonly createdAt: DateTime\n declare readonly isSettled: boolean\n\n #id: string\n #turnId: string\n #reason: string\n #payload: unknown\n #createdAt: DateTime\n #settled: boolean\n #schema: Schema | undefined\n #controller: AbortController\n #resolve!: (value: T) => void\n #reject!: (reason: unknown) => void\n #promise: Promise<T>\n\n /**\n * @param raw - The raw gate input validated against `rawTurnGateSchema`.\n * @throws {@link @nhtio/adk!E_INVALID_INITIAL_TURN_GATE_VALUE} when `raw` does not satisfy the schema.\n */\n constructor(raw: RawTurnGate) {\n let resolved: ResolvedTurnGate\n try {\n resolved = validateOrThrow<ResolvedTurnGate>(rawTurnGateSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_TURN_GATE_VALUE({ cause: isError(err) ? err : undefined })\n }\n\n this.#id = resolved.id\n this.#turnId = resolved.turnId\n this.#reason = resolved.reason\n this.#payload = resolved.payload\n this.#createdAt = resolved.createdAt\n this.#settled = false\n this.#schema = resolved.schema\n this.#controller = new AbortController()\n\n this.#promise = new Promise<T>((resolve, reject) => {\n this.#resolve = resolve\n this.#reject = reject\n })\n\n // Wire the internal abort controller\n const onAbort = () => {\n if (!this.#settled) {\n this.#settled = true\n this.#reject(new E_TURN_GATE_ABORTED())\n }\n }\n\n this.#controller.signal.addEventListener('abort', onAbort, { once: true })\n\n // Wire the external turn abort signal\n if (resolved.abortSignal) {\n if (resolved.abortSignal.aborted) {\n // Already aborted — reject immediately after construction\n queueMicrotask(() => onAbort())\n } else {\n resolved.abortSignal.addEventListener('abort', onAbort, { once: true })\n // Clean up the external listener once the gate settles via another path\n this.#promise.then(\n () => resolved.abortSignal!.removeEventListener('abort', onAbort),\n () => resolved.abortSignal!.removeEventListener('abort', onAbort)\n )\n }\n }\n\n // Wire the timeout\n if (resolved.timeout !== undefined) {\n const timer = setTimeout(() => {\n if (!this.#settled) {\n this.#settled = true\n this.#reject(new E_TURN_GATE_TIMEOUT())\n }\n }, resolved.timeout)\n\n this.#promise.then(\n () => clearTimeout(timer),\n () => clearTimeout(timer)\n )\n }\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n turnId: {\n get: () => this.#turnId,\n enumerable: true,\n configurable: false,\n },\n reason: {\n get: () => this.#reason,\n enumerable: true,\n configurable: false,\n },\n payload: {\n get: () => this.#payload,\n enumerable: true,\n configurable: false,\n },\n createdAt: {\n get: () => this.#createdAt,\n enumerable: true,\n configurable: false,\n },\n isSettled: {\n get: () => this.#settled,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Resolves the gate with `value`, unblocking the awaiting middleware.\n *\n * @remarks\n * If a schema was provided at construction, `value` is validated synchronously before the\n * promise is settled. A validation failure throws {@link @nhtio/adk!E_INVALID_TURN_GATE_RESOLUTION}\n * in the caller's context — the promise is NOT settled and the gate remains open.\n *\n * No-ops if the gate is already settled.\n *\n * @param value - The resolution value. Must satisfy the gate's schema when one was provided.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_GATE_RESOLUTION} when `value` fails schema validation.\n */\n resolve(value: unknown): void {\n if (this.#settled) return\n if (this.#schema !== undefined) {\n try {\n value = validateOrThrow(this.#schema, value, true)\n } catch (err) {\n throw new E_INVALID_TURN_GATE_RESOLUTION({\n cause: isError(err) ? err : undefined,\n })\n }\n }\n this.#settled = true\n this.#resolve(value as T)\n }\n\n /**\n * Rejects the gate with `error`, unblocking the awaiting middleware with a rejection.\n *\n * @remarks\n * No-ops if the gate is already settled.\n *\n * @param error - The rejection reason.\n */\n reject(error: Error): void {\n if (this.#settled) return\n this.#settled = true\n this.#reject(error)\n }\n\n /**\n * Aborts the gate by firing the internal `AbortController`, which rejects the promise with\n * {@link @nhtio/adk!E_TURN_GATE_ABORTED}.\n *\n * @remarks\n * No-ops if the gate is already settled. Distinct from the turn-level abort signal — this\n * allows callers to cancel a specific gate without aborting the whole turn.\n */\n abort(): void {\n if (this.#settled) return\n this.#controller.abort()\n }\n\n /**\n * Returns the internal promise. Called by `ctx.waitFor()` to block the middleware pipeline.\n *\n * @internal\n */\n _promise(): Promise<T> {\n return this.#promise\n }\n}\n","import { Tool } from '../classes/tool'\nimport { validator } from '@nhtio/validation'\nimport type { TurnPipelineMiddlewareFn } from '../types/turn_runner'\nimport type { DispatchPipelineMiddlewareFn, DispatchExecutorFn } from '../types/dispatch_runner'\nimport type {\n MemoryRetrievalFn,\n MessageRetrievalFn,\n ThoughtRetrievalFn,\n ToolCallRetrievalFn,\n ToolsRetrievalFn,\n StandingInstructionsRefreshFn,\n StandingInstructionStoreFn,\n StandingInstructionMutateFn,\n StandingInstructionDeleteFn,\n MemoryStoreFn,\n MemoryMutateFn,\n MemoryDeleteFn,\n RetrievableRetrievalFn,\n RetrievableStoreFn,\n RetrievableMutateFn,\n RetrievableDeleteFn,\n MessageStoreFn,\n MessageMutateFn,\n MessageDeleteFn,\n ThoughtStoreFn,\n ThoughtMutateFn,\n ThoughtDeleteFn,\n ToolCallStoreFn,\n ToolCallMutateFn,\n ToolCallDeleteFn,\n} from './turn_runner_context'\n\n/**\n * Configuration supplied to {@link @nhtio/adk!TurnRunner} at construction time.\n *\n * @remarks\n * Validated against `turnRunnerConfigSchema` at construction — a misconfigured runner throws\n * immediately rather than failing on the first turn.\n *\n * All fetch and mutation callbacks are required: they are injected into each {@link @nhtio/adk!TurnContext}\n * so middleware can call fetch, refresh, and persistence methods directly on the context without\n * coupling to the runner.\n *\n * `tools` is optional at the caller level and defaults to `[]` after schema resolution — a runner\n * with no baseline tools is valid.\n */\nexport interface TurnRunnerConfig {\n /** Performs the LLM API/SDK call for each iteration of the dispatch loop; receives the active {@link @nhtio/adk!DispatchContext} and an {@link @nhtio/adk!DispatchExecutorHelpers} object for managing per-id stream state. */\n executorCallback: DispatchExecutorFn\n /** Called once per turn to supply memories; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchMemoriesCallback: MemoryRetrievalFn\n /** Called once per turn to supply conversation history; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchMessagesCallback: MessageRetrievalFn\n /** Called once per turn to supply thought traces; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchThoughtsCallback: ThoughtRetrievalFn\n /** Called once per turn to supply tool call records; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchToolCallsCallback: ToolCallRetrievalFn\n /** Called to supply available tools; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchToolsCallback: ToolsRetrievalFn\n /** Called to refresh and return standing instructions; receives the active {@link @nhtio/adk!TurnContext}. */\n refreshStandingInstructionsCallback: StandingInstructionsRefreshFn\n /** Persists a new standing instruction. */\n storeStandingInstructionCallback: StandingInstructionStoreFn\n /** Updates an existing standing instruction in the persistence layer. */\n mutateStandingInstructionCallback: StandingInstructionMutateFn\n /** Removes a standing instruction from the persistence layer. */\n deleteStandingInstructionCallback: StandingInstructionDeleteFn\n /** Persists a new memory. */\n storeMemoryCallback: MemoryStoreFn\n /** Updates an existing memory in the persistence layer. */\n mutateMemoryCallback: MemoryMutateFn\n /** Removes a memory from the persistence layer by ID. */\n deleteMemoryCallback: MemoryDeleteFn\n /** Called once per turn to supply retrievable (RAG) records; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchRetrievablesCallback: RetrievableRetrievalFn\n /** Persists a new retrievable record. */\n storeRetrievableCallback: RetrievableStoreFn\n /** Updates an existing retrievable record in the persistence layer. */\n mutateRetrievableCallback: RetrievableMutateFn\n /** Removes a retrievable record from the persistence layer by ID. */\n deleteRetrievableCallback: RetrievableDeleteFn\n /** Persists a new message. */\n storeMessageCallback: MessageStoreFn\n /** Updates an existing message in the persistence layer. */\n mutateMessageCallback: MessageMutateFn\n /** Removes a message from the persistence layer by ID. */\n deleteMessageCallback: MessageDeleteFn\n /** Persists a new thought. */\n storeThoughtCallback: ThoughtStoreFn\n /** Updates an existing thought in the persistence layer. */\n mutateThoughtCallback: ThoughtMutateFn\n /** Removes a thought from the persistence layer by ID. */\n deleteThoughtCallback: ThoughtDeleteFn\n /** Persists a new tool call. */\n storeToolCallCallback: ToolCallStoreFn\n /** Updates an existing tool call in the persistence layer. */\n mutateToolCallCallback: ToolCallMutateFn\n /** Removes a tool call from the persistence layer by ID. */\n deleteToolCallCallback: ToolCallDeleteFn\n /** Baseline tools available on every turn. Middleware may trim or extend this per-turn via `ctx.tools`. Defaults to `[]`. */\n tools?: Tool[]\n /** Turn-level input middleware, executed in order against the {@link @nhtio/adk!TurnContext} before the LLM dispatch. Defaults to `[]`. */\n turnInputPipeline?: TurnPipelineMiddlewareFn[]\n /** Turn-level output middleware, executed in order against the {@link @nhtio/adk!TurnContext} after the LLM dispatch resolves successfully. Defaults to `[]`. */\n turnOutputPipeline?: TurnPipelineMiddlewareFn[]\n /** LLM-iteration input middleware, executed in order against the {@link @nhtio/adk!DispatchContext} before the executor on each iteration. Defaults to `[]`. */\n dispatchInputPipeline?: DispatchPipelineMiddlewareFn[]\n /** LLM-iteration output middleware, executed in order against the {@link @nhtio/adk!DispatchContext} after the executor on each iteration. Defaults to `[]`. */\n dispatchOutputPipeline?: DispatchPipelineMiddlewareFn[]\n}\n\n/**\n * Fully-resolved {@link TurnRunnerConfig} after schema validation.\n *\n * @remarks\n * All optional fields are guaranteed present (e.g. `tools` defaults to `[]`). The runner stores\n * this type internally so field access never needs to guard for undefined.\n */\nexport type ResolvedTurnRunnerConfig = Required<TurnRunnerConfig>\n\n/**\n * Validator schema used to validate a {@link TurnRunnerConfig} at {@link @nhtio/adk!TurnRunner} construction time.\n *\n * @remarks\n * Validates that all callbacks are functions of the correct arity, and that `tools` — when\n * provided — is an array of valid {@link @nhtio/adk!Tool} instances. Defaults `tools` to `[]`.\n *\n * Throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} (via the {@link @nhtio/adk!TurnRunner} constructor) when\n * validation fails.\n */\nexport const turnRunnerConfigSchema = validator.object<TurnRunnerConfig>({\n executorCallback: validator.function().required(),\n fetchMemoriesCallback: validator.function().arity(1).required(),\n fetchMessagesCallback: validator.function().arity(1).required(),\n fetchThoughtsCallback: validator.function().arity(1).required(),\n fetchToolCallsCallback: validator.function().arity(1).required(),\n fetchToolsCallback: validator.function().arity(1).required(),\n refreshStandingInstructionsCallback: validator.function().arity(1).required(),\n storeStandingInstructionCallback: validator.function().arity(2).required(),\n mutateStandingInstructionCallback: validator.function().arity(2).required(),\n deleteStandingInstructionCallback: validator.function().arity(2).required(),\n storeMemoryCallback: validator.function().arity(2).required(),\n mutateMemoryCallback: validator.function().arity(2).required(),\n deleteMemoryCallback: validator.function().arity(2).required(),\n fetchRetrievablesCallback: validator.function().arity(1).required(),\n storeRetrievableCallback: validator.function().arity(2).required(),\n mutateRetrievableCallback: validator.function().arity(2).required(),\n deleteRetrievableCallback: validator.function().arity(2).required(),\n storeMessageCallback: validator.function().arity(2).required(),\n mutateMessageCallback: validator.function().arity(2).required(),\n deleteMessageCallback: validator.function().arity(2).required(),\n storeThoughtCallback: validator.function().arity(2).required(),\n mutateThoughtCallback: validator.function().arity(2).required(),\n deleteThoughtCallback: validator.function().arity(2).required(),\n storeToolCallCallback: validator.function().arity(2).required(),\n mutateToolCallCallback: validator.function().arity(2).required(),\n deleteToolCallCallback: validator.function().arity(2).required(),\n tools: validator\n .array()\n .items(\n validator.any().custom((value: unknown, helpers: { error: (code: string) => unknown }) => {\n if (Tool.isTool(value)) return value\n return helpers.error('any.invalid')\n })\n )\n .default([]),\n turnInputPipeline: validator.array().items(validator.function()).default([]),\n turnOutputPipeline: validator.array().items(validator.function()).default([]),\n dispatchInputPipeline: validator.array().items(validator.function()).default([]),\n dispatchOutputPipeline: validator.array().items(validator.function()).default([]),\n})\n","import { DateTime } from 'luxon'\nimport { Middleware } from '@nhtio/middleware'\nimport { TurnGate } from './classes/turn_gate'\nimport { DispatchRunner } from './dispatch_runner'\nimport { ToolRegistry } from './classes/tool_registry'\nimport { isInstanceOf, isError } from './utils/guards'\nimport { TypedEventEmitter } from '@nhtio/tiny-typed-emitter'\nimport { passesSchema, validateOrThrow } from './utils/validation'\nimport { turnRunnerConfigSchema } from './contracts/turn_runner_config'\nimport { TurnContext, RawTurnContext } from './contracts/turn_runner_context'\nimport {\n E_INVALID_TURN_RUNNER_CONFIG,\n E_INPUT_PIPELINE_ERROR,\n E_OUTPUT_PIPELINE_ERROR,\n E_PIPELINE_SHORT_CIRCUITED,\n} from './exceptions/runtime'\nimport type { Runner } from '@nhtio/middleware'\nimport type { RawTurnGate } from './classes/turn_gate'\nimport type { ResolvedTurnRunnerConfig, TurnRunnerConfig } from './contracts/turn_runner_config'\nimport type {\n OpenGateFn,\n TurnEvents,\n TurnEvent,\n TurnEventListener,\n TurnPipelineMiddlewareFn,\n TurnObservabilityEvents,\n TurnObservabilityEvent,\n TurnObservabilityEventListener,\n} from './types/turn_runner'\n\nexport type {\n TurnPipelineMiddlewareFn,\n TurnStreamableContent,\n TurnToolCallContent,\n TurnStartEvent,\n TurnEndEvent,\n TurnGateClosedEvent,\n ToolExecutionStartEvent,\n ToolExecutionEndEvent,\n EmitMessageFn,\n EmitThoughtFn,\n EmitToolCallFn,\n EmitToolExecutionStartFn,\n EmitToolExecutionEndFn,\n OpenGateFn,\n TurnEvents,\n TurnEvent,\n TurnEventListener,\n TurnObservabilityEvents,\n TurnObservabilityEvent,\n TurnObservabilityEventListener,\n} from './types/turn_runner'\n\n/**\n * Executes a single agent turn through paired input and output middleware pipelines.\n *\n * @remarks\n * Construction validates `config` eagerly and throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} if it\n * does not satisfy the schema — fail-fast so misconfiguration surfaces before any turn runs.\n *\n * Each call to {@link TurnRunner.run} threads a {@link @nhtio/adk!TurnContext} through the input pipeline,\n * invokes the model, then threads the result through the output pipeline. Middleware on each side\n * can read and mutate the context for pre- and post-processing (e.g. message normalisation, tool\n * call dispatch, response filtering).\n *\n * **Two event buses:**\n * - Functional bus (`on` / `off` / `once`): `message`, `thought`, `toolCall` — pipeline-affecting\n * events that middleware raises throughout turn execution.\n * - Observability bus (`observe` / `unobserve` / `observeOnce`): `turnStart`, `turnEnd`,\n * `turnGateOpen`, `turnGateClosed`, `error` — instrumentation-only events that monitor execution\n * without participating in it.\n *\n * Streaming content is surfaced via `message` and `thought` events; tool call lifecycle via\n * `toolCall`; non-fatal pipeline errors via the observability `error` event; gate lifecycle via\n * `turnGateOpen` and `turnGateClosed` — all throughout execution.\n *\n * @example\n * ```ts\n * const runner = new TurnRunner({\n * fetchMemoriesCallback: async (ctx) => memoryStore.query(ctx),\n * fetchMessagesCallback: async (ctx) => messageStore.history(ctx),\n * fetchThoughtsCallback: async (ctx) => thoughtStore.history(ctx),\n * fetchToolCallsCallback: async (ctx) => toolCallStore.history(ctx),\n * })\n * // Functional bus — pipeline events\n * runner.on('message', (chunk) => process.stdout.write(chunk.aDelta))\n * // Observability bus — instrumentation\n * runner.observe('error', (err) => console.error(err.toString()))\n * runner.observe('turnStart', ({ turnId }) => console.log('turn started', turnId))\n * runner.observe('turnGateOpen', (gate) => {\n * if (gate.reason === 'tool_approval') {\n * gate.resolve(true) // approve immediately for this example\n * }\n * })\n * await runner.run({\n * turnAbortController: new AbortController(),\n * systemPrompt: 'You are a helpful assistant.',\n * standingInstructions: [],\n * })\n * ```\n */\nexport class TurnRunner {\n /**\n * Returns `true` if `value` is a {@link TurnRunner} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link TurnRunner} instance.\n */\n public static isTurnRunner(value: unknown): value is TurnRunner {\n return isInstanceOf(value, 'TurnRunner', TurnRunner)\n }\n\n #config: ResolvedTurnRunnerConfig\n #inputRunner: Runner<TurnPipelineMiddlewareFn>\n #outputRunner: Runner<TurnPipelineMiddlewareFn>\n #functionalEmitter: TypedEventEmitter<TurnEvents>\n #observabilityEmitter: TypedEventEmitter<TurnObservabilityEvents>\n\n /**\n * @param config - Construction-time configuration validated against {@link turnRunnerConfigSchema}.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} when `config` does not satisfy the schema.\n */\n constructor(config: TurnRunnerConfig) {\n const isValid = passesSchema(turnRunnerConfigSchema, config)\n if (!isValid) {\n throw new E_INVALID_TURN_RUNNER_CONFIG()\n }\n // Store the resolved config so optional fields (e.g. tools) are always present.\n this.#config = validateOrThrow<ResolvedTurnRunnerConfig>(turnRunnerConfigSchema, config, true)\n const turnInputPipeline = new Middleware<TurnPipelineMiddlewareFn>()\n const turnOutputPipeline = new Middleware<TurnPipelineMiddlewareFn>()\n const wrap =\n (fn: TurnPipelineMiddlewareFn): TurnPipelineMiddlewareFn =>\n (ctx, next) => {\n // Skip downstream user middlewares once an abort has been signalled. The\n // wrapper still calls next() so the pipeline reaches its terminal resolver\n // (keeping the short-circuit detector quiet); the original middleware body\n // does not run, so it has nothing to clean up.\n if (ctx.aborted) return next()\n return fn(ctx, next)\n }\n for (const fn of this.#config.turnInputPipeline) turnInputPipeline.add(wrap(fn))\n for (const fn of this.#config.turnOutputPipeline) turnOutputPipeline.add(wrap(fn))\n this.#inputRunner = turnInputPipeline.runner()\n this.#outputRunner = turnOutputPipeline.runner()\n this.#functionalEmitter = new TypedEventEmitter<TurnEvents>()\n this.#observabilityEmitter = new TypedEventEmitter<TurnObservabilityEvents>()\n }\n\n // ── Functional bus ───────────────────────────────────────────────────────\n\n /**\n * Removes a previously registered functional listener for `event`.\n *\n * @param event - The event to stop listening to.\n * @param listener - The listener function to remove.\n * @returns `this` for chaining.\n */\n off<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.off(event, listener)\n return this\n }\n\n /**\n * Registers a persistent functional listener for `event`.\n *\n * @param event - The event to listen to.\n * @param listener - The function to call on each emission.\n * @returns `this` for chaining.\n */\n on<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.on(event, listener)\n return this\n }\n\n /**\n * Registers a one-time functional listener for `event` that is automatically removed after the\n * first emission.\n *\n * @param event - The event to listen to.\n * @param listener - The function to call on the next emission.\n * @returns `this` for chaining.\n */\n once<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.once(event, listener)\n return this\n }\n\n // ── Observability bus ────────────────────────────────────────────────────\n\n /**\n * Removes a previously registered observability listener for `event`.\n *\n * @param event - The event to stop observing.\n * @param listener - The listener function to remove.\n * @returns `this` for chaining.\n */\n unobserve<K>(\n event: TurnObservabilityEvent<K>,\n listener: TurnObservabilityEventListener<K>\n ): this {\n this.#observabilityEmitter.off(event, listener)\n return this\n }\n\n /**\n * Registers a persistent observability listener for `event`.\n *\n * @remarks\n * Use the observability bus (`observe` / `unobserve` / `observeOnce`) for instrumentation:\n * turn lifecycle, gate lifecycle, and non-fatal errors. Use the functional bus (`on` / `off` /\n * `once`) for pipeline-affecting events: `message`, `thought`, `toolCall`.\n *\n * @param event - The event to observe.\n * @param listener - The function to call on each emission.\n * @returns `this` for chaining.\n */\n observe<K>(event: TurnObservabilityEvent<K>, listener: TurnObservabilityEventListener<K>): this {\n this.#observabilityEmitter.on(event, listener)\n return this\n }\n\n /**\n * Registers a one-time observability listener for `event` that is automatically removed after\n * the first emission.\n *\n * @param event - The event to observe once.\n * @param listener - The function to call on the next emission.\n * @returns `this` for chaining.\n */\n observeOnce<K>(\n event: TurnObservabilityEvent<K>,\n listener: TurnObservabilityEventListener<K>\n ): this {\n this.#observabilityEmitter.once(event, listener)\n return this\n }\n\n // ── Turn execution ───────────────────────────────────────────────────────\n\n /**\n * Executes a single agent turn against the provided raw context.\n *\n * @remarks\n * Returns `Promise<void>` intentionally — all meaningful output surfaces via events, not return\n * values. Register listeners before calling `run`: observability events (`turnStart`, `turnEnd`)\n * bracket execution; functional events (`message`, `thought`, `toolCall`) fire throughout;\n * observability `error` carries non-fatal pipeline failures; `turnGateOpen` and `turnGateClosed`\n * fire when middleware suspends via `ctx.waitFor()`. Awaiting this method only tells you the\n * pipeline has finished, not what it produced.\n *\n * Constructs a validated {@link @nhtio/adk!TurnContext} from `context` (throwing\n * {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} on failure), then runs the input middleware pipeline.\n * Abort signals are silently swallowed.\n *\n * @param context - Raw input validated and wrapped into a {@link @nhtio/adk!TurnContext} before execution.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} when `context` does not satisfy the schema.\n */\n async run(context: RawTurnContext): Promise<void> {\n const abortController = context.turnAbortController ?? new AbortController()\n\n // Forward declaration so openGate can reference turnContext.id before it is assigned.\n let turnContextId: string\n\n const openGate: OpenGateFn = <T>(raw: Omit<RawTurnGate, 'turnId' | 'abortSignal'>) => {\n const gate = new TurnGate<T>({\n ...raw,\n turnId: turnContextId,\n abortSignal: abortController.signal,\n })\n this.#observabilityEmitter.emit('turnGateOpen', gate)\n const promise = gate._promise()\n promise.then(\n () => {\n this.#observabilityEmitter.emit('turnGateClosed', {\n gateId: gate.id,\n turnId: gate.turnId,\n result: 'resolved',\n settledAt: DateTime.now(),\n })\n },\n (err: unknown) => {\n let result: 'rejected' | 'aborted' | 'timeout' = 'rejected'\n if (isInstanceOf(err, 'E_TURN_GATE_ABORTED')) result = 'aborted'\n else if (isInstanceOf(err, 'E_TURN_GATE_TIMEOUT')) result = 'timeout'\n this.#observabilityEmitter.emit('turnGateClosed', {\n gateId: gate.id,\n turnId: gate.turnId,\n result,\n settledAt: DateTime.now(),\n })\n }\n )\n return promise\n }\n\n const tools = new ToolRegistry(this.#config.tools)\n\n const turnContext = new TurnContext(\n { ...context, turnAbortController: abortController },\n {\n fetchMemories: this.#config.fetchMemoriesCallback,\n fetchMessages: this.#config.fetchMessagesCallback,\n fetchThoughts: this.#config.fetchThoughtsCallback,\n fetchToolCalls: this.#config.fetchToolCallsCallback,\n fetchTools: this.#config.fetchToolsCallback,\n refreshStandingInstructions: this.#config.refreshStandingInstructionsCallback,\n storeStandingInstruction: this.#config.storeStandingInstructionCallback,\n mutateStandingInstruction: this.#config.mutateStandingInstructionCallback,\n deleteStandingInstruction: this.#config.deleteStandingInstructionCallback,\n storeMemory: this.#config.storeMemoryCallback,\n mutateMemory: this.#config.mutateMemoryCallback,\n deleteMemory: this.#config.deleteMemoryCallback,\n fetchRetrievables: this.#config.fetchRetrievablesCallback,\n storeRetrievable: this.#config.storeRetrievableCallback,\n mutateRetrievable: this.#config.mutateRetrievableCallback,\n deleteRetrievable: this.#config.deleteRetrievableCallback,\n storeMessage: this.#config.storeMessageCallback,\n mutateMessage: this.#config.mutateMessageCallback,\n deleteMessage: this.#config.deleteMessageCallback,\n storeThought: this.#config.storeThoughtCallback,\n mutateThought: this.#config.mutateThoughtCallback,\n deleteThought: this.#config.deleteThoughtCallback,\n storeToolCall: this.#config.storeToolCallCallback,\n mutateToolCall: this.#config.mutateToolCallCallback,\n deleteToolCall: this.#config.deleteToolCallCallback,\n emitMessage: (content) => this.#functionalEmitter.emit('message', content),\n emitThought: (content) => this.#functionalEmitter.emit('thought', content),\n emitToolCall: (content) => this.#functionalEmitter.emit('toolCall', content),\n emitToolExecutionStart: (event) =>\n this.#observabilityEmitter.emit('toolExecutionStart', event),\n emitToolExecutionEnd: (event) => this.#observabilityEmitter.emit('toolExecutionEnd', event),\n openGate,\n tools,\n }\n )\n\n turnContextId = turnContext.id\n\n const startedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnStart', { turnId: turnContext.id, startedAt })\n\n const emitTurnEnd = () => {\n const endedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnEnd', {\n turnId: turnContext.id,\n startedAt,\n endedAt,\n durationMs: endedAt.diff(startedAt).milliseconds,\n })\n }\n\n // 1. Input pipeline\n let inputFailed = false\n let inputReached = false\n await this.#inputRunner\n .errorHandler(async (error) => {\n if (!isError(error) || !isInstanceOf(error, 'AbortError')) {\n inputFailed = true\n const err = new E_INPUT_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n this.#observabilityEmitter.emit('error', err)\n }\n })\n .finalHandler(async () => {\n inputReached = true\n })\n .run((fn, next) => Promise.resolve(fn(turnContext, next)))\n\n if (!inputReached && !inputFailed && !turnContext.aborted) {\n inputFailed = true\n const err = new E_PIPELINE_SHORT_CIRCUITED(['turn-input'])\n this.#observabilityEmitter.emit('error', err)\n }\n\n if (inputFailed || turnContext.aborted) {\n emitTurnEnd()\n return\n }\n\n // 2. LLM execution dispatch\n let dispatchFailed = false\n try {\n await DispatchRunner.dispatch({\n source: turnContext,\n executor: this.#config.executorCallback,\n turnInputPipeline: this.#config.dispatchInputPipeline,\n turnOutputPipeline: this.#config.dispatchOutputPipeline,\n observers: {\n dispatchStart: [\n (e) => {\n this.#observabilityEmitter.emit('dispatchStart', e)\n },\n ],\n dispatchEnd: [\n (e) => {\n this.#observabilityEmitter.emit('dispatchEnd', e)\n },\n ],\n iterationStart: [\n (e) => {\n this.#observabilityEmitter.emit('iterationStart', e)\n },\n ],\n iterationEnd: [\n (e) => {\n this.#observabilityEmitter.emit('iterationEnd', e)\n },\n ],\n log: [\n (e) => {\n this.#observabilityEmitter.emit('log', e)\n },\n ],\n },\n })\n } catch (err) {\n dispatchFailed = true\n const wrapped = isInstanceOf(err, 'BaseException') ? (err as InstanceType<typeof Error>) : err\n this.#observabilityEmitter.emit('error', wrapped as any)\n }\n\n if (dispatchFailed || turnContext.aborted) {\n emitTurnEnd()\n return\n }\n\n // 3. Output pipeline\n let outputFailed = false\n let outputReached = false\n await this.#outputRunner\n .errorHandler(async (error) => {\n if (!isError(error) || !isInstanceOf(error, 'AbortError')) {\n outputFailed = true\n const err = new E_OUTPUT_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n this.#observabilityEmitter.emit('error', err)\n }\n })\n .finalHandler(async () => {\n outputReached = true\n })\n .run((fn, next) => Promise.resolve(fn(turnContext, next)))\n\n if (!outputReached && !outputFailed && !turnContext.aborted) {\n const err = new E_PIPELINE_SHORT_CIRCUITED(['turn-output'])\n this.#observabilityEmitter.emit('error', err)\n }\n\n emitTurnEnd()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiEA,IAAM,oBAAoB,UAAU,OAAoB;CACtD,IAAI,UAAU,OAAO,EAAE,SAAS;CAChC,QAAQ,UAAU,OAAO,EAAE,SAAS;CACpC,QAAQ,UAAU,OAAO,EAAE,SAAS;CACpC,SAAS,UAAU,IAAI,EAAE,SAAS;CAClC,QAAQ,UACL,IAAI,EACJ,QAAQ,OAAO,YAAY;EAC1B,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,KAAA;EAClD,IAAI,O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AI,CAAC,QAAQ,KAAK,KAAK,CAAC,aAAa,OAAO,YAAY,GAAG;IACzD,eAAe;IACf,MAAM,MAAM,IAAI,wBAAwB,EACtC,OAAO,QAAQ,KAAK,IAAI,QAAQ,KAAA,EAClC,CAAC;IACD,KAAKE,sBAAsB,KAAK,SAAS,GAAG;GAC9C;EACF,CAAC,EACA,aAAa,YAAY;GACxB,gBAAgB;EAClB,CAAC,EACA,KAAK,IAAI,SAAS,QAAQ,QAAQ,GAAG,aAAa,IAAI,CAAC,CAAC;EAE3D,IAAI,CAAC,iBAAiB,CAAC,gBAAgB,CAAC,YAAY,SAAS;GAC3D,MAAM,MAAM,IAAI,2BAA2B,CAAC,aAAa,CAAC;GAC1D,KAAKA,sBAAsB,KAAK,SAAS,GAAG;EAC9C;EAEA,YAAY;CACd;AACF"}
|
package/turn_runner.cjs
CHANGED
package/turn_runner.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as TurnRunner } from "./turn_runner-
|
|
1
|
+
import { t as TurnRunner } from "./turn_runner-y7eyEcJH.mjs";
|
|
2
2
|
export { TurnRunner };
|
package/types.d.ts
CHANGED
|
@@ -41,13 +41,13 @@ export type { TokenEncoding } from "./lib/classes/tokenizable";
|
|
|
41
41
|
/**
|
|
42
42
|
* @primaryExport
|
|
43
43
|
*/
|
|
44
|
-
export type { RawTurnContext, ResolvedTurnContext, MemoryRetrievalFn, MessageRetrievalFn, ThoughtRetrievalFn, ToolCallRetrievalFn, ToolsRetrievalFn, RetrievableRetrievalFn, StandingInstructionsRefreshFn, StandingInstructionStoreFn, StandingInstructionMutateFn, StandingInstructionDeleteFn, MemoryStoreFn, MemoryMutateFn, MemoryDeleteFn, MessageStoreFn, MessageMutateFn, MessageDeleteFn, ThoughtStoreFn, ThoughtMutateFn, ThoughtDeleteFn, ToolCallStoreFn, ToolCallMutateFn, ToolCallDeleteFn, RetrievableStoreFn, RetrievableMutateFn, RetrievableDeleteFn,
|
|
44
|
+
export type { RawTurnContext, ResolvedTurnContext, MemoryRetrievalFn, MessageRetrievalFn, ThoughtRetrievalFn, ToolCallRetrievalFn, ToolsRetrievalFn, RetrievableRetrievalFn, StandingInstructionsRefreshFn, StandingInstructionStoreFn, StandingInstructionMutateFn, StandingInstructionDeleteFn, MemoryStoreFn, MemoryMutateFn, MemoryDeleteFn, MessageStoreFn, MessageMutateFn, MessageDeleteFn, ThoughtStoreFn, ThoughtMutateFn, ThoughtDeleteFn, ToolCallStoreFn, ToolCallMutateFn, ToolCallDeleteFn, RetrievableStoreFn, RetrievableMutateFn, RetrievableDeleteFn, } from "./lib/contracts/turn_runner_context";
|
|
45
45
|
export type { TurnRunnerConfig, ResolvedTurnRunnerConfig } from "./lib/contracts/turn_runner_config";
|
|
46
46
|
export type { TurnPipelineMiddlewareFn, TurnStreamableContent, TurnToolCallContent, TurnStartEvent, TurnEndEvent, TurnGateClosedEvent, ToolExecutionStartEvent, ToolExecutionEndEvent, EmitMessageFn, EmitThoughtFn, EmitToolCallFn, EmitToolExecutionStartFn, EmitToolExecutionEndFn, OpenGateFn, TurnEvents, TurnEvent, TurnEventListener, TurnObservabilityEvents, TurnObservabilityEvent, TurnObservabilityEventListener, } from "./lib/types/turn_runner";
|
|
47
47
|
/**
|
|
48
48
|
* @primaryExport
|
|
49
49
|
*/
|
|
50
|
-
export type { RawDispatchContext, DispatchMemoryRetrievalFn, DispatchMessageRetrievalFn, DispatchThoughtRetrievalFn, DispatchToolCallRetrievalFn, DispatchToolsRetrievalFn, DispatchStandingInstructionsRefreshFn, DispatchStandingInstructionStoreFn, DispatchStandingInstructionMutateFn, DispatchStandingInstructionDeleteFn, DispatchMemoryStoreFn, DispatchMemoryMutateFn, DispatchMemoryDeleteFn, DispatchMessageStoreFn, DispatchMessageMutateFn, DispatchMessageDeleteFn, DispatchThoughtStoreFn, DispatchThoughtMutateFn, DispatchThoughtDeleteFn, DispatchToolCallStoreFn, DispatchToolCallMutateFn, DispatchToolCallDeleteFn,
|
|
50
|
+
export type { RawDispatchContext, DispatchMemoryRetrievalFn, DispatchMessageRetrievalFn, DispatchThoughtRetrievalFn, DispatchToolCallRetrievalFn, DispatchToolsRetrievalFn, DispatchStandingInstructionsRefreshFn, DispatchStandingInstructionStoreFn, DispatchStandingInstructionMutateFn, DispatchStandingInstructionDeleteFn, DispatchMemoryStoreFn, DispatchMemoryMutateFn, DispatchMemoryDeleteFn, DispatchMessageStoreFn, DispatchMessageMutateFn, DispatchMessageDeleteFn, DispatchThoughtStoreFn, DispatchThoughtMutateFn, DispatchThoughtDeleteFn, DispatchToolCallStoreFn, DispatchToolCallMutateFn, DispatchToolCallDeleteFn, } from "./lib/contracts/dispatch_context";
|
|
51
51
|
/**
|
|
52
52
|
* @primaryExport
|
|
53
53
|
*/
|
package/CHANGELOG.md
DELETED
|
@@ -1,49 +0,0 @@
|
|
|
1
|
-
# Changelog
|
|
2
|
-
|
|
3
|
-
All notable changes to `@nhtio/adk` are documented in this file.
|
|
4
|
-
|
|
5
|
-
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|
6
|
-
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
|
-
|
|
8
|
-
## [Unreleased]
|
|
9
|
-
|
|
10
|
-
### Added
|
|
11
|
-
|
|
12
|
-
- **Unified `ByteStore<R>` storage contract** (`src/lib/contracts/byte_store.ts`) — the single
|
|
13
|
-
low-level "give bytes, get a reader" shape every storage layer implements, with `SpoolStore`
|
|
14
|
-
(`ByteStore<SpoolReader>`) and `MediaStore` (`ByteStore<MediaReader>`) semantic aliases. `write`
|
|
15
|
-
accepts `string | Uint8Array | ReadableStream<Uint8Array>`; string input is UTF-8-encoded.
|
|
16
|
-
Exported alongside `implementsByteStore` and `byteStoreSchema`.
|
|
17
|
-
- **Injectable `spoolStore` option** on the OpenAI and WebLLM Chat Completions batteries — back
|
|
18
|
-
tool-output artifacts with durable storage (`OpfsSpoolStore`, a Flydrive-backed store) instead of
|
|
19
|
-
the default per-dispatch in-memory store. Durable stores also stream large/binary tool output to
|
|
20
|
-
disk rather than buffering it in memory.
|
|
21
|
-
- **`ctx.storeMediaBytes(id, bytes)` → `MediaReader`** and **`ctx.storeRetrievableBytes(id, bytes)`
|
|
22
|
-
→ `SpoolReader`** — handler-reachable byte-persistence conduits that route tool-generated media
|
|
23
|
-
and large extracted RAG text into consumer storage. Both accept a `ReadableStream`. Exposed on
|
|
24
|
-
`TurnContext` and `DispatchContext`; `ConduitBytes` is exported from the public API.
|
|
25
|
-
- **Reader-backed `Retrievable.content`** — `content` now accepts a `SpooledArtifact` in addition
|
|
26
|
-
to `string | Tokenizable`, so large extracted RAG text can live in a consumer `ByteStore` instead
|
|
27
|
-
of permanently on the heap. New `Retrievable.estimateTokens(encoding)` and
|
|
28
|
-
`Retrievable.contentString()` accessors. (Note: token estimation and render still materialise the
|
|
29
|
-
body transiently; reader-backing removes *permanent* heap residency, not the transient
|
|
30
|
-
allocation.)
|
|
31
|
-
|
|
32
|
-
### Fixed
|
|
33
|
-
|
|
34
|
-
- **`InMemorySpoolStore` no longer corrupts binary tool output.** It previously UTF-8-decoded every
|
|
35
|
-
`Uint8Array` at write time, mangling non-text bytes (PDFs, images). Bytes are now stored
|
|
36
|
-
byte-faithfully; `InMemorySpoolReader` decodes on demand for line/text reads and reports the true
|
|
37
|
-
stored byte length.
|
|
38
|
-
|
|
39
|
-
### Changed (BREAKING)
|
|
40
|
-
|
|
41
|
-
- **Render helpers are now async.** `renderFirstPartyRetrievables`,
|
|
42
|
-
`renderThirdPartyPublicRetrievables`, `renderThirdPartyPrivateRetrievables`, `renderRetrievables`,
|
|
43
|
-
and `renderChatCompletionsSystemPrompt` on `ChatCompletionsHelpers` now return `Promise<string>`
|
|
44
|
-
(previously `string`). Consumers who override these helpers must update their signatures.
|
|
45
|
-
- **`TurnRunnerConfig` gains two required callbacks** — `storeMediaBytesCallback` and
|
|
46
|
-
`storeRetrievableBytesCallback` (both arity 3). `RawDispatchContext` gains the matching required
|
|
47
|
-
`storeMediaBytes` / `storeRetrievableBytes` fields.
|
|
48
|
-
- **Tool-output spool writes are now awaited** — a custom `spoolStore.write()` may return a
|
|
49
|
-
`Promise` (required for `ReadableStream` input).
|
package/common-BJ6V6dsH.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"common-BJ6V6dsH.js","names":["#id","#content","#trustTier","#source","#kind","#score","#createdAt","#updatedAt"],"sources":["../src/lib/classes/retrievable.ts","../src/lib/contracts/byte_store.ts","../src/lib/helpers/media_readers.ts"],"sourcesContent":["import { Tokenizable } from './tokenizable'\nimport { validator } from '@nhtio/validation'\nimport { SpooledArtifact } from './spooled_artifact'\nimport { validateOrThrow } from '../utils/validation'\nimport { isInstanceOf, isError } from '../utils/guards'\nimport { E_INVALID_INITIAL_RETRIEVABLE_VALUE } from '../exceptions/runtime'\nimport type { DateTime } from 'luxon'\nimport type { TokenEncoding } from './tokenizable'\n\n/**\n * Trust-tier discriminator declared by the retrieval middleware at construction time. Drives\n * which envelope the LLM battery wraps the record in.\n *\n * @remarks\n * Vocabulary deliberately mirrors the published security-research taxonomy (\"first-party /\n * third-party\" per *Hidden-in-Plain-Text* WWW '26 and *When AI Meets the Web* IEEE S&P 2026)\n * and explicitly avoids the words \"user\" or \"system\" so the names cannot leak into the model's\n * OpenAI-Model-Spec role-tier authority resolution.\n *\n * - `'first-party'` — deployer-vetted corpora (signed internal docs, policy KBs, curated\n * reference material). Rendered as a `<retrieved_corpus>` parent with per-record nonce-keyed\n * `<retrieved>` children. The label \"first-party\" never appears in the envelope itself.\n * - `'third-party-public'` — open-web scrapes, search results, public APIs. Rendered through\n * the untrusted-content envelope with `kind: 'retrieved-third-party-public'`.\n * - `'third-party-private'` — user uploads, pasted attachments, partner APIs. Rendered through\n * the untrusted-content envelope with `kind: 'retrieved-third-party-private'`.\n */\nexport type RetrievableTrustTier = 'first-party' | 'third-party-public' | 'third-party-private'\n\n/**\n * Plain input object supplied to {@link Retrievable} at construction time.\n *\n * @remarks\n * Validated against `rawRetrievableSchema` before the `Retrievable` instance is created.\n * Temporal fields accept any value that Luxon can parse — ISO strings, Unix timestamps,\n * `Date` objects, or existing `DateTime` instances.\n */\nexport interface RawRetrievable {\n /**\n * Stable unique identifier for this retrieved record. Used as the closing-tag nonce in the\n * rendered envelope, so it must be unguessable from the payload.\n */\n id: string\n /**\n * The retrieved content. A plain `string` or {@link @nhtio/adk!Tokenizable} for small inline text, or a\n * {@link @nhtio/adk!SpooledArtifact} when the extracted text is large and lives in a consumer\n * {@link @nhtio/adk!ByteStore} (persist it via {@link @nhtio/adk!DispatchContext.storeRetrievableBytes}, wrap\n * the returned reader in a `SpooledArtifact`, and pass it here). Reader-backed content keeps the\n * body out of the permanent heap, but token estimation and render still materialise it\n * transiently (see {@link Retrievable.estimateTokens}).\n */\n content: string | Tokenizable | SpooledArtifact\n /**\n * Trust tier declared by the retrieval middleware at construction time. Required — there is\n * NO default. The decision must be conscious. See {@link RetrievableTrustTier}.\n */\n trustTier: RetrievableTrustTier\n /** Optional provenance string: URL, document path, knowledge-base id, etc. */\n source?: string\n /** Optional semantic label: 'policy' | 'reference' | 'web-page' | 'pdf' | etc. */\n kind?: string\n /** Optional relevance / similarity score in `[0, 1]` from the retrieval middleware. */\n score?: number\n /** When the source record was created (publication date, upload date, etc.). */\n createdAt: string | number | Date | DateTime\n /** When the source record was last modified. */\n updatedAt: string | number | Date | DateTime\n}\n\n/**\n * A fully-resolved {@link RawRetrievable} where all fields have been validated and temporal\n * values normalised to Luxon `DateTime` instances.\n */\ninterface ResolvedRetrievable {\n id: string\n content: Tokenizable | SpooledArtifact\n trustTier: RetrievableTrustTier\n source?: string\n kind?: string\n score?: number\n createdAt: DateTime\n updatedAt: DateTime\n}\n\n/**\n * Validator schema used to validate a {@link RawRetrievable} before constructing a\n * {@link Retrievable}.\n *\n * @remarks\n * - `id` — required non-empty string.\n * - `content` — required {@link @nhtio/adk!Tokenizable.schema}.\n * - `trustTier` — required, one of `'first-party'`, `'third-party-public'`,\n * `'third-party-private'`. Unknown / missing values reject.\n * - `source` / `kind` — optional strings.\n * - `score` — optional number in `[0, 1]`.\n * - `createdAt` / `updatedAt` — required datetime-parseable values.\n *\n * Throws {@link @nhtio/adk/exceptions!E_INVALID_INITIAL_RETRIEVABLE_VALUE} (via the {@link Retrievable} constructor)\n * when validation fails.\n */\nconst contentSchema = validator.alternatives(\n validator.string(),\n validator.custom((value, helpers) => {\n if (Tokenizable.isTokenizable(value) || SpooledArtifact.isSpooledArtifact(value)) {\n return value\n }\n return helpers.error('any.invalid')\n })\n)\n\nconst rawRetrievableSchema = validator.object<RawRetrievable>({\n id: validator.string().required(),\n content: contentSchema.required(),\n trustTier: validator\n .string()\n .valid('first-party', 'third-party-public', 'third-party-private')\n .required(),\n source: validator.string().optional(),\n kind: validator.string().optional(),\n score: validator.number().min(0).max(1).optional(),\n createdAt: validator.datetime().required(),\n updatedAt: validator.datetime().required(),\n})\n\n/**\n * An immutable, validated retrieved record (RAG content) held by the agent.\n *\n * @remarks\n * Peer of {@link @nhtio/adk!Memory} / `Message` / `Thought` / `ToolCall`. Carries an explicit `trustTier`\n * that LLM batteries branch on to choose the rendering envelope. The retrieval middleware that\n * produced the record is the only party that knows its provenance — batteries MUST NOT\n * auto-classify or infer the tier from `source`.\n */\nexport class Retrievable {\n /**\n * Validator schema that accepts a {@link RawRetrievable} object.\n *\n * @remarks\n * Reusable fragment for any schema that needs to validate or nest a retrievable record.\n */\n public static schema = rawRetrievableSchema\n\n /**\n * Returns `true` if `value` is a {@link Retrievable} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n */\n public static isRetrievable(value: unknown): value is Retrievable {\n return isInstanceOf(value, 'Retrievable', Retrievable)\n }\n\n /** Stable unique identifier for this retrieved record. */\n declare readonly id: string\n /**\n * The retrieved content: a {@link @nhtio/adk!Tokenizable} (inline text) or a\n * {@link @nhtio/adk!SpooledArtifact} (reader-backed, large text living in a consumer store). Use\n * {@link Retrievable.estimateTokens} for budgeting and {@link Retrievable.contentString} to\n * materialise the body at render time.\n */\n declare readonly content: Tokenizable | SpooledArtifact\n /** Trust tier declared by the retrieval middleware. */\n declare readonly trustTier: RetrievableTrustTier\n /** Optional provenance string. */\n declare readonly source: string | undefined\n /** Optional semantic label. */\n declare readonly kind: string | undefined\n /** Optional relevance / similarity score in `[0, 1]`. */\n declare readonly score: number | undefined\n /** When the source record was created. */\n declare readonly createdAt: DateTime\n /** When the source record was last modified. */\n declare readonly updatedAt: DateTime\n\n #id: string\n #content: Tokenizable | SpooledArtifact\n #trustTier: RetrievableTrustTier\n #source: string | undefined\n #kind: string | undefined\n #score: number | undefined\n #createdAt: DateTime\n #updatedAt: DateTime\n\n /**\n * @param raw - The raw retrievable input validated against `rawRetrievableSchema`.\n * @throws {@link @nhtio/adk/exceptions!E_INVALID_INITIAL_RETRIEVABLE_VALUE} when `raw` does not satisfy the schema.\n */\n constructor(raw: RawRetrievable) {\n let resolved: ResolvedRetrievable\n try {\n resolved = validateOrThrow<ResolvedRetrievable>(rawRetrievableSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_RETRIEVABLE_VALUE({ cause: isError(err) ? err : undefined })\n }\n this.#id = resolved.id\n this.#content =\n Tokenizable.isTokenizable(resolved.content) ||\n SpooledArtifact.isSpooledArtifact(resolved.content)\n ? resolved.content\n : new Tokenizable(resolved.content)\n this.#trustTier = resolved.trustTier\n this.#source = resolved.source\n this.#kind = resolved.kind\n this.#score = resolved.score\n this.#createdAt = resolved.createdAt\n this.#updatedAt = resolved.updatedAt\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n content: {\n get: () => this.#content,\n enumerable: true,\n configurable: false,\n },\n trustTier: {\n get: () => this.#trustTier,\n enumerable: true,\n configurable: false,\n },\n source: {\n get: () => this.#source,\n enumerable: true,\n configurable: false,\n },\n kind: {\n get: () => this.#kind,\n enumerable: true,\n configurable: false,\n },\n score: {\n get: () => this.#score,\n enumerable: true,\n configurable: false,\n },\n createdAt: {\n get: () => this.#createdAt,\n enumerable: true,\n configurable: false,\n },\n updatedAt: {\n get: () => this.#updatedAt,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Estimates the token count of the content under `encoding`.\n *\n * @remarks\n * Delegates to the content's own `estimateTokens`: synchronous for a {@link @nhtio/adk!Tokenizable}\n * (returns `number`), asynchronous for a {@link @nhtio/adk!SpooledArtifact} (returns\n * `Promise<number>`, reading the bytes from the backing store on demand). Both shapes satisfy the\n * adapter's token-budget path, which already awaits estimates.\n *\n * Note: the `SpooledArtifact` branch materialises the full decoded string transiently to count\n * tokens — reader-backing keeps the body off the *permanent* heap, but does not eliminate the\n * transient allocation at budgeting time.\n *\n * @param encoding - The encoding identifier to use for counting.\n * @returns The estimated token count.\n */\n estimateTokens(encoding: TokenEncoding): number | Promise<number> {\n return this.#content.estimateTokens(encoding)\n }\n\n /**\n * Returns the content body as a single string.\n *\n * @remarks\n * For a {@link @nhtio/adk!Tokenizable} this is synchronous in effect (resolved immediately); for a\n * {@link @nhtio/adk!SpooledArtifact} it reads the full body from the backing store via\n * {@link @nhtio/adk!SpooledArtifact.asString}. Always returns a `Promise` so callers have one\n * code path; render helpers `await` it at the point the trust-tier envelope is built.\n *\n * @returns The full content body as a string.\n */\n async contentString(): Promise<string> {\n return SpooledArtifact.isSpooledArtifact(this.#content)\n ? this.#content.asString()\n : this.#content.toString()\n }\n}\n","import { validator } from '@nhtio/validation'\nimport { passesSchema } from '../utils/validation'\nimport type { SpoolReader } from './spool_reader'\nimport type { MediaReader } from './media_reader'\n\n/**\n * Unified \"give bytes, get a reader\" persistence contract.\n *\n * @remarks\n * For the purposes of storage there is no meaningful distinction between text and binary — bytes\n * are bytes. `ByteStore` is the single low-level shape every ADK storage layer implements: hand it\n * bytes under an `id`, get back a replayable reader `R`; read or delete by the same `id` later. The\n * generic `R` is the reader the store hands out — different reader contracts (line-indexed\n * {@link @nhtio/adk!SpoolReader} vs binary-streamed {@link @nhtio/adk!MediaReader}) are\n * distinguished by the `R` instantiation, not by separate store interfaces. See the {@link SpoolStore}\n * and {@link MediaStore} aliases for the two concrete semantics.\n *\n * `write` accepts a `string`, a `Uint8Array`, or a `ReadableStream<Uint8Array>`. The stream form is\n * the point of the contract: a durable store can persist an arbitrarily large payload straight to\n * disk/object storage without first materializing it in memory. **String input is encoded as\n * UTF-8.** The returned reader is only guaranteed readable once the `write` result has resolved.\n *\n * All three methods may be synchronous or asynchronous so that in-memory implementations are not\n * forced to pay promise overhead while I/O-backed implementations stay async. Note that any\n * implementation accepting a `ReadableStream` must return a `Promise` for that input — draining a\n * stream cannot be synchronous.\n */\nexport interface ByteStore<R> {\n /**\n * Persists `bytes` under `id` and returns a reader over them.\n *\n * @remarks\n * Re-writing the same `id` replaces the prior entry. `string` input is encoded as UTF-8;\n * `Uint8Array` and `ReadableStream<Uint8Array>` are stored byte-faithfully. Stream input\n * necessarily resolves asynchronously.\n *\n * @param id - Identifier used to retrieve or delete the bytes later.\n * @param bytes - The payload, as a `string`, `Uint8Array`, or `ReadableStream<Uint8Array>`.\n * @returns A reader over the stored bytes (or a `Promise` of one).\n */\n write(id: string, bytes: string | Uint8Array | ReadableStream<Uint8Array>): R | Promise<R>\n\n /**\n * Returns a reader over the bytes previously written under `id`, or `undefined` if no entry\n * exists.\n *\n * @param id - Identifier supplied to a prior {@link ByteStore.write} call.\n * @returns A reader over the stored bytes, `undefined`, or a `Promise` of either.\n */\n read(id: string): R | undefined | Promise<R | undefined>\n\n /**\n * Removes the entry under `id`.\n *\n * @param id - Identifier whose entry should be removed.\n * @returns `true` if an entry existed and was removed; `false` otherwise (or a `Promise` of one).\n */\n delete(id: string): boolean | Promise<boolean>\n}\n\n/**\n * A {@link ByteStore} that hands out line-indexed text readers ({@link @nhtio/adk!SpoolReader}).\n *\n * @remarks\n * The store backing tool-output artifacts. Stored bytes are decoded as UTF-8 text for line-oriented\n * reads; binary input is stored byte-faithfully but `SpoolReader.readAll()` interprets it as text,\n * so opaque binary belongs in a {@link MediaStore} / `Media`, not here.\n */\nexport type SpoolStore = ByteStore<SpoolReader>\n\n/**\n * A {@link ByteStore} that hands out binary-streamed readers ({@link @nhtio/adk!MediaReader}).\n *\n * @remarks\n * The store backing persisted media bytes. Stored bytes are opaque and replayable via\n * `MediaReader.stream()`; no text decoding is implied.\n */\nexport type MediaStore = ByteStore<MediaReader>\n\n/**\n * Validator schema used to validate a {@link ByteStore} value.\n *\n * @remarks\n * Because `ByteStore` is a structural interface with no associated constructor, validation is\n * duck-typed: the value must be non-null with `write`, `read`, and `delete` present as callable\n * properties. Arity is not enforced — implementations may add optional parameters beyond the\n * contract. The reader type `R` cannot be checked structurally here; conformance of the reader is\n * the caller's concern at the point of use.\n */\nexport const byteStoreSchema = validator.any().custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).write === 'function' &&\n typeof (value as any).read === 'function' &&\n typeof (value as any).delete === 'function'\n ) {\n return value\n }\n return helpers.error('any.invalid')\n})\n\n/**\n * Returns `true` if `value` implements the {@link ByteStore} interface.\n *\n * @remarks\n * Duck-typed: checks that `value` is non-null with `write`, `read`, and `delete` as callable\n * functions. Does not use `instanceof` — there is no `ByteStore` constructor.\n *\n * @param value - The value to test.\n * @returns `true` when `value` conforms to the {@link ByteStore} interface.\n */\nexport const implementsByteStore = <R = unknown>(value: unknown): value is ByteStore<R> => {\n return passesSchema(byteStoreSchema, value)\n}\n","import type { MediaReader } from '../contracts/media_reader'\n\n/**\n * Constructs a {@link @nhtio/adk!MediaReader} backed by an in-memory `Uint8Array`.\n *\n * @remarks\n * Each `stream()` call returns a fresh single-chunk `ReadableStream` over the same buffer. The\n * reader is re-openable by construction — call `stream()` as many times as needed.\n *\n * @param bytes - The buffer to serve.\n * @returns A {@link @nhtio/adk!MediaReader} that re-reads `bytes` on every call.\n */\nexport const inMemoryMediaReader = (bytes: Uint8Array): MediaReader => {\n return {\n stream(): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(bytes)\n controller.close()\n },\n })\n },\n byteLength(): number {\n return bytes.byteLength\n },\n }\n}\n\n/**\n * Constructs a {@link @nhtio/adk!MediaReader} backed by a fetch call.\n *\n * @remarks\n * Each `stream()` call re-issues the fetch. Tool authors whose underlying source is rate-limited\n * or expensive must cache locally before constructing the reader — the framework cannot make\n * that decision for them.\n *\n * `byteLength()` returns `undefined` because most remote sources do not promise it without an\n * extra HEAD request; consumers that need a byte size should resolve it out-of-band.\n *\n * @param url - The URL to fetch on each call.\n * @param init - Optional `fetch` init forwarded verbatim.\n * @returns A {@link @nhtio/adk!MediaReader} that re-issues `fetch(url, init)` on every call.\n */\nexport const fromFetch = (url: string | URL, init?: RequestInit): MediaReader => {\n return {\n async stream(): Promise<ReadableStream<Uint8Array>> {\n const response = await fetch(url, init)\n if (!response.ok) {\n throw new Error(`fromFetch: fetch failed with status ${response.status}`)\n }\n if (!response.body) {\n throw new Error('fromFetch: response has no body')\n }\n return response.body as ReadableStream<Uint8Array>\n },\n byteLength(): undefined {\n return undefined\n },\n }\n}\n\n/**\n * Constructs a {@link @nhtio/adk!MediaReader} backed by a browser `File` or `Blob`.\n *\n * @remarks\n * Each `stream()` call re-streams the underlying File via `File.stream()`. `byteLength()`\n * resolves from `file.size`.\n *\n * @param file - The browser `File` or `Blob` to stream.\n * @returns A {@link @nhtio/adk!MediaReader} that re-streams `file` on every call.\n */\nexport const fromWebFile = (file: Blob): MediaReader => {\n return {\n stream(): ReadableStream<Uint8Array> {\n return file.stream() as ReadableStream<Uint8Array>\n },\n byteLength(): number {\n return file.size\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoGA,IAAM,gBAAgB,kBAAA,UAAU,aAC9B,kBAAA,UAAU,OAAO,GACjB,kBAAA,UAAU,QAAQ,OAAO,YAAY;CACnC,IAAI,sBAAA,YAAY,cAAc,KAAK,KAAK,yBAAA,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,WAAW,QAAQ,KAAK;IACxB,WAAW,MAAM;GACnB,EACF,CAAC;EACH;EACA,aAAqB;GACnB,OAAO,MAAM;EACf;CACF;AACF;;;;;;;;;;;;;;;;AAiBA,IAAa,aAAa,KAAmB,SAAoC;CAC/E,OAAO;EACL,MAAM,SAA8C;GAClD,MAAM,WAAW,MAAM,MAAM,KAAK,IAAI;GACtC,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,uCAAuC,SAAS,QAAQ;GAE1E,IAAI,CAAC,SAAS,MACZ,MAAM,IAAI,MAAM,iCAAiC;GAEnD,OAAO,SAAS;EAClB;EACA,aAAwB,CAExB;CACF;AACF;;;;;;;;;;;AAYA,IAAa,eAAe,SAA4B;CACtD,OAAO;EACL,SAAqC;GACnC,OAAO,KAAK,OAAO;EACrB;EACA,aAAqB;GACnB,OAAO,KAAK;EACd;CACF;AACF"}
|
package/common-aFmr9Oqs.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"common-aFmr9Oqs.mjs","names":["#id","#content","#trustTier","#source","#kind","#score","#createdAt","#updatedAt"],"sources":["../src/lib/classes/retrievable.ts","../src/lib/contracts/byte_store.ts","../src/lib/helpers/media_readers.ts"],"sourcesContent":["import { Tokenizable } from './tokenizable'\nimport { validator } from '@nhtio/validation'\nimport { SpooledArtifact } from './spooled_artifact'\nimport { validateOrThrow } from '../utils/validation'\nimport { isInstanceOf, isError } from '../utils/guards'\nimport { E_INVALID_INITIAL_RETRIEVABLE_VALUE } from '../exceptions/runtime'\nimport type { DateTime } from 'luxon'\nimport type { TokenEncoding } from './tokenizable'\n\n/**\n * Trust-tier discriminator declared by the retrieval middleware at construction time. Drives\n * which envelope the LLM battery wraps the record in.\n *\n * @remarks\n * Vocabulary deliberately mirrors the published security-research taxonomy (\"first-party /\n * third-party\" per *Hidden-in-Plain-Text* WWW '26 and *When AI Meets the Web* IEEE S&P 2026)\n * and explicitly avoids the words \"user\" or \"system\" so the names cannot leak into the model's\n * OpenAI-Model-Spec role-tier authority resolution.\n *\n * - `'first-party'` — deployer-vetted corpora (signed internal docs, policy KBs, curated\n * reference material). Rendered as a `<retrieved_corpus>` parent with per-record nonce-keyed\n * `<retrieved>` children. The label \"first-party\" never appears in the envelope itself.\n * - `'third-party-public'` — open-web scrapes, search results, public APIs. Rendered through\n * the untrusted-content envelope with `kind: 'retrieved-third-party-public'`.\n * - `'third-party-private'` — user uploads, pasted attachments, partner APIs. Rendered through\n * the untrusted-content envelope with `kind: 'retrieved-third-party-private'`.\n */\nexport type RetrievableTrustTier = 'first-party' | 'third-party-public' | 'third-party-private'\n\n/**\n * Plain input object supplied to {@link Retrievable} at construction time.\n *\n * @remarks\n * Validated against `rawRetrievableSchema` before the `Retrievable` instance is created.\n * Temporal fields accept any value that Luxon can parse — ISO strings, Unix timestamps,\n * `Date` objects, or existing `DateTime` instances.\n */\nexport interface RawRetrievable {\n /**\n * Stable unique identifier for this retrieved record. Used as the closing-tag nonce in the\n * rendered envelope, so it must be unguessable from the payload.\n */\n id: string\n /**\n * The retrieved content. A plain `string` or {@link @nhtio/adk!Tokenizable} for small inline text, or a\n * {@link @nhtio/adk!SpooledArtifact} when the extracted text is large and lives in a consumer\n * {@link @nhtio/adk!ByteStore} (persist it via {@link @nhtio/adk!DispatchContext.storeRetrievableBytes}, wrap\n * the returned reader in a `SpooledArtifact`, and pass it here). Reader-backed content keeps the\n * body out of the permanent heap, but token estimation and render still materialise it\n * transiently (see {@link Retrievable.estimateTokens}).\n */\n content: string | Tokenizable | SpooledArtifact\n /**\n * Trust tier declared by the retrieval middleware at construction time. Required — there is\n * NO default. The decision must be conscious. See {@link RetrievableTrustTier}.\n */\n trustTier: RetrievableTrustTier\n /** Optional provenance string: URL, document path, knowledge-base id, etc. */\n source?: string\n /** Optional semantic label: 'policy' | 'reference' | 'web-page' | 'pdf' | etc. */\n kind?: string\n /** Optional relevance / similarity score in `[0, 1]` from the retrieval middleware. */\n score?: number\n /** When the source record was created (publication date, upload date, etc.). */\n createdAt: string | number | Date | DateTime\n /** When the source record was last modified. */\n updatedAt: string | number | Date | DateTime\n}\n\n/**\n * A fully-resolved {@link RawRetrievable} where all fields have been validated and temporal\n * values normalised to Luxon `DateTime` instances.\n */\ninterface ResolvedRetrievable {\n id: string\n content: Tokenizable | SpooledArtifact\n trustTier: RetrievableTrustTier\n source?: string\n kind?: string\n score?: number\n createdAt: DateTime\n updatedAt: DateTime\n}\n\n/**\n * Validator schema used to validate a {@link RawRetrievable} before constructing a\n * {@link Retrievable}.\n *\n * @remarks\n * - `id` — required non-empty string.\n * - `content` — required {@link @nhtio/adk!Tokenizable.schema}.\n * - `trustTier` — required, one of `'first-party'`, `'third-party-public'`,\n * `'third-party-private'`. Unknown / missing values reject.\n * - `source` / `kind` — optional strings.\n * - `score` — optional number in `[0, 1]`.\n * - `createdAt` / `updatedAt` — required datetime-parseable values.\n *\n * Throws {@link @nhtio/adk/exceptions!E_INVALID_INITIAL_RETRIEVABLE_VALUE} (via the {@link Retrievable} constructor)\n * when validation fails.\n */\nconst contentSchema = validator.alternatives(\n validator.string(),\n validator.custom((value, helpers) => {\n if (Tokenizable.isTokenizable(value) || SpooledArtifact.isSpooledArtifact(value)) {\n return value\n }\n return helpers.error('any.invalid')\n })\n)\n\nconst rawRetrievableSchema = validator.object<RawRetrievable>({\n id: validator.string().required(),\n content: contentSchema.required(),\n trustTier: validator\n .string()\n .valid('first-party', 'third-party-public', 'third-party-private')\n .required(),\n source: validator.string().optional(),\n kind: validator.string().optional(),\n score: validator.number().min(0).max(1).optional(),\n createdAt: validator.datetime().required(),\n updatedAt: validator.datetime().required(),\n})\n\n/**\n * An immutable, validated retrieved record (RAG content) held by the agent.\n *\n * @remarks\n * Peer of {@link @nhtio/adk!Memory} / `Message` / `Thought` / `ToolCall`. Carries an explicit `trustTier`\n * that LLM batteries branch on to choose the rendering envelope. The retrieval middleware that\n * produced the record is the only party that knows its provenance — batteries MUST NOT\n * auto-classify or infer the tier from `source`.\n */\nexport class Retrievable {\n /**\n * Validator schema that accepts a {@link RawRetrievable} object.\n *\n * @remarks\n * Reusable fragment for any schema that needs to validate or nest a retrievable record.\n */\n public static schema = rawRetrievableSchema\n\n /**\n * Returns `true` if `value` is a {@link Retrievable} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n */\n public static isRetrievable(value: unknown): value is Retrievable {\n return isInstanceOf(value, 'Retrievable', Retrievable)\n }\n\n /** Stable unique identifier for this retrieved record. */\n declare readonly id: string\n /**\n * The retrieved content: a {@link @nhtio/adk!Tokenizable} (inline text) or a\n * {@link @nhtio/adk!SpooledArtifact} (reader-backed, large text living in a consumer store). Use\n * {@link Retrievable.estimateTokens} for budgeting and {@link Retrievable.contentString} to\n * materialise the body at render time.\n */\n declare readonly content: Tokenizable | SpooledArtifact\n /** Trust tier declared by the retrieval middleware. */\n declare readonly trustTier: RetrievableTrustTier\n /** Optional provenance string. */\n declare readonly source: string | undefined\n /** Optional semantic label. */\n declare readonly kind: string | undefined\n /** Optional relevance / similarity score in `[0, 1]`. */\n declare readonly score: number | undefined\n /** When the source record was created. */\n declare readonly createdAt: DateTime\n /** When the source record was last modified. */\n declare readonly updatedAt: DateTime\n\n #id: string\n #content: Tokenizable | SpooledArtifact\n #trustTier: RetrievableTrustTier\n #source: string | undefined\n #kind: string | undefined\n #score: number | undefined\n #createdAt: DateTime\n #updatedAt: DateTime\n\n /**\n * @param raw - The raw retrievable input validated against `rawRetrievableSchema`.\n * @throws {@link @nhtio/adk/exceptions!E_INVALID_INITIAL_RETRIEVABLE_VALUE} when `raw` does not satisfy the schema.\n */\n constructor(raw: RawRetrievable) {\n let resolved: ResolvedRetrievable\n try {\n resolved = validateOrThrow<ResolvedRetrievable>(rawRetrievableSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_RETRIEVABLE_VALUE({ cause: isError(err) ? err : undefined })\n }\n this.#id = resolved.id\n this.#content =\n Tokenizable.isTokenizable(resolved.content) ||\n SpooledArtifact.isSpooledArtifact(resolved.content)\n ? resolved.content\n : new Tokenizable(resolved.content)\n this.#trustTier = resolved.trustTier\n this.#source = resolved.source\n this.#kind = resolved.kind\n this.#score = resolved.score\n this.#createdAt = resolved.createdAt\n this.#updatedAt = resolved.updatedAt\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n content: {\n get: () => this.#content,\n enumerable: true,\n configurable: false,\n },\n trustTier: {\n get: () => this.#trustTier,\n enumerable: true,\n configurable: false,\n },\n source: {\n get: () => this.#source,\n enumerable: true,\n configurable: false,\n },\n kind: {\n get: () => this.#kind,\n enumerable: true,\n configurable: false,\n },\n score: {\n get: () => this.#score,\n enumerable: true,\n configurable: false,\n },\n createdAt: {\n get: () => this.#createdAt,\n enumerable: true,\n configurable: false,\n },\n updatedAt: {\n get: () => this.#updatedAt,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Estimates the token count of the content under `encoding`.\n *\n * @remarks\n * Delegates to the content's own `estimateTokens`: synchronous for a {@link @nhtio/adk!Tokenizable}\n * (returns `number`), asynchronous for a {@link @nhtio/adk!SpooledArtifact} (returns\n * `Promise<number>`, reading the bytes from the backing store on demand). Both shapes satisfy the\n * adapter's token-budget path, which already awaits estimates.\n *\n * Note: the `SpooledArtifact` branch materialises the full decoded string transiently to count\n * tokens — reader-backing keeps the body off the *permanent* heap, but does not eliminate the\n * transient allocation at budgeting time.\n *\n * @param encoding - The encoding identifier to use for counting.\n * @returns The estimated token count.\n */\n estimateTokens(encoding: TokenEncoding): number | Promise<number> {\n return this.#content.estimateTokens(encoding)\n }\n\n /**\n * Returns the content body as a single string.\n *\n * @remarks\n * For a {@link @nhtio/adk!Tokenizable} this is synchronous in effect (resolved immediately); for a\n * {@link @nhtio/adk!SpooledArtifact} it reads the full body from the backing store via\n * {@link @nhtio/adk!SpooledArtifact.asString}. Always returns a `Promise` so callers have one\n * code path; render helpers `await` it at the point the trust-tier envelope is built.\n *\n * @returns The full content body as a string.\n */\n async contentString(): Promise<string> {\n return SpooledArtifact.isSpooledArtifact(this.#content)\n ? this.#content.asString()\n : this.#content.toString()\n }\n}\n","import { validator } from '@nhtio/validation'\nimport { passesSchema } from '../utils/validation'\nimport type { SpoolReader } from './spool_reader'\nimport type { MediaReader } from './media_reader'\n\n/**\n * Unified \"give bytes, get a reader\" persistence contract.\n *\n * @remarks\n * For the purposes of storage there is no meaningful distinction between text and binary — bytes\n * are bytes. `ByteStore` is the single low-level shape every ADK storage layer implements: hand it\n * bytes under an `id`, get back a replayable reader `R`; read or delete by the same `id` later. The\n * generic `R` is the reader the store hands out — different reader contracts (line-indexed\n * {@link @nhtio/adk!SpoolReader} vs binary-streamed {@link @nhtio/adk!MediaReader}) are\n * distinguished by the `R` instantiation, not by separate store interfaces. See the {@link SpoolStore}\n * and {@link MediaStore} aliases for the two concrete semantics.\n *\n * `write` accepts a `string`, a `Uint8Array`, or a `ReadableStream<Uint8Array>`. The stream form is\n * the point of the contract: a durable store can persist an arbitrarily large payload straight to\n * disk/object storage without first materializing it in memory. **String input is encoded as\n * UTF-8.** The returned reader is only guaranteed readable once the `write` result has resolved.\n *\n * All three methods may be synchronous or asynchronous so that in-memory implementations are not\n * forced to pay promise overhead while I/O-backed implementations stay async. Note that any\n * implementation accepting a `ReadableStream` must return a `Promise` for that input — draining a\n * stream cannot be synchronous.\n */\nexport interface ByteStore<R> {\n /**\n * Persists `bytes` under `id` and returns a reader over them.\n *\n * @remarks\n * Re-writing the same `id` replaces the prior entry. `string` input is encoded as UTF-8;\n * `Uint8Array` and `ReadableStream<Uint8Array>` are stored byte-faithfully. Stream input\n * necessarily resolves asynchronously.\n *\n * @param id - Identifier used to retrieve or delete the bytes later.\n * @param bytes - The payload, as a `string`, `Uint8Array`, or `ReadableStream<Uint8Array>`.\n * @returns A reader over the stored bytes (or a `Promise` of one).\n */\n write(id: string, bytes: string | Uint8Array | ReadableStream<Uint8Array>): R | Promise<R>\n\n /**\n * Returns a reader over the bytes previously written under `id`, or `undefined` if no entry\n * exists.\n *\n * @param id - Identifier supplied to a prior {@link ByteStore.write} call.\n * @returns A reader over the stored bytes, `undefined`, or a `Promise` of either.\n */\n read(id: string): R | undefined | Promise<R | undefined>\n\n /**\n * Removes the entry under `id`.\n *\n * @param id - Identifier whose entry should be removed.\n * @returns `true` if an entry existed and was removed; `false` otherwise (or a `Promise` of one).\n */\n delete(id: string): boolean | Promise<boolean>\n}\n\n/**\n * A {@link ByteStore} that hands out line-indexed text readers ({@link @nhtio/adk!SpoolReader}).\n *\n * @remarks\n * The store backing tool-output artifacts. Stored bytes are decoded as UTF-8 text for line-oriented\n * reads; binary input is stored byte-faithfully but `SpoolReader.readAll()` interprets it as text,\n * so opaque binary belongs in a {@link MediaStore} / `Media`, not here.\n */\nexport type SpoolStore = ByteStore<SpoolReader>\n\n/**\n * A {@link ByteStore} that hands out binary-streamed readers ({@link @nhtio/adk!MediaReader}).\n *\n * @remarks\n * The store backing persisted media bytes. Stored bytes are opaque and replayable via\n * `MediaReader.stream()`; no text decoding is implied.\n */\nexport type MediaStore = ByteStore<MediaReader>\n\n/**\n * Validator schema used to validate a {@link ByteStore} value.\n *\n * @remarks\n * Because `ByteStore` is a structural interface with no associated constructor, validation is\n * duck-typed: the value must be non-null with `write`, `read`, and `delete` present as callable\n * properties. Arity is not enforced — implementations may add optional parameters beyond the\n * contract. The reader type `R` cannot be checked structurally here; conformance of the reader is\n * the caller's concern at the point of use.\n */\nexport const byteStoreSchema = validator.any().custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).write === 'function' &&\n typeof (value as any).read === 'function' &&\n typeof (value as any).delete === 'function'\n ) {\n return value\n }\n return helpers.error('any.invalid')\n})\n\n/**\n * Returns `true` if `value` implements the {@link ByteStore} interface.\n *\n * @remarks\n * Duck-typed: checks that `value` is non-null with `write`, `read`, and `delete` as callable\n * functions. Does not use `instanceof` — there is no `ByteStore` constructor.\n *\n * @param value - The value to test.\n * @returns `true` when `value` conforms to the {@link ByteStore} interface.\n */\nexport const implementsByteStore = <R = unknown>(value: unknown): value is ByteStore<R> => {\n return passesSchema(byteStoreSchema, value)\n}\n","import type { MediaReader } from '../contracts/media_reader'\n\n/**\n * Constructs a {@link @nhtio/adk!MediaReader} backed by an in-memory `Uint8Array`.\n *\n * @remarks\n * Each `stream()` call returns a fresh single-chunk `ReadableStream` over the same buffer. The\n * reader is re-openable by construction — call `stream()` as many times as needed.\n *\n * @param bytes - The buffer to serve.\n * @returns A {@link @nhtio/adk!MediaReader} that re-reads `bytes` on every call.\n */\nexport const inMemoryMediaReader = (bytes: Uint8Array): MediaReader => {\n return {\n stream(): ReadableStream<Uint8Array> {\n return new ReadableStream<Uint8Array>({\n start(controller) {\n controller.enqueue(bytes)\n controller.close()\n },\n })\n },\n byteLength(): number {\n return bytes.byteLength\n },\n }\n}\n\n/**\n * Constructs a {@link @nhtio/adk!MediaReader} backed by a fetch call.\n *\n * @remarks\n * Each `stream()` call re-issues the fetch. Tool authors whose underlying source is rate-limited\n * or expensive must cache locally before constructing the reader — the framework cannot make\n * that decision for them.\n *\n * `byteLength()` returns `undefined` because most remote sources do not promise it without an\n * extra HEAD request; consumers that need a byte size should resolve it out-of-band.\n *\n * @param url - The URL to fetch on each call.\n * @param init - Optional `fetch` init forwarded verbatim.\n * @returns A {@link @nhtio/adk!MediaReader} that re-issues `fetch(url, init)` on every call.\n */\nexport const fromFetch = (url: string | URL, init?: RequestInit): MediaReader => {\n return {\n async stream(): Promise<ReadableStream<Uint8Array>> {\n const response = await fetch(url, init)\n if (!response.ok) {\n throw new Error(`fromFetch: fetch failed with status ${response.status}`)\n }\n if (!response.body) {\n throw new Error('fromFetch: response has no body')\n }\n return response.body as ReadableStream<Uint8Array>\n },\n byteLength(): undefined {\n return undefined\n },\n }\n}\n\n/**\n * Constructs a {@link @nhtio/adk!MediaReader} backed by a browser `File` or `Blob`.\n *\n * @remarks\n * Each `stream()` call re-streams the underlying File via `File.stream()`. `byteLength()`\n * resolves from `file.size`.\n *\n * @param file - The browser `File` or `Blob` to stream.\n * @returns A {@link @nhtio/adk!MediaReader} that re-streams `file` on every call.\n */\nexport const fromWebFile = (file: Blob): MediaReader => {\n return {\n stream(): ReadableStream<Uint8Array> {\n return file.stream() as ReadableStream<Uint8Array>\n },\n byteLength(): number {\n return file.size\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAoGA,IAAM,gBAAgB,UAAU,aAC9B,UAAU,OAAO,GACjB,UAAU,QAAQ,OAAO,YAAY;CACnC,IAAI,YAAY,cAAc,KAAK,KAAK,gBAAgB,kBAAkB,KAAK,GAC7E,OAAO;CAET,OAAO,QAAQ,MAAM,aAAa;AACpC,CAAC,CACH;AAEA,IAAM,uBAAuB,UAAU,OAAuB;CAC5D,IAAI,UAAU,OAAO,EAAE,SAAS;CAChC,SAAS,cAAc,SAAS;CAChC,WAAW,UACR,OAAO,EACP,MAAM,eAAe,sBAAsB,qBAAqB,EAChE,SAAS;CACZ,QAAQ,UAAU,OAAO,EAAE,SAAS;CACpC,MAAM,UAAU,OAAO,EAAE,SAAS;CAClC,OAAO,UAAU,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,CAAC,EAAE,SAAS;CACjD,WAAW,UAAU,SAAS,EAAE,SAAS;CACzC,WAAW,UAAU,SAAS,EAAE,SAAS;AAC3C,CAAC;;;;;;;;;;AAWD,IAAa,cAAb,MAAa,YAAY;;;;;;;CAOvB,OAAc,SAAS;;;;;;;CAQvB,OAAc,cAAc,OAAsC;EAChE,OAAO,aAAa,OAAO,eAAe,WAAW;CACvD;CAwBA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;;;;;CAMA,YAAY,KAAqB;EAC/B,IAAI;EACJ,IAAI;GACF,WAAW,gBAAqC,sBAAsB,KAAK,IAAI;EACjF,SAAS,KAAK;GACZ,MAAM,IAAI,oCAAoC,EAAE,OAAO,QAAQ,GAAG,IAAI,MAAM,KAAA,EAAU,CA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