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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/batteries/embeddings/index.d.ts +25 -0
  3. package/batteries/embeddings/openai/adapter.cjs +185 -0
  4. package/batteries/embeddings/openai/adapter.cjs.map +1 -0
  5. package/batteries/embeddings/openai/adapter.d.ts +74 -0
  6. package/batteries/embeddings/openai/adapter.mjs +183 -0
  7. package/batteries/embeddings/openai/adapter.mjs.map +1 -0
  8. package/batteries/embeddings/openai/exceptions.cjs +48 -0
  9. package/batteries/embeddings/openai/exceptions.cjs.map +1 -0
  10. package/batteries/embeddings/openai/exceptions.d.ts +45 -0
  11. package/batteries/embeddings/openai/exceptions.mjs +43 -0
  12. package/batteries/embeddings/openai/exceptions.mjs.map +1 -0
  13. package/batteries/embeddings/openai/helpers.cjs +25 -0
  14. package/batteries/embeddings/openai/helpers.cjs.map +1 -0
  15. package/batteries/embeddings/openai/helpers.d.ts +25 -0
  16. package/batteries/embeddings/openai/helpers.mjs +23 -0
  17. package/batteries/embeddings/openai/helpers.mjs.map +1 -0
  18. package/batteries/embeddings/openai/index.d.ts +17 -0
  19. package/batteries/embeddings/openai/types.cjs +2 -0
  20. package/batteries/embeddings/openai/types.d.ts +123 -0
  21. package/batteries/embeddings/openai/types.mjs +0 -0
  22. package/batteries/embeddings/openai/validation.cjs +56 -0
  23. package/batteries/embeddings/openai/validation.cjs.map +1 -0
  24. package/batteries/embeddings/openai/validation.d.ts +24 -0
  25. package/batteries/embeddings/openai/validation.mjs +53 -0
  26. package/batteries/embeddings/openai/validation.mjs.map +1 -0
  27. package/batteries/embeddings/openai.cjs +14 -0
  28. package/batteries/embeddings/openai.mjs +5 -0
  29. package/batteries/embeddings/webllm/adapter.cjs +147 -0
  30. package/batteries/embeddings/webllm/adapter.cjs.map +1 -0
  31. package/batteries/embeddings/webllm/adapter.d.ts +74 -0
  32. package/batteries/embeddings/webllm/adapter.mjs +145 -0
  33. package/batteries/embeddings/webllm/adapter.mjs.map +1 -0
  34. package/batteries/embeddings/webllm/exceptions.cjs +31 -0
  35. package/batteries/embeddings/webllm/exceptions.cjs.map +1 -0
  36. package/batteries/embeddings/webllm/exceptions.d.ts +25 -0
  37. package/batteries/embeddings/webllm/exceptions.mjs +28 -0
  38. package/batteries/embeddings/webllm/exceptions.mjs.map +1 -0
  39. package/batteries/embeddings/webllm/index.d.ts +15 -0
  40. package/batteries/embeddings/webllm/types.cjs +2 -0
  41. package/batteries/embeddings/webllm/types.d.ts +52 -0
  42. package/batteries/embeddings/webllm/types.mjs +0 -0
  43. package/batteries/embeddings/webllm/validation.cjs +43 -0
  44. package/batteries/embeddings/webllm/validation.cjs.map +1 -0
  45. package/batteries/embeddings/webllm/validation.d.ts +25 -0
  46. package/batteries/embeddings/webllm/validation.mjs +40 -0
  47. package/batteries/embeddings/webllm/validation.mjs.map +1 -0
  48. package/batteries/embeddings/webllm.cjs +10 -0
  49. package/batteries/embeddings/webllm.mjs +4 -0
  50. package/batteries/embeddings.cjs +15 -0
  51. package/batteries/embeddings.mjs +6 -0
  52. package/batteries/index.d.ts +1 -0
  53. package/batteries/llm/openai_chat_completions/adapter.cjs +14 -73
  54. package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -1
  55. package/batteries/llm/openai_chat_completions/adapter.mjs +8 -67
  56. package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -1
  57. package/batteries/llm/openai_chat_completions/helpers.cjs +2 -2
  58. package/batteries/llm/openai_chat_completions/helpers.mjs +2 -2
  59. package/batteries/llm/openai_chat_completions/validation.cjs +1 -1
  60. package/batteries/llm/openai_chat_completions/validation.mjs +1 -1
  61. package/batteries/llm/webllm_chat_completions/adapter.cjs +7 -6
  62. package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -1
  63. package/batteries/llm/webllm_chat_completions/adapter.mjs +7 -6
  64. package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -1
  65. package/batteries/llm/webllm_chat_completions/validation.cjs +1 -1
  66. package/batteries/llm/webllm_chat_completions/validation.mjs +1 -1
  67. package/batteries/storage/flydrive.cjs +1 -1
  68. package/batteries/storage/flydrive.mjs +1 -1
  69. package/batteries/storage/in_memory.cjs +1 -1
  70. package/batteries/storage/in_memory.mjs +1 -1
  71. package/batteries/storage/opfs.cjs +1 -1
  72. package/batteries/storage/opfs.mjs +1 -1
  73. package/batteries/tools/color.cjs +2 -2
  74. package/batteries/tools/color.mjs +2 -2
  75. package/batteries/tools/comparison.cjs +3 -3
  76. package/batteries/tools/comparison.mjs +3 -3
  77. package/batteries/tools/data_structure.cjs +3 -3
  78. package/batteries/tools/data_structure.mjs +3 -3
  79. package/batteries/tools/datetime_extended.cjs +2 -2
  80. package/batteries/tools/datetime_extended.mjs +2 -2
  81. package/batteries/tools/datetime_math.cjs +2 -2
  82. package/batteries/tools/datetime_math.mjs +2 -2
  83. package/batteries/tools/encoding.cjs +3 -3
  84. package/batteries/tools/encoding.mjs +3 -3
  85. package/batteries/tools/formatting.cjs +3 -3
  86. package/batteries/tools/formatting.mjs +3 -3
  87. package/batteries/tools/geo_basics.cjs +2 -2
  88. package/batteries/tools/geo_basics.mjs +2 -2
  89. package/batteries/tools/math.cjs +3 -3
  90. package/batteries/tools/math.mjs +3 -3
  91. package/batteries/tools/memory.cjs +5 -5
  92. package/batteries/tools/memory.mjs +5 -5
  93. package/batteries/tools/parsing.cjs +4 -4
  94. package/batteries/tools/parsing.mjs +4 -4
  95. package/batteries/tools/retrievables.cjs +4 -4
  96. package/batteries/tools/retrievables.mjs +4 -4
  97. package/batteries/tools/standing_instructions.cjs +4 -4
  98. package/batteries/tools/standing_instructions.mjs +4 -4
  99. package/batteries/tools/statistics.cjs +4 -4
  100. package/batteries/tools/statistics.mjs +4 -4
  101. package/batteries/tools/string_processing.cjs +3 -3
  102. package/batteries/tools/string_processing.mjs +3 -3
  103. package/batteries/tools/structured_data.cjs +3 -3
  104. package/batteries/tools/structured_data.mjs +3 -3
  105. package/batteries/tools/text_analysis.cjs +3 -3
  106. package/batteries/tools/text_analysis.mjs +3 -3
  107. package/batteries/tools/text_comparison.cjs +2 -2
  108. package/batteries/tools/text_comparison.mjs +2 -2
  109. package/batteries/tools/time.cjs +2 -2
  110. package/batteries/tools/time.mjs +2 -2
  111. package/batteries/tools/unit_conversion.cjs +2 -2
  112. package/batteries/tools/unit_conversion.mjs +2 -2
  113. package/batteries.cjs +13 -0
  114. package/batteries.mjs +8 -3
  115. package/{common-DuKWGTVd.js → common-D_e5zYsG.js} +8 -8
  116. package/{common-DuKWGTVd.js.map → common-D_e5zYsG.js.map} +1 -1
  117. package/{common-ClCHam5-.mjs → common-lMrnzoyn.mjs} +8 -8
  118. package/{common-ClCHam5-.mjs.map → common-lMrnzoyn.mjs.map} +1 -1
  119. package/common.cjs +7 -7
  120. package/common.mjs +7 -7
  121. package/{dispatch_runner-uNtS-XSP.mjs → dispatch_runner-CDF3X0nv.mjs} +3 -3
  122. package/{dispatch_runner-uNtS-XSP.mjs.map → dispatch_runner-CDF3X0nv.mjs.map} +1 -1
  123. package/{dispatch_runner-CEFHXRJZ.js → dispatch_runner-CpuyATj1.js} +3 -3
  124. package/{dispatch_runner-CEFHXRJZ.js.map → dispatch_runner-CpuyATj1.js.map} +1 -1
  125. package/dispatch_runner.cjs +1 -1
  126. package/dispatch_runner.mjs +1 -1
  127. package/exceptions.cjs +1 -1
  128. package/exceptions.mjs +1 -1
  129. package/forge.cjs +4 -4
  130. package/forge.mjs +4 -4
  131. package/guards.cjs +8 -8
  132. package/guards.mjs +8 -8
  133. package/index.cjs +12 -12
  134. package/index.mjs +12 -12
  135. package/lib/exceptions/runtime.d.ts +5 -0
  136. package/lib/utils/retry.cjs +107 -0
  137. package/lib/utils/retry.cjs.map +1 -0
  138. package/lib/utils/retry.d.ts +63 -0
  139. package/lib/utils/retry.mjs +102 -0
  140. package/lib/utils/retry.mjs.map +1 -0
  141. package/mcp/adk-docs-corpus.json +1 -1
  142. package/package.json +138 -73
  143. package/{runtime-DyD9oQjH.js → runtime-MFFcJrRv.js} +6 -2
  144. package/runtime-MFFcJrRv.js.map +1 -0
  145. package/{runtime-CDIZwCT0.mjs → runtime-j92CNi5z.mjs} +6 -2
  146. package/runtime-j92CNi5z.mjs.map +1 -0
  147. package/skills/adk-assembly/SKILL.md +2 -2
  148. package/{spooled_artifact-CHvDDYGA.js → spooled_artifact-B8gIIn9h.js} +4 -4
  149. package/{spooled_artifact-CHvDDYGA.js.map → spooled_artifact-B8gIIn9h.js.map} +1 -1
  150. package/{spooled_artifact-D-JrpY4W.mjs → spooled_artifact-CWoKUDEm.mjs} +4 -4
  151. package/{spooled_artifact-D-JrpY4W.mjs.map → spooled_artifact-CWoKUDEm.mjs.map} +1 -1
  152. package/spooled_artifact.cjs +2 -2
  153. package/spooled_artifact.mjs +2 -2
  154. package/{spooled_markdown_artifact-B4eWOfCX.mjs → spooled_markdown_artifact-CNle4jXN.mjs} +3 -3
  155. package/{spooled_markdown_artifact-B4eWOfCX.mjs.map → spooled_markdown_artifact-CNle4jXN.mjs.map} +1 -1
  156. package/{spooled_markdown_artifact-BYfPqFvk.js → spooled_markdown_artifact-DQX0RCdI.js} +3 -3
  157. package/{spooled_markdown_artifact-BYfPqFvk.js.map → spooled_markdown_artifact-DQX0RCdI.js.map} +1 -1
  158. package/{thought-DBNsR6l8.js → thought-BD6AkkOr.js} +4 -4
  159. package/{thought-DBNsR6l8.js.map → thought-BD6AkkOr.js.map} +1 -1
  160. package/{thought-D9IS11b5.mjs → thought-B_P8LiB6.mjs} +4 -4
  161. package/{thought-D9IS11b5.mjs.map → thought-B_P8LiB6.mjs.map} +1 -1
  162. package/{tool-CsYuHhiS.mjs → tool-CRZSUcdP.mjs} +3 -3
  163. package/{tool-CsYuHhiS.mjs.map → tool-CRZSUcdP.mjs.map} +1 -1
  164. package/{tool-DIHzOZiV.js → tool-CX9vNHAw.js} +3 -3
  165. package/{tool-DIHzOZiV.js.map → tool-CX9vNHAw.js.map} +1 -1
  166. package/{tool_call-CkOVOhg0.js → tool_call--7ti-frB.js} +4 -4
  167. package/{tool_call-CkOVOhg0.js.map → tool_call--7ti-frB.js.map} +1 -1
  168. package/{tool_call-Bs_Q5LOG.mjs → tool_call-BUeMuCc6.mjs} +4 -4
  169. package/{tool_call-Bs_Q5LOG.mjs.map → tool_call-BUeMuCc6.mjs.map} +1 -1
  170. package/{tool_registry-CX3ofUh9.mjs → tool_registry-BGHg6KTq.mjs} +2 -2
  171. package/{tool_registry-CX3ofUh9.mjs.map → tool_registry-BGHg6KTq.mjs.map} +1 -1
  172. package/{tool_registry-CKk5ooxm.js → tool_registry-CtCQ4Xoz.js} +2 -2
  173. package/{tool_registry-CKk5ooxm.js.map → tool_registry-CtCQ4Xoz.js.map} +1 -1
  174. package/{turn_runner-D0qGIrRI.js → turn_runner-BJTtAORU.js} +7 -6
  175. package/turn_runner-BJTtAORU.js.map +1 -0
  176. package/{turn_runner-C1-mup84.mjs → turn_runner-C02LZHjt.mjs} +8 -7
  177. package/turn_runner-C02LZHjt.mjs.map +1 -0
  178. package/turn_runner.cjs +1 -1
  179. package/turn_runner.mjs +1 -1
  180. package/runtime-CDIZwCT0.mjs.map +0 -1
  181. package/runtime-DyD9oQjH.js.map +0 -1
  182. package/turn_runner-C1-mup84.mjs.map +0 -1
  183. package/turn_runner-D0qGIrRI.js.map +0 -1
@@ -1,9 +1,9 @@
1
1
  require("./chunk-Ble4zEEl.js");
2
2
  const require_exceptions = require("./exceptions-CitH5wZI.js");
3
- const require_tool_registry = require("./tool_registry-CKk5ooxm.js");
4
- const require_runtime = require("./runtime-DyD9oQjH.js");
5
- const require_tool = require("./tool-DIHzOZiV.js");
6
- const require_dispatch_runner = require("./dispatch_runner-CEFHXRJZ.js");
3
+ const require_tool_registry = require("./tool_registry-CtCQ4Xoz.js");
4
+ const require_runtime = require("./runtime-MFFcJrRv.js");
5
+ const require_tool = require("./tool-CX9vNHAw.js");
6
+ const require_dispatch_runner = require("./dispatch_runner-CpuyATj1.js");
7
7
  let _nhtio_validation = require("@nhtio/validation");
8
8
  let luxon = require("luxon");
9
9
  let _nhtio_middleware = require("@nhtio/middleware");
@@ -338,7 +338,8 @@ var TurnRunner = class TurnRunner {
338
338
  * @throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} when `config` does not satisfy the schema.
339
339
  */
340
340
  constructor(config) {
341
- if (!require_exceptions.passesSchema(turnRunnerConfigSchema, config)) throw new require_runtime.E_INVALID_TURN_RUNNER_CONFIG();
341
+ const { error } = turnRunnerConfigSchema.validate(config, { abortEarly: false });
342
+ if (error) throw new require_runtime.E_INVALID_TURN_RUNNER_CONFIG([error.details.map((d) => d.message).join("; ")], { cause: error });
342
343
  this.#config = require_exceptions.validateOrThrow(turnRunnerConfigSchema, config, true);
343
344
  const turnInputPipeline = new _nhtio_middleware.Middleware();
344
345
  const turnOutputPipeline = new _nhtio_middleware.Middleware();
@@ -616,4 +617,4 @@ Object.defineProperty(exports, "TurnRunner", {
616
617
  }
617
618
  });
618
619
 
619
- //# sourceMappingURL=turn_runner-D0qGIrRI.js.map
620
+ //# sourceMappingURL=turn_runner-BJTtAORU.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"turn_runner-BJTtAORU.js","names":["#id","#turnId","#reason","#payload","#createdAt","#settled","#schema","#controller","#promise","#resolve","#reject","#config","#inputRunner","#outputRunner","#functionalEmitter","#observabilityEmitter"],"sources":["../src/lib/classes/turn_gate.ts","../src/lib/contracts/turn_runner_config.ts","../src/lib/turn_runner.ts"],"sourcesContent":["import { DateTime } from 'luxon'\nimport { validator } from '@nhtio/validation'\nimport { validateOrThrow } from '../utils/validation'\nimport { isInstanceOf, isError, isObject } from '../utils/guards'\nimport {\n E_TURN_GATE_ABORTED,\n E_TURN_GATE_TIMEOUT,\n E_INVALID_TURN_GATE_RESOLUTION,\n E_INVALID_INITIAL_TURN_GATE_VALUE,\n} from '../exceptions/runtime'\nimport type { Schema } from '@nhtio/validation'\n\n/**\n * Plain input object supplied to {@link TurnGate} at construction time.\n *\n * @remarks\n * `turnId` and `abortSignal` are injected by the runner — callers constructing a gate via\n * `ctx.waitFor()` never supply them directly.\n *\n * `abortSignal` is `AbortSignal` (not `AbortController`) because the gate reacts to turn-level\n * cancellation but cannot trigger it. The gate owns its own internal `AbortController` for\n * `gate.abort()`.\n */\nexport interface RawTurnGate {\n /** Stable unique identifier for this gate. */\n id: string\n /** The ID of the turn that opened this gate. */\n turnId: string\n /** Human-readable label describing why this gate was opened (e.g. `'tool_approval'`). */\n reason: string\n /** Arbitrary data supplied to the gate opener; passed through to `turnGateOpen` listeners. */\n payload: unknown\n /** Optional validator schema for the resolution value. When present, `resolve()` validates before settling. */\n schema?: Schema\n /** Optional timeout in milliseconds. When elapsed the gate self-rejects with {@link @nhtio/adk!E_TURN_GATE_TIMEOUT}. */\n timeout?: number\n /** The turn's abort signal. When fired the gate self-rejects with {@link @nhtio/adk!E_TURN_GATE_ABORTED}. */\n abortSignal?: AbortSignal\n /** When this gate was created. */\n createdAt: string | number | Date | DateTime\n}\n\n/**\n * Fully-resolved {@link RawTurnGate} after schema validation.\n *\n * @internal\n */\ninterface ResolvedTurnGate {\n id: string\n turnId: string\n reason: string\n payload: unknown\n schema?: Schema\n timeout?: number\n abortSignal?: AbortSignal\n createdAt: DateTime\n}\n\n/**\n * Validator schema used to validate a {@link RawTurnGate} before constructing a {@link TurnGate}.\n *\n * @remarks\n * - `schema` and `abortSignal` are validated as opaque passthrough values.\n * - `timeout` must be a positive integer when provided.\n */\nconst rawTurnGateSchema = validator.object<RawTurnGate>({\n id: validator.string().required(),\n turnId: validator.string().required(),\n reason: validator.string().required(),\n payload: validator.any().required(),\n schema: validator\n .any()\n .custom((value, helpers) => {\n if (value === undefined || value === null) return undefined\n if (typeof (value as any).validate === 'function') return value\n return helpers.error('any.invalid')\n })\n .optional(),\n timeout: validator.number().integer().min(1).optional(),\n abortSignal: validator\n .any()\n .custom((value, helpers) => {\n if (value === undefined || value === null) return undefined\n // eslint-disable-next-line adk/use-is-instance-of -- native built-in; AbortSignal cross-realm is handled by the duck-type fallback below\n if (typeof AbortSignal !== 'undefined' && value instanceof AbortSignal) return value\n if (\n isObject(value) &&\n typeof (value as any).aborted === 'boolean' &&\n typeof (value as any).addEventListener === 'function'\n ) {\n return value\n }\n return helpers.error('any.invalid')\n })\n .optional(),\n createdAt: validator.datetime().required(),\n})\n\n/**\n * A cooperative suspension gate that blocks a turn's middleware pipeline until resolved, rejected,\n * aborted, or timed out.\n *\n * @typeParam T - The expected type of the resolution value.\n *\n * @remarks\n * Created exclusively via `ctx.waitFor()` — middleware never constructs a gate directly.\n * The gate emits `turnGateOpen` on the runner's observability bus at creation time and\n * `turnGateClosed` when it settles.\n *\n * Resolution is validated against an optional schema before the internal promise is settled.\n * A validation failure throws {@link @nhtio/adk!E_INVALID_TURN_GATE_RESOLUTION} **synchronously in the\n * caller's context** — the promise is NOT settled and the gate remains open.\n */\nexport class TurnGate<T = unknown> {\n /**\n * Validator schema that accepts a {@link RawTurnGate} object.\n *\n * @remarks\n * Reusable fragment for any schema that needs to validate or nest a gate entry.\n */\n public static schema = rawTurnGateSchema\n\n /**\n * Returns `true` if `value` is a {@link TurnGate} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link TurnGate} instance.\n */\n public static isTurnGate(value: unknown): value is TurnGate {\n return isInstanceOf(value, 'TurnGate', TurnGate)\n }\n\n declare readonly id: string\n declare readonly turnId: string\n declare readonly reason: string\n declare readonly payload: unknown\n declare readonly createdAt: DateTime\n declare readonly isSettled: boolean\n\n #id: string\n #turnId: string\n #reason: string\n #payload: unknown\n #createdAt: DateTime\n #settled: boolean\n #schema: Schema | undefined\n #controller: AbortController\n #resolve!: (value: T) => void\n #reject!: (reason: unknown) => void\n #promise: Promise<T>\n\n /**\n * @param raw - The raw gate input validated against `rawTurnGateSchema`.\n * @throws {@link @nhtio/adk!E_INVALID_INITIAL_TURN_GATE_VALUE} when `raw` does not satisfy the schema.\n */\n constructor(raw: RawTurnGate) {\n let resolved: ResolvedTurnGate\n try {\n resolved = validateOrThrow<ResolvedTurnGate>(rawTurnGateSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_TURN_GATE_VALUE({ cause: isError(err) ? err : undefined })\n }\n\n this.#id = resolved.id\n this.#turnId = resolved.turnId\n this.#reason = resolved.reason\n this.#payload = resolved.payload\n this.#createdAt = resolved.createdAt\n this.#settled = false\n this.#schema = resolved.schema\n this.#controller = new AbortController()\n\n this.#promise = new Promise<T>((resolve, reject) => {\n this.#resolve = resolve\n this.#reject = reject\n })\n\n // Wire the internal abort controller\n const onAbort = () => {\n if (!this.#settled) {\n this.#settled = true\n this.#reject(new E_TURN_GATE_ABORTED())\n }\n }\n\n this.#controller.signal.addEventListener('abort', onAbort, { once: true })\n\n // Wire the external turn abort signal\n if (resolved.abortSignal) {\n if (resolved.abortSignal.aborted) {\n // Already aborted — reject immediately after construction\n queueMicrotask(() => onAbort())\n } else {\n resolved.abortSignal.addEventListener('abort', onAbort, { once: true })\n // Clean up the external listener once the gate settles via another path\n this.#promise.then(\n () => resolved.abortSignal!.removeEventListener('abort', onAbort),\n () => resolved.abortSignal!.removeEventListener('abort', onAbort)\n )\n }\n }\n\n // Wire the timeout\n if (resolved.timeout !== undefined) {\n const timer = setTimeout(() => {\n if (!this.#settled) {\n this.#settled = true\n this.#reject(new E_TURN_GATE_TIMEOUT())\n }\n }, resolved.timeout)\n\n this.#promise.then(\n () => clearTimeout(timer),\n () => clearTimeout(timer)\n )\n }\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n turnId: {\n get: () => this.#turnId,\n enumerable: true,\n configurable: false,\n },\n reason: {\n get: () => this.#reason,\n enumerable: true,\n configurable: false,\n },\n payload: {\n get: () => this.#payload,\n enumerable: true,\n configurable: false,\n },\n createdAt: {\n get: () => this.#createdAt,\n enumerable: true,\n configurable: false,\n },\n isSettled: {\n get: () => this.#settled,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Resolves the gate with `value`, unblocking the awaiting middleware.\n *\n * @remarks\n * If a schema was provided at construction, `value` is validated synchronously before the\n * promise is settled. A validation failure throws {@link @nhtio/adk!E_INVALID_TURN_GATE_RESOLUTION}\n * in the caller's context — the promise is NOT settled and the gate remains open.\n *\n * No-ops if the gate is already settled.\n *\n * @param value - The resolution value. Must satisfy the gate's schema when one was provided.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_GATE_RESOLUTION} when `value` fails schema validation.\n */\n resolve(value: unknown): void {\n if (this.#settled) return\n if (this.#schema !== undefined) {\n try {\n value = validateOrThrow(this.#schema, value, true)\n } catch (err) {\n throw new E_INVALID_TURN_GATE_RESOLUTION({\n cause: isError(err) ? err : undefined,\n })\n }\n }\n this.#settled = true\n this.#resolve(value as T)\n }\n\n /**\n * Rejects the gate with `error`, unblocking the awaiting middleware with a rejection.\n *\n * @remarks\n * No-ops if the gate is already settled.\n *\n * @param error - The rejection reason.\n */\n reject(error: Error): void {\n if (this.#settled) return\n this.#settled = true\n this.#reject(error)\n }\n\n /**\n * Aborts the gate by firing the internal `AbortController`, which rejects the promise with\n * {@link @nhtio/adk!E_TURN_GATE_ABORTED}.\n *\n * @remarks\n * No-ops if the gate is already settled. Distinct from the turn-level abort signal — this\n * allows callers to cancel a specific gate without aborting the whole turn.\n */\n abort(): void {\n if (this.#settled) return\n this.#controller.abort()\n }\n\n /**\n * Returns the internal promise. Called by `ctx.waitFor()` to block the middleware pipeline.\n *\n * @internal\n */\n _promise(): Promise<T> {\n return this.#promise\n }\n}\n","import { Tool } from '../classes/tool'\nimport { validator } from '@nhtio/validation'\nimport type { TurnPipelineMiddlewareFn } from '../types/turn_runner'\nimport type { DispatchPipelineMiddlewareFn, DispatchExecutorFn } from '../types/dispatch_runner'\nimport type {\n MemoryRetrievalFn,\n MessageRetrievalFn,\n ThoughtRetrievalFn,\n ToolCallRetrievalFn,\n ToolsRetrievalFn,\n StandingInstructionsRefreshFn,\n StandingInstructionStoreFn,\n StandingInstructionMutateFn,\n StandingInstructionDeleteFn,\n MemoryStoreFn,\n MemoryMutateFn,\n MemoryDeleteFn,\n RetrievableRetrievalFn,\n RetrievableStoreFn,\n RetrievableMutateFn,\n RetrievableDeleteFn,\n MessageStoreFn,\n MessageMutateFn,\n MessageDeleteFn,\n ThoughtStoreFn,\n ThoughtMutateFn,\n ThoughtDeleteFn,\n ToolCallStoreFn,\n ToolCallMutateFn,\n ToolCallDeleteFn,\n MediaBytesStoreFn,\n RetrievableBytesStoreFn,\n} from './turn_runner_context'\n\n/**\n * Configuration supplied to {@link @nhtio/adk!TurnRunner} at construction time.\n *\n * @remarks\n * Validated against `turnRunnerConfigSchema` at construction — a misconfigured runner throws\n * immediately rather than failing on the first turn.\n *\n * All fetch and mutation callbacks are required: they are injected into each {@link @nhtio/adk!TurnContext}\n * so middleware can call fetch, refresh, and persistence methods directly on the context without\n * coupling to the runner.\n *\n * `tools` is optional at the caller level and defaults to `[]` after schema resolution — a runner\n * with no baseline tools is valid.\n */\nexport interface TurnRunnerConfig {\n /** Performs the LLM API/SDK call for each iteration of the dispatch loop; receives the active {@link @nhtio/adk!DispatchContext} and an {@link @nhtio/adk!DispatchExecutorHelpers} object for managing per-id stream state. */\n executorCallback: DispatchExecutorFn\n /** Called once per turn to supply memories; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchMemoriesCallback: MemoryRetrievalFn\n /** Called once per turn to supply conversation history; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchMessagesCallback: MessageRetrievalFn\n /** Called once per turn to supply thought traces; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchThoughtsCallback: ThoughtRetrievalFn\n /** Called once per turn to supply tool call records; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchToolCallsCallback: ToolCallRetrievalFn\n /** Called to supply available tools; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchToolsCallback: ToolsRetrievalFn\n /** Called to refresh and return standing instructions; receives the active {@link @nhtio/adk!TurnContext}. */\n refreshStandingInstructionsCallback: StandingInstructionsRefreshFn\n /** Persists a new standing instruction. */\n storeStandingInstructionCallback: StandingInstructionStoreFn\n /** Updates an existing standing instruction in the persistence layer. */\n mutateStandingInstructionCallback: StandingInstructionMutateFn\n /** Removes a standing instruction from the persistence layer. */\n deleteStandingInstructionCallback: StandingInstructionDeleteFn\n /** Persists a new memory. */\n storeMemoryCallback: MemoryStoreFn\n /** Updates an existing memory in the persistence layer. */\n mutateMemoryCallback: MemoryMutateFn\n /** Removes a memory from the persistence layer by ID. */\n deleteMemoryCallback: MemoryDeleteFn\n /** Called once per turn to supply retrievable (RAG) records; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchRetrievablesCallback: RetrievableRetrievalFn\n /** Persists a new retrievable record. */\n storeRetrievableCallback: RetrievableStoreFn\n /** Updates an existing retrievable record in the persistence layer. */\n mutateRetrievableCallback: RetrievableMutateFn\n /** Removes a retrievable record from the persistence layer by ID. */\n deleteRetrievableCallback: RetrievableDeleteFn\n /** Persists a new message. */\n storeMessageCallback: MessageStoreFn\n /** Updates an existing message in the persistence layer. */\n mutateMessageCallback: MessageMutateFn\n /** Removes a message from the persistence layer by ID. */\n deleteMessageCallback: MessageDeleteFn\n /** Persists a new thought. */\n storeThoughtCallback: ThoughtStoreFn\n /** Updates an existing thought in the persistence layer. */\n mutateThoughtCallback: ThoughtMutateFn\n /** Removes a thought from the persistence layer by ID. */\n deleteThoughtCallback: ThoughtDeleteFn\n /** Persists a new tool call. */\n storeToolCallCallback: ToolCallStoreFn\n /** Updates an existing tool call in the persistence layer. */\n mutateToolCallCallback: ToolCallMutateFn\n /** Removes a tool call from the persistence layer by ID. */\n deleteToolCallCallback: ToolCallDeleteFn\n /** Persists tool-generated media bytes into consumer storage; returns a `MediaReader`. */\n storeMediaBytesCallback: MediaBytesStoreFn\n /** Persists extracted retrievable text bytes into consumer storage; returns a `SpoolReader`. */\n storeRetrievableBytesCallback: RetrievableBytesStoreFn\n /** Baseline tools available on every turn. Middleware may trim or extend this per-turn via `ctx.tools`. Defaults to `[]`. */\n tools?: Tool[]\n /** Turn-level input middleware, executed in order against the {@link @nhtio/adk!TurnContext} before the LLM dispatch. Defaults to `[]`. */\n turnInputPipeline?: TurnPipelineMiddlewareFn[]\n /** Turn-level output middleware, executed in order against the {@link @nhtio/adk!TurnContext} after the LLM dispatch resolves successfully. Defaults to `[]`. */\n turnOutputPipeline?: TurnPipelineMiddlewareFn[]\n /** LLM-iteration input middleware, executed in order against the {@link @nhtio/adk!DispatchContext} before the executor on each iteration. Defaults to `[]`. */\n dispatchInputPipeline?: DispatchPipelineMiddlewareFn[]\n /** LLM-iteration output middleware, executed in order against the {@link @nhtio/adk!DispatchContext} after the executor on each iteration. Defaults to `[]`. */\n dispatchOutputPipeline?: DispatchPipelineMiddlewareFn[]\n}\n\n/**\n * Fully-resolved {@link TurnRunnerConfig} after schema validation.\n *\n * @remarks\n * All optional fields are guaranteed present (e.g. `tools` defaults to `[]`). The runner stores\n * this type internally so field access never needs to guard for undefined.\n */\nexport type ResolvedTurnRunnerConfig = Required<TurnRunnerConfig>\n\n/**\n * Validator schema used to validate a {@link TurnRunnerConfig} at {@link @nhtio/adk!TurnRunner} construction time.\n *\n * @remarks\n * Validates that all callbacks are functions of the correct arity, and that `tools` — when\n * provided — is an array of valid {@link @nhtio/adk!Tool} instances. Defaults `tools` to `[]`.\n *\n * Throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} (via the {@link @nhtio/adk!TurnRunner} constructor) when\n * validation fails.\n */\nexport const turnRunnerConfigSchema = validator.object<TurnRunnerConfig>({\n executorCallback: validator.function().required(),\n fetchMemoriesCallback: validator.function().arity(1).required(),\n fetchMessagesCallback: validator.function().arity(1).required(),\n fetchThoughtsCallback: validator.function().arity(1).required(),\n fetchToolCallsCallback: validator.function().arity(1).required(),\n fetchToolsCallback: validator.function().arity(1).required(),\n refreshStandingInstructionsCallback: validator.function().arity(1).required(),\n storeStandingInstructionCallback: validator.function().arity(2).required(),\n mutateStandingInstructionCallback: validator.function().arity(2).required(),\n deleteStandingInstructionCallback: validator.function().arity(2).required(),\n storeMemoryCallback: validator.function().arity(2).required(),\n mutateMemoryCallback: validator.function().arity(2).required(),\n deleteMemoryCallback: validator.function().arity(2).required(),\n fetchRetrievablesCallback: validator.function().arity(1).required(),\n storeRetrievableCallback: validator.function().arity(2).required(),\n mutateRetrievableCallback: validator.function().arity(2).required(),\n deleteRetrievableCallback: validator.function().arity(2).required(),\n storeMessageCallback: validator.function().arity(2).required(),\n mutateMessageCallback: validator.function().arity(2).required(),\n deleteMessageCallback: validator.function().arity(2).required(),\n storeThoughtCallback: validator.function().arity(2).required(),\n mutateThoughtCallback: validator.function().arity(2).required(),\n deleteThoughtCallback: validator.function().arity(2).required(),\n storeToolCallCallback: validator.function().arity(2).required(),\n mutateToolCallCallback: validator.function().arity(2).required(),\n deleteToolCallCallback: validator.function().arity(2).required(),\n storeMediaBytesCallback: validator.function().arity(3).required(),\n storeRetrievableBytesCallback: validator.function().arity(3).required(),\n tools: validator\n .array()\n .items(\n validator.any().custom((value: unknown, helpers: { error: (code: string) => unknown }) => {\n if (Tool.isTool(value)) return value\n return helpers.error('any.invalid')\n })\n )\n .default([]),\n turnInputPipeline: validator.array().items(validator.function()).default([]),\n turnOutputPipeline: validator.array().items(validator.function()).default([]),\n dispatchInputPipeline: validator.array().items(validator.function()).default([]),\n dispatchOutputPipeline: validator.array().items(validator.function()).default([]),\n})\n","import { DateTime } from 'luxon'\nimport { Middleware } from '@nhtio/middleware'\nimport { TurnGate } from './classes/turn_gate'\nimport { DispatchRunner } from './dispatch_runner'\nimport { validateOrThrow } from './utils/validation'\nimport { ToolRegistry } from './classes/tool_registry'\nimport { isInstanceOf, isError } from './utils/guards'\nimport { TypedEventEmitter } from '@nhtio/tiny-typed-emitter'\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 // Validate once, capturing the field-level error so the thrown exception can name the\n // offending field(s) (e.g. a missing required callback) instead of failing opaquely.\n const { error } = turnRunnerConfigSchema.validate(config, { abortEarly: false })\n if (error) {\n const detail = error.details.map((d) => d.message).join('; ')\n throw new E_INVALID_TURN_RUNNER_CONFIG([detail], { cause: error })\n }\n // Store the resolved config so optional fields (e.g. tools) are always present.\n this.#config = validateOrThrow<ResolvedTurnRunnerConfig>(turnRunnerConfigSchema, config, true)\n const turnInputPipeline = new Middleware<TurnPipelineMiddlewareFn>()\n const turnOutputPipeline = new Middleware<TurnPipelineMiddlewareFn>()\n const wrap =\n (fn: TurnPipelineMiddlewareFn): TurnPipelineMiddlewareFn =>\n (ctx, next) => {\n // Skip downstream user middlewares once an abort has been signalled. The\n // wrapper still calls next() so the pipeline reaches its terminal resolver\n // (keeping the short-circuit detector quiet); the original middleware body\n // does not run, so it has nothing to clean up.\n if (ctx.aborted) return next()\n return fn(ctx, next)\n }\n for (const fn of this.#config.turnInputPipeline) turnInputPipeline.add(wrap(fn))\n for (const fn of this.#config.turnOutputPipeline) turnOutputPipeline.add(wrap(fn))\n this.#inputRunner = turnInputPipeline.runner()\n this.#outputRunner = turnOutputPipeline.runner()\n this.#functionalEmitter = new TypedEventEmitter<TurnEvents>()\n this.#observabilityEmitter = new TypedEventEmitter<TurnObservabilityEvents>()\n }\n\n // ── Functional bus ───────────────────────────────────────────────────────\n\n /**\n * Removes a previously registered functional listener for `event`.\n *\n * @param event - The event to stop listening to.\n * @param listener - The listener function to remove.\n * @returns `this` for chaining.\n */\n off<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.off(event, listener)\n return this\n }\n\n /**\n * Registers a persistent functional listener for `event`.\n *\n * @param event - The event to listen to.\n * @param listener - The function to call on each emission.\n * @returns `this` for chaining.\n */\n on<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.on(event, listener)\n return this\n }\n\n /**\n * Registers a one-time functional listener for `event` that is automatically removed after the\n * first emission.\n *\n * @param event - The event to listen to.\n * @param listener - The function to call on the next emission.\n * @returns `this` for chaining.\n */\n once<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.once(event, listener)\n return this\n }\n\n // ── Observability bus ────────────────────────────────────────────────────\n\n /**\n * Removes a previously registered observability listener for `event`.\n *\n * @param event - The event to stop observing.\n * @param listener - The listener function to remove.\n * @returns `this` for chaining.\n */\n unobserve<K>(\n event: TurnObservabilityEvent<K>,\n listener: TurnObservabilityEventListener<K>\n ): this {\n this.#observabilityEmitter.off(event, listener)\n return this\n }\n\n /**\n * Registers a persistent observability listener for `event`.\n *\n * @remarks\n * Use the observability bus (`observe` / `unobserve` / `observeOnce`) for instrumentation:\n * turn lifecycle, gate lifecycle, and non-fatal errors. Use the functional bus (`on` / `off` /\n * `once`) for pipeline-affecting events: `message`, `thought`, `toolCall`.\n *\n * @param event - The event to observe.\n * @param listener - The function to call on each emission.\n * @returns `this` for chaining.\n */\n observe<K>(event: TurnObservabilityEvent<K>, listener: TurnObservabilityEventListener<K>): this {\n this.#observabilityEmitter.on(event, listener)\n return this\n }\n\n /**\n * Registers a one-time observability listener for `event` that is automatically removed after\n * the first emission.\n *\n * @param event - The event to observe once.\n * @param listener - The function to call on the next emission.\n * @returns `this` for chaining.\n */\n observeOnce<K>(\n event: TurnObservabilityEvent<K>,\n listener: TurnObservabilityEventListener<K>\n ): this {\n this.#observabilityEmitter.once(event, listener)\n return this\n }\n\n // ── Turn execution ───────────────────────────────────────────────────────\n\n /**\n * Executes a single agent turn against the provided raw context.\n *\n * @remarks\n * Returns `Promise<void>` intentionally — all meaningful output surfaces via events, not return\n * values. Register listeners before calling `run`: observability events (`turnStart`, `turnEnd`)\n * bracket execution; functional events (`message`, `thought`, `toolCall`) fire throughout;\n * observability `error` carries non-fatal pipeline failures; `turnGateOpen` and `turnGateClosed`\n * fire when middleware suspends via `ctx.waitFor()`. Awaiting this method only tells you the\n * pipeline has finished, not what it produced.\n *\n * Constructs a validated {@link @nhtio/adk!TurnContext} from `context` (throwing\n * {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} on failure), then runs the input middleware pipeline.\n * Abort signals are silently swallowed.\n *\n * @param context - Raw input validated and wrapped into a {@link @nhtio/adk!TurnContext} before execution.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} when `context` does not satisfy the schema.\n */\n async run(context: RawTurnContext): Promise<void> {\n const abortController = context.turnAbortController ?? new AbortController()\n\n // Forward declaration so openGate can reference turnContext.id before it is assigned.\n let turnContextId: string\n\n const openGate: OpenGateFn = <T>(raw: Omit<RawTurnGate, 'turnId' | 'abortSignal'>) => {\n const gate = new TurnGate<T>({\n ...raw,\n turnId: turnContextId,\n abortSignal: abortController.signal,\n })\n this.#observabilityEmitter.emit('turnGateOpen', gate)\n const promise = gate._promise()\n promise.then(\n () => {\n this.#observabilityEmitter.emit('turnGateClosed', {\n gateId: gate.id,\n turnId: gate.turnId,\n result: 'resolved',\n settledAt: DateTime.now(),\n })\n },\n (err: unknown) => {\n let result: 'rejected' | 'aborted' | 'timeout' = 'rejected'\n if (isInstanceOf(err, 'E_TURN_GATE_ABORTED')) result = 'aborted'\n else if (isInstanceOf(err, 'E_TURN_GATE_TIMEOUT')) result = 'timeout'\n this.#observabilityEmitter.emit('turnGateClosed', {\n gateId: gate.id,\n turnId: gate.turnId,\n result,\n settledAt: DateTime.now(),\n })\n }\n )\n return promise\n }\n\n const tools = new ToolRegistry(this.#config.tools)\n\n const turnContext = new TurnContext(\n { ...context, turnAbortController: abortController },\n {\n fetchMemories: this.#config.fetchMemoriesCallback,\n fetchMessages: this.#config.fetchMessagesCallback,\n fetchThoughts: this.#config.fetchThoughtsCallback,\n fetchToolCalls: this.#config.fetchToolCallsCallback,\n fetchTools: this.#config.fetchToolsCallback,\n refreshStandingInstructions: this.#config.refreshStandingInstructionsCallback,\n storeStandingInstruction: this.#config.storeStandingInstructionCallback,\n mutateStandingInstruction: this.#config.mutateStandingInstructionCallback,\n deleteStandingInstruction: this.#config.deleteStandingInstructionCallback,\n storeMemory: this.#config.storeMemoryCallback,\n mutateMemory: this.#config.mutateMemoryCallback,\n deleteMemory: this.#config.deleteMemoryCallback,\n fetchRetrievables: this.#config.fetchRetrievablesCallback,\n storeRetrievable: this.#config.storeRetrievableCallback,\n mutateRetrievable: this.#config.mutateRetrievableCallback,\n deleteRetrievable: this.#config.deleteRetrievableCallback,\n storeMessage: this.#config.storeMessageCallback,\n mutateMessage: this.#config.mutateMessageCallback,\n deleteMessage: this.#config.deleteMessageCallback,\n storeThought: this.#config.storeThoughtCallback,\n mutateThought: this.#config.mutateThoughtCallback,\n deleteThought: this.#config.deleteThoughtCallback,\n storeToolCall: this.#config.storeToolCallCallback,\n mutateToolCall: this.#config.mutateToolCallCallback,\n deleteToolCall: this.#config.deleteToolCallCallback,\n storeMediaBytes: this.#config.storeMediaBytesCallback,\n storeRetrievableBytes: this.#config.storeRetrievableBytesCallback,\n emitMessage: (content) => this.#functionalEmitter.emit('message', content),\n emitThought: (content) => this.#functionalEmitter.emit('thought', content),\n emitToolCall: (content) => this.#functionalEmitter.emit('toolCall', content),\n emitToolExecutionStart: (event) =>\n this.#observabilityEmitter.emit('toolExecutionStart', event),\n emitToolExecutionEnd: (event) => this.#observabilityEmitter.emit('toolExecutionEnd', event),\n openGate,\n tools,\n }\n )\n\n turnContextId = turnContext.id\n\n const startedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnStart', { turnId: turnContext.id, startedAt })\n\n const emitTurnEnd = () => {\n const endedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnEnd', {\n turnId: turnContext.id,\n startedAt,\n endedAt,\n durationMs: endedAt.diff(startedAt).milliseconds,\n })\n }\n\n // 1. Input pipeline\n let inputFailed = false\n let inputReached = false\n await this.#inputRunner\n .errorHandler(async (error) => {\n if (!isError(error) || !isInstanceOf(error, 'AbortError')) {\n inputFailed = true\n const err = new E_INPUT_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n this.#observabilityEmitter.emit('error', err)\n }\n })\n .finalHandler(async () => {\n inputReached = true\n })\n .run((fn, next) => Promise.resolve(fn(turnContext, next)))\n\n if (!inputReached && !inputFailed && !turnContext.aborted) {\n inputFailed = true\n const err = new E_PIPELINE_SHORT_CIRCUITED(['turn-input'])\n this.#observabilityEmitter.emit('error', err)\n }\n\n if (inputFailed || turnContext.aborted) {\n emitTurnEnd()\n return\n }\n\n // 2. LLM execution dispatch\n let dispatchFailed = false\n try {\n await DispatchRunner.dispatch({\n source: turnContext,\n executor: this.#config.executorCallback,\n turnInputPipeline: this.#config.dispatchInputPipeline,\n turnOutputPipeline: this.#config.dispatchOutputPipeline,\n observers: {\n dispatchStart: [\n (e) => {\n this.#observabilityEmitter.emit('dispatchStart', e)\n },\n ],\n dispatchEnd: [\n (e) => {\n this.#observabilityEmitter.emit('dispatchEnd', e)\n },\n ],\n iterationStart: [\n (e) => {\n this.#observabilityEmitter.emit('iterationStart', e)\n },\n ],\n iterationEnd: [\n (e) => {\n this.#observabilityEmitter.emit('iterationEnd', e)\n },\n ],\n log: [\n (e) => {\n this.#observabilityEmitter.emit('log', e)\n },\n ],\n },\n })\n } catch (err) {\n dispatchFailed = true\n const wrapped = isInstanceOf(err, 'BaseException') ? (err as InstanceType<typeof Error>) : err\n this.#observabilityEmitter.emit('error', wrapped as any)\n }\n\n if (dispatchFailed || turnContext.aborted) {\n emitTurnEnd()\n return\n }\n\n // 3. Output pipeline\n let outputFailed = false\n let outputReached = false\n await this.#outputRunner\n .errorHandler(async (error) => {\n if (!isError(error) || !isInstanceOf(error, 'AbortError')) {\n outputFailed = true\n const err = new E_OUTPUT_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n this.#observabilityEmitter.emit('error', err)\n }\n })\n .finalHandler(async () => {\n outputReached = true\n })\n .run((fn, next) => Promise.resolve(fn(turnContext, next)))\n\n if (!outputReached && !outputFailed && !turnContext.aborted) {\n const err = new E_PIPELINE_SHORT_CIRCUITED(['turn-output'])\n this.#observabilityEmitter.emit('error', err)\n }\n\n emitTurnEnd()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiEA,IAAM,oBAAoB,kBAAA,UAAU,OAAoB;CACtD,IAAI,kBAAA,UAAU,OAAO,EAAE,SAAS;CAChC,QAAQ,kBAAA,UAAU,OAAO,EAAE,SAAS;CACpC,QAAQ,kBAAA,UAAU,OAAO,EAAE,SAAS;CACpC,SAAS,kBAAA,UAAU,IAAI,EAAE,SAAS;CAClC,QAAQ,kBAAA,UACL,IAAI,EACJ,QAAQ,OAAO,YAAY;EAC1B,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,KAAA;EAClD,IAAI,OAAQ,MAAc,aAAa,YAAY,OAAO;EAC1D,OAAO,QAAQ,MAAM,aAAa;CACpC,CAAC,EACA,SAAS;CACZ,SAAS,kBAAA,UAAU,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE,SAAS;CACtD,aAAa,kBAAA,UACV,IAAI,EACJ,QAAQ,OAAO,YAAY;EAC1B,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,KAAA;EAElD,IAAI,OAAO,gBAAgB,eAAe,iBAAiB,aAAa,OAAO;EAC/E,IACE,sBAAA,SAAS,KAAK,KACd,OAAQ,MAAc,YAAY,aAClC,OAAQ,MAAc,qBAAqB,YAE3C,OAAO;EAET,OAAO,QAAQ,MAAM,aAAa;CACpC,CAAC,EACA,SAAS;CACZ,WAAW,kBAAA,UAAU,SAAS,EAAE,SAAS;AAC3C,CAAC;;;;;;;;;;;;;;;;AAiBD,IAAa,WAAb,MAAa,SAAsB;;;;;;;CAOjC,OAAc,SAAS;;;;;;;;;;CAWvB,OAAc,WAAW,OAAmC;EAC1D,OAAO,sBAAA,aAAa,OAAO,YAAY,QAAQ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,SAAS,OAAc;EACzD;EAEA,IAAI,kBAAkB,YAAY,SAAS;GACzC,YAAY;GACZ;EACF;EAGA,IAAI,eAAe;EACnB,IAAI,gBAAgB;EACpB,MAAM,KAAKF,cACR,aAAa,OAAO,UAAU;GAC7B,IAAI,CAAC,sBAAA,QAAQ,KAAK,KAAK,CAAC,sBAAA,aAAa,OAAO,YAAY,GAAG;IACzD,eAAe;IACf,MAAM,MAAM,IAAI,gBAAA,wBAAwB,EACtC,OAAO,sBAAA,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,gBAAA,2BAA2B,CAAC,aAAa,CAAC;GAC1D,KAAKA,sBAAsB,KAAK,SAAS,GAAG;EAC9C;EAEA,YAAY;CACd;AACF"}
@@ -1,8 +1,8 @@
1
- import { a as validateOrThrow, i as passesSchema } from "./exceptions-BeWH2FwP.mjs";
2
- import { c as isObject, o as isError, s as isInstanceOf, t as ToolRegistry } from "./tool_registry-CX3ofUh9.mjs";
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-CDIZwCT0.mjs";
4
- import { t as Tool } from "./tool-CsYuHhiS.mjs";
5
- import { r as TurnContext, t as DispatchRunner } from "./dispatch_runner-uNtS-XSP.mjs";
1
+ import { a as validateOrThrow } from "./exceptions-BeWH2FwP.mjs";
2
+ import { c as isObject, o as isError, s as isInstanceOf, t as ToolRegistry } from "./tool_registry-BGHg6KTq.mjs";
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-j92CNi5z.mjs";
4
+ import { t as Tool } from "./tool-CRZSUcdP.mjs";
5
+ import { r as TurnContext, t as DispatchRunner } from "./dispatch_runner-CDF3X0nv.mjs";
6
6
  import { validator } from "@nhtio/validation";
7
7
  import { DateTime } from "luxon";
8
8
  import { Middleware } from "@nhtio/middleware";
@@ -337,7 +337,8 @@ var TurnRunner = class TurnRunner {
337
337
  * @throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} when `config` does not satisfy the schema.
338
338
  */
339
339
  constructor(config) {
340
- if (!passesSchema(turnRunnerConfigSchema, config)) throw new E_INVALID_TURN_RUNNER_CONFIG();
340
+ const { error } = turnRunnerConfigSchema.validate(config, { abortEarly: false });
341
+ if (error) throw new E_INVALID_TURN_RUNNER_CONFIG([error.details.map((d) => d.message).join("; ")], { cause: error });
341
342
  this.#config = validateOrThrow(turnRunnerConfigSchema, config, true);
342
343
  const turnInputPipeline = new Middleware();
343
344
  const turnOutputPipeline = new Middleware();
@@ -604,4 +605,4 @@ var TurnRunner = class TurnRunner {
604
605
  //#endregion
605
606
  export { TurnGate as n, TurnRunner as t };
606
607
 
607
- //# sourceMappingURL=turn_runner-C1-mup84.mjs.map
608
+ //# sourceMappingURL=turn_runner-C02LZHjt.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"turn_runner-C02LZHjt.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 MediaBytesStoreFn,\n RetrievableBytesStoreFn,\n} from './turn_runner_context'\n\n/**\n * Configuration supplied to {@link @nhtio/adk!TurnRunner} at construction time.\n *\n * @remarks\n * Validated against `turnRunnerConfigSchema` at construction — a misconfigured runner throws\n * immediately rather than failing on the first turn.\n *\n * All fetch and mutation callbacks are required: they are injected into each {@link @nhtio/adk!TurnContext}\n * so middleware can call fetch, refresh, and persistence methods directly on the context without\n * coupling to the runner.\n *\n * `tools` is optional at the caller level and defaults to `[]` after schema resolution — a runner\n * with no baseline tools is valid.\n */\nexport interface TurnRunnerConfig {\n /** Performs the LLM API/SDK call for each iteration of the dispatch loop; receives the active {@link @nhtio/adk!DispatchContext} and an {@link @nhtio/adk!DispatchExecutorHelpers} object for managing per-id stream state. */\n executorCallback: DispatchExecutorFn\n /** Called once per turn to supply memories; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchMemoriesCallback: MemoryRetrievalFn\n /** Called once per turn to supply conversation history; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchMessagesCallback: MessageRetrievalFn\n /** Called once per turn to supply thought traces; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchThoughtsCallback: ThoughtRetrievalFn\n /** Called once per turn to supply tool call records; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchToolCallsCallback: ToolCallRetrievalFn\n /** Called to supply available tools; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchToolsCallback: ToolsRetrievalFn\n /** Called to refresh and return standing instructions; receives the active {@link @nhtio/adk!TurnContext}. */\n refreshStandingInstructionsCallback: StandingInstructionsRefreshFn\n /** Persists a new standing instruction. */\n storeStandingInstructionCallback: StandingInstructionStoreFn\n /** Updates an existing standing instruction in the persistence layer. */\n mutateStandingInstructionCallback: StandingInstructionMutateFn\n /** Removes a standing instruction from the persistence layer. */\n deleteStandingInstructionCallback: StandingInstructionDeleteFn\n /** Persists a new memory. */\n storeMemoryCallback: MemoryStoreFn\n /** Updates an existing memory in the persistence layer. */\n mutateMemoryCallback: MemoryMutateFn\n /** Removes a memory from the persistence layer by ID. */\n deleteMemoryCallback: MemoryDeleteFn\n /** Called once per turn to supply retrievable (RAG) records; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchRetrievablesCallback: RetrievableRetrievalFn\n /** Persists a new retrievable record. */\n storeRetrievableCallback: RetrievableStoreFn\n /** Updates an existing retrievable record in the persistence layer. */\n mutateRetrievableCallback: RetrievableMutateFn\n /** Removes a retrievable record from the persistence layer by ID. */\n deleteRetrievableCallback: RetrievableDeleteFn\n /** Persists a new message. */\n storeMessageCallback: MessageStoreFn\n /** Updates an existing message in the persistence layer. */\n mutateMessageCallback: MessageMutateFn\n /** Removes a message from the persistence layer by ID. */\n deleteMessageCallback: MessageDeleteFn\n /** Persists a new thought. */\n storeThoughtCallback: ThoughtStoreFn\n /** Updates an existing thought in the persistence layer. */\n mutateThoughtCallback: ThoughtMutateFn\n /** Removes a thought from the persistence layer by ID. */\n deleteThoughtCallback: ThoughtDeleteFn\n /** Persists a new tool call. */\n storeToolCallCallback: ToolCallStoreFn\n /** Updates an existing tool call in the persistence layer. */\n mutateToolCallCallback: ToolCallMutateFn\n /** Removes a tool call from the persistence layer by ID. */\n deleteToolCallCallback: ToolCallDeleteFn\n /** Persists tool-generated media bytes into consumer storage; returns a `MediaReader`. */\n storeMediaBytesCallback: MediaBytesStoreFn\n /** Persists extracted retrievable text bytes into consumer storage; returns a `SpoolReader`. */\n storeRetrievableBytesCallback: RetrievableBytesStoreFn\n /** Baseline tools available on every turn. Middleware may trim or extend this per-turn via `ctx.tools`. Defaults to `[]`. */\n tools?: Tool[]\n /** Turn-level input middleware, executed in order against the {@link @nhtio/adk!TurnContext} before the LLM dispatch. Defaults to `[]`. */\n turnInputPipeline?: TurnPipelineMiddlewareFn[]\n /** Turn-level output middleware, executed in order against the {@link @nhtio/adk!TurnContext} after the LLM dispatch resolves successfully. Defaults to `[]`. */\n turnOutputPipeline?: TurnPipelineMiddlewareFn[]\n /** LLM-iteration input middleware, executed in order against the {@link @nhtio/adk!DispatchContext} before the executor on each iteration. Defaults to `[]`. */\n dispatchInputPipeline?: DispatchPipelineMiddlewareFn[]\n /** LLM-iteration output middleware, executed in order against the {@link @nhtio/adk!DispatchContext} after the executor on each iteration. Defaults to `[]`. */\n dispatchOutputPipeline?: DispatchPipelineMiddlewareFn[]\n}\n\n/**\n * Fully-resolved {@link TurnRunnerConfig} after schema validation.\n *\n * @remarks\n * All optional fields are guaranteed present (e.g. `tools` defaults to `[]`). The runner stores\n * this type internally so field access never needs to guard for undefined.\n */\nexport type ResolvedTurnRunnerConfig = Required<TurnRunnerConfig>\n\n/**\n * Validator schema used to validate a {@link TurnRunnerConfig} at {@link @nhtio/adk!TurnRunner} construction time.\n *\n * @remarks\n * Validates that all callbacks are functions of the correct arity, and that `tools` — when\n * provided — is an array of valid {@link @nhtio/adk!Tool} instances. Defaults `tools` to `[]`.\n *\n * Throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} (via the {@link @nhtio/adk!TurnRunner} constructor) when\n * validation fails.\n */\nexport const turnRunnerConfigSchema = validator.object<TurnRunnerConfig>({\n executorCallback: validator.function().required(),\n fetchMemoriesCallback: validator.function().arity(1).required(),\n fetchMessagesCallback: validator.function().arity(1).required(),\n fetchThoughtsCallback: validator.function().arity(1).required(),\n fetchToolCallsCallback: validator.function().arity(1).required(),\n fetchToolsCallback: validator.function().arity(1).required(),\n refreshStandingInstructionsCallback: validator.function().arity(1).required(),\n storeStandingInstructionCallback: validator.function().arity(2).required(),\n mutateStandingInstructionCallback: validator.function().arity(2).required(),\n deleteStandingInstructionCallback: validator.function().arity(2).required(),\n storeMemoryCallback: validator.function().arity(2).required(),\n mutateMemoryCallback: validator.function().arity(2).required(),\n deleteMemoryCallback: validator.function().arity(2).required(),\n fetchRetrievablesCallback: validator.function().arity(1).required(),\n storeRetrievableCallback: validator.function().arity(2).required(),\n mutateRetrievableCallback: validator.function().arity(2).required(),\n deleteRetrievableCallback: validator.function().arity(2).required(),\n storeMessageCallback: validator.function().arity(2).required(),\n mutateMessageCallback: validator.function().arity(2).required(),\n deleteMessageCallback: validator.function().arity(2).required(),\n storeThoughtCallback: validator.function().arity(2).required(),\n mutateThoughtCallback: validator.function().arity(2).required(),\n deleteThoughtCallback: validator.function().arity(2).required(),\n storeToolCallCallback: validator.function().arity(2).required(),\n mutateToolCallCallback: validator.function().arity(2).required(),\n deleteToolCallCallback: validator.function().arity(2).required(),\n storeMediaBytesCallback: validator.function().arity(3).required(),\n storeRetrievableBytesCallback: validator.function().arity(3).required(),\n tools: validator\n .array()\n .items(\n validator.any().custom((value: unknown, helpers: { error: (code: string) => unknown }) => {\n if (Tool.isTool(value)) return value\n return helpers.error('any.invalid')\n })\n )\n .default([]),\n turnInputPipeline: validator.array().items(validator.function()).default([]),\n turnOutputPipeline: validator.array().items(validator.function()).default([]),\n dispatchInputPipeline: validator.array().items(validator.function()).default([]),\n dispatchOutputPipeline: validator.array().items(validator.function()).default([]),\n})\n","import { DateTime } from 'luxon'\nimport { Middleware } from '@nhtio/middleware'\nimport { TurnGate } from './classes/turn_gate'\nimport { DispatchRunner } from './dispatch_runner'\nimport { validateOrThrow } from './utils/validation'\nimport { ToolRegistry } from './classes/tool_registry'\nimport { isInstanceOf, isError } from './utils/guards'\nimport { TypedEventEmitter } from '@nhtio/tiny-typed-emitter'\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 // Validate once, capturing the field-level error so the thrown exception can name the\n // offending field(s) (e.g. a missing required callback) instead of failing opaquely.\n const { error } = turnRunnerConfigSchema.validate(config, { abortEarly: false })\n if (error) {\n const detail = error.details.map((d) => d.message).join('; ')\n throw new E_INVALID_TURN_RUNNER_CONFIG([detail], { cause: error })\n }\n // Store the resolved config so optional fields (e.g. tools) are always present.\n this.#config = validateOrThrow<ResolvedTurnRunnerConfig>(turnRunnerConfigSchema, config, true)\n const turnInputPipeline = new Middleware<TurnPipelineMiddlewareFn>()\n const turnOutputPipeline = new Middleware<TurnPipelineMiddlewareFn>()\n const wrap =\n (fn: TurnPipelineMiddlewareFn): TurnPipelineMiddlewareFn =>\n (ctx, next) => {\n // Skip downstream user middlewares once an abort has been signalled. The\n // wrapper still calls next() so the pipeline reaches its terminal resolver\n // (keeping the short-circuit detector quiet); the original middleware body\n // does not run, so it has nothing to clean up.\n if (ctx.aborted) return next()\n return fn(ctx, next)\n }\n for (const fn of this.#config.turnInputPipeline) turnInputPipeline.add(wrap(fn))\n for (const fn of this.#config.turnOutputPipeline) turnOutputPipeline.add(wrap(fn))\n this.#inputRunner = turnInputPipeline.runner()\n this.#outputRunner = turnOutputPipeline.runner()\n this.#functionalEmitter = new TypedEventEmitter<TurnEvents>()\n this.#observabilityEmitter = new TypedEventEmitter<TurnObservabilityEvents>()\n }\n\n // ── Functional bus ───────────────────────────────────────────────────────\n\n /**\n * Removes a previously registered functional listener for `event`.\n *\n * @param event - The event to stop listening to.\n * @param listener - The listener function to remove.\n * @returns `this` for chaining.\n */\n off<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.off(event, listener)\n return this\n }\n\n /**\n * Registers a persistent functional listener for `event`.\n *\n * @param event - The event to listen to.\n * @param listener - The function to call on each emission.\n * @returns `this` for chaining.\n */\n on<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.on(event, listener)\n return this\n }\n\n /**\n * Registers a one-time functional listener for `event` that is automatically removed after the\n * first emission.\n *\n * @param event - The event to listen to.\n * @param listener - The function to call on the next emission.\n * @returns `this` for chaining.\n */\n once<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.once(event, listener)\n return this\n }\n\n // ── Observability bus ────────────────────────────────────────────────────\n\n /**\n * Removes a previously registered observability listener for `event`.\n *\n * @param event - The event to stop observing.\n * @param listener - The listener function to remove.\n * @returns `this` for chaining.\n */\n unobserve<K>(\n event: TurnObservabilityEvent<K>,\n listener: TurnObservabilityEventListener<K>\n ): this {\n this.#observabilityEmitter.off(event, listener)\n return this\n }\n\n /**\n * Registers a persistent observability listener for `event`.\n *\n * @remarks\n * Use the observability bus (`observe` / `unobserve` / `observeOnce`) for instrumentation:\n * turn lifecycle, gate lifecycle, and non-fatal errors. Use the functional bus (`on` / `off` /\n * `once`) for pipeline-affecting events: `message`, `thought`, `toolCall`.\n *\n * @param event - The event to observe.\n * @param listener - The function to call on each emission.\n * @returns `this` for chaining.\n */\n observe<K>(event: TurnObservabilityEvent<K>, listener: TurnObservabilityEventListener<K>): this {\n this.#observabilityEmitter.on(event, listener)\n return this\n }\n\n /**\n * Registers a one-time observability listener for `event` that is automatically removed after\n * the first emission.\n *\n * @param event - The event to observe once.\n * @param listener - The function to call on the next emission.\n * @returns `this` for chaining.\n */\n observeOnce<K>(\n event: TurnObservabilityEvent<K>,\n listener: TurnObservabilityEventListener<K>\n ): this {\n this.#observabilityEmitter.once(event, listener)\n return this\n }\n\n // ── Turn execution ───────────────────────────────────────────────────────\n\n /**\n * Executes a single agent turn against the provided raw context.\n *\n * @remarks\n * Returns `Promise<void>` intentionally — all meaningful output surfaces via events, not return\n * values. Register listeners before calling `run`: observability events (`turnStart`, `turnEnd`)\n * bracket execution; functional events (`message`, `thought`, `toolCall`) fire throughout;\n * observability `error` carries non-fatal pipeline failures; `turnGateOpen` and `turnGateClosed`\n * fire when middleware suspends via `ctx.waitFor()`. Awaiting this method only tells you the\n * pipeline has finished, not what it produced.\n *\n * Constructs a validated {@link @nhtio/adk!TurnContext} from `context` (throwing\n * {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} on failure), then runs the input middleware pipeline.\n * Abort signals are silently swallowed.\n *\n * @param context - Raw input validated and wrapped into a {@link @nhtio/adk!TurnContext} before execution.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} when `context` does not satisfy the schema.\n */\n async run(context: RawTurnContext): Promise<void> {\n const abortController = context.turnAbortController ?? new AbortController()\n\n // Forward declaration so openGate can reference turnContext.id before it is assigned.\n let turnContextId: string\n\n const openGate: OpenGateFn = <T>(raw: Omit<RawTurnGate, 'turnId' | 'abortSignal'>) => {\n const gate = new TurnGate<T>({\n ...raw,\n turnId: turnContextId,\n abortSignal: abortController.signal,\n })\n this.#observabilityEmitter.emit('turnGateOpen', gate)\n const promise = gate._promise()\n promise.then(\n () => {\n this.#observabilityEmitter.emit('turnGateClosed', {\n gateId: gate.id,\n turnId: gate.turnId,\n result: 'resolved',\n settledAt: DateTime.now(),\n })\n },\n (err: unknown) => {\n let result: 'rejected' | 'aborted' | 'timeout' = 'rejected'\n if (isInstanceOf(err, 'E_TURN_GATE_ABORTED')) result = 'aborted'\n else if (isInstanceOf(err, 'E_TURN_GATE_TIMEOUT')) result = 'timeout'\n this.#observabilityEmitter.emit('turnGateClosed', {\n gateId: gate.id,\n turnId: gate.turnId,\n result,\n settledAt: DateTime.now(),\n })\n }\n )\n return promise\n }\n\n const tools = new ToolRegistry(this.#config.tools)\n\n const turnContext = new TurnContext(\n { ...context, turnAbortController: abortController },\n {\n fetchMemories: this.#config.fetchMemoriesCallback,\n fetchMessages: this.#config.fetchMessagesCallback,\n fetchThoughts: this.#config.fetchThoughtsCallback,\n fetchToolCalls: this.#config.fetchToolCallsCallback,\n fetchTools: this.#config.fetchToolsCallback,\n refreshStandingInstructions: this.#config.refreshStandingInstructionsCallback,\n storeStandingInstruction: this.#config.storeStandingInstructionCallback,\n mutateStandingInstruction: this.#config.mutateStandingInstructionCallback,\n deleteStandingInstruction: this.#config.deleteStandingInstructionCallback,\n storeMemory: this.#config.storeMemoryCallback,\n mutateMemory: this.#config.mutateMemoryCallback,\n deleteMemory: this.#config.deleteMemoryCallback,\n fetchRetrievables: this.#config.fetchRetrievablesCallback,\n storeRetrievable: this.#config.storeRetrievableCallback,\n mutateRetrievable: this.#config.mutateRetrievableCallback,\n deleteRetrievable: this.#config.deleteRetrievableCallback,\n storeMessage: this.#config.storeMessageCallback,\n mutateMessage: this.#config.mutateMessageCallback,\n deleteMessage: this.#config.deleteMessageCallback,\n storeThought: this.#config.storeThoughtCallback,\n mutateThought: this.#config.mutateThoughtCallback,\n deleteThought: this.#config.deleteThoughtCallback,\n storeToolCall: this.#config.storeToolCallCallback,\n mutateToolCall: this.#config.mutateToolCallCallback,\n deleteToolCall: this.#config.deleteToolCallCallback,\n storeMediaBytes: this.#config.storeMediaBytesCallback,\n storeRetrievableBytes: this.#config.storeRetrievableBytesCallback,\n emitMessage: (content) => this.#functionalEmitter.emit('message', content),\n emitThought: (content) => this.#functionalEmitter.emit('thought', content),\n emitToolCall: (content) => this.#functionalEmitter.emit('toolCall', content),\n emitToolExecutionStart: (event) =>\n this.#observabilityEmitter.emit('toolExecutionStart', event),\n emitToolExecutionEnd: (event) => this.#observabilityEmitter.emit('toolExecutionEnd', event),\n openGate,\n tools,\n }\n )\n\n turnContextId = turnContext.id\n\n const startedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnStart', { turnId: turnContext.id, startedAt })\n\n const emitTurnEnd = () => {\n const endedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnEnd', {\n turnId: turnContext.id,\n startedAt,\n endedAt,\n durationMs: endedAt.diff(startedAt).milliseconds,\n })\n }\n\n // 1. Input pipeline\n let inputFailed = false\n let inputReached = false\n await this.#inputRunner\n .errorHandler(async (error) => {\n if (!isError(error) || !isInstanceOf(error, 'AbortError')) {\n inputFailed = true\n const err = new E_INPUT_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n this.#observabilityEmitter.emit('error', err)\n }\n })\n .finalHandler(async () => {\n inputReached = true\n })\n .run((fn, next) => Promise.resolve(fn(turnContext, next)))\n\n if (!inputReached && !inputFailed && !turnContext.aborted) {\n inputFailed = true\n const err = new E_PIPELINE_SHORT_CIRCUITED(['turn-input'])\n this.#observabilityEmitter.emit('error', err)\n }\n\n if (inputFailed || turnContext.aborted) {\n emitTurnEnd()\n return\n }\n\n // 2. LLM execution dispatch\n let dispatchFailed = false\n try {\n await DispatchRunner.dispatch({\n source: turnContext,\n executor: this.#config.executorCallback,\n turnInputPipeline: this.#config.dispatchInputPipeline,\n turnOutputPipeline: this.#config.dispatchOutputPipeline,\n observers: {\n dispatchStart: [\n (e) => {\n this.#observabilityEmitter.emit('dispatchStart', e)\n },\n ],\n dispatchEnd: [\n (e) => {\n this.#observabilityEmitter.emit('dispatchEnd', e)\n },\n ],\n iterationStart: [\n (e) => {\n this.#observabilityEmitter.emit('iterationStart', e)\n },\n ],\n iterationEnd: [\n (e) => {\n this.#observabilityEmitter.emit('iterationEnd', e)\n },\n ],\n log: [\n (e) => {\n this.#observabilityEmitter.emit('log', e)\n },\n ],\n },\n })\n } catch (err) {\n dispatchFailed = true\n const wrapped = isInstanceOf(err, 'BaseException') ? (err as InstanceType<typeof Error>) : err\n this.#observabilityEmitter.emit('error', wrapped as any)\n }\n\n if (dispatchFailed || turnContext.aborted) {\n emitTurnEnd()\n return\n }\n\n // 3. Output pipeline\n let outputFailed = false\n let outputReached = false\n await this.#outputRunner\n .errorHandler(async (error) => {\n if (!isError(error) || !isInstanceOf(error, 'AbortError')) {\n outputFailed = true\n const err = new E_OUTPUT_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n this.#observabilityEmitter.emit('error', err)\n }\n })\n .finalHandler(async () => {\n outputReached = true\n })\n .run((fn, next) => Promise.resolve(fn(turnContext, next)))\n\n if (!outputReached && !outputFailed && !turnContext.aborted) {\n const err = new E_PIPELINE_SHORT_CIRCUITED(['turn-output'])\n this.#observabilityEmitter.emit('error', err)\n }\n\n emitTurnEnd()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiEA,IAAM,oBAAoB,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,OAAQ,MAAc,aAAa,YAAY,OAAO;EAC1D,OAAO,QAAQ,MAAM,aAAa;CACpC,CAAC,EACA,SAAS;CACZ,SAAS,UAAU,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,EAAE,SAAS;CACtD,aAAa,UACV,IAAI,EACJ,QAAQ,OAAO,YAAY;EAC1B,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO,KAAA;EAElD,IAAI,OAAO,gBAAgB,eAAe,iBAAiB,aAAa,OAAO;EAC/E,IACE,SAAS,KAAK,KACd,OAAQ,MAAc,YAAY,aAClC,OAAQ,MAAc,qBAAqB,YAE3C,OAAO;EAET,OAAO,QAAQ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AAwB,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
@@ -1,4 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  require("./chunk-Ble4zEEl.js");
3
- const require_turn_runner = require("./turn_runner-D0qGIrRI.js");
3
+ const require_turn_runner = require("./turn_runner-BJTtAORU.js");
4
4
  exports.TurnRunner = require_turn_runner.TurnRunner;
package/turn_runner.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { t as TurnRunner } from "./turn_runner-C1-mup84.mjs";
1
+ import { t as TurnRunner } from "./turn_runner-C02LZHjt.mjs";
2
2
  export { TurnRunner };
@@ -1 +0,0 @@
1
- {"version":3,"file":"runtime-CDIZwCT0.mjs","names":[],"sources":["../src/lib/exceptions/runtime.ts"],"sourcesContent":["import { createException } from '../utils/exceptions'\n\n/**\n * Thrown by {@link @nhtio/adk!TurnRunner} when the supplied config object fails schema validation at\n * construction time.\n *\n * @remarks\n * Marked fatal — a misconfigured runner must not be allowed to execute turns.\n *\n * @group Turn Runner Construction\n */\nexport const E_INVALID_TURN_RUNNER_CONFIG = createException(\n 'E_INVALID_TURN_RUNNER_CONFIG',\n 'The turn runner cannot be instantiated with the provided configuration.',\n 'E_INVALID_TURN_RUNNER_CONFIG',\n 529,\n true\n)\n\n/**\n * Thrown by {@link @nhtio/adk!TurnRunner} when the {@link @nhtio/adk!TurnContext} supplied to `run` fails schema\n * validation.\n *\n * @remarks\n * Marked fatal — an invalid context indicates a programming error in the caller, not a\n * recoverable runtime condition. Thrown synchronously out of `run()` before `turnStart` is\n * emitted.\n *\n * @group Turn Input Validation\n */\nexport const E_INVALID_TURN_CONTEXT = createException(\n 'E_INVALID_TURN_CONTEXT',\n 'The turn runner received an invalid context object.',\n 'E_INVALID_TURN_CONTEXT',\n 529,\n true\n)\n\n/**\n * Emitted (via the `error` event) when a non-abort error propagates out of the input\n * middleware pipeline during {@link @nhtio/adk!TurnRunner.run}.\n *\n * @remarks\n * Not fatal — the turn runner emits this on the `error` event rather than throwing, so\n * registered listeners can handle or log the failure without crashing the pipeline. Dispatch\n * and output middleware are skipped; `turnEnd` still fires.\n *\n * @group Pipelines\n */\nexport const E_INPUT_PIPELINE_ERROR = createException(\n 'E_INPUT_PIPELINE_ERROR',\n 'An error occurred in the input pipeline.',\n 'E_INPUT_PIPELINE_ERROR',\n 500,\n false\n)\n\n/**\n * Emitted (via the `error` event) when a non-abort error propagates out of the output\n * middleware pipeline during {@link @nhtio/adk!TurnRunner.run}.\n *\n * @remarks\n * Not fatal — the turn runner emits this on the `error` event rather than throwing, so\n * registered listeners can handle or log the failure without crashing the pipeline. `turnEnd`\n * still fires.\n *\n * @group Pipelines\n */\nexport const E_OUTPUT_PIPELINE_ERROR = createException(\n 'E_OUTPUT_PIPELINE_ERROR',\n 'An error occurred in the output pipeline.',\n 'E_OUTPUT_PIPELINE_ERROR',\n 500,\n false\n)\n\n/**\n * Emitted (via the `error` event) when a middleware pipeline resolves without reaching its\n * terminal handler and without the turn being aborted. Indicates that some middleware\n * returned without calling `next` and without signalling a deliberate refusal via the turn's\n * abort controller.\n *\n * @remarks\n * Not fatal — the runner emits this on the `error` event so the failure is observable, then\n * proceeds to short-circuit the remainder of the turn the same way any other pipeline error\n * would. The constructor takes a single positional argument identifying the pipeline that\n * short-circuited: one of `'turn-input'`, `'turn-output'`, `'dispatch-input'`, or `'dispatch-output'`.\n *\n * Deliberate refusals should call `ctx.abort(reason)`, which sets the `'aborted'` outcome\n * instead of emitting this error.\n *\n * @warning\n * This is a **detection condition**, not a thrown exception. The runner constructs and emits\n * the code itself when it detects a missing `next()` on the unwind — nothing in user code\n * throws it. Upstream post-steps still run normally.\n *\n * @example\n * ```ts\n * throw new E_PIPELINE_SHORT_CIRCUITED(['turn-input'])\n * ```\n *\n * @group Pipelines\n */\nexport const E_PIPELINE_SHORT_CIRCUITED = createException<[string]>(\n 'E_PIPELINE_SHORT_CIRCUITED',\n \"The '%s' middleware pipeline short-circuited without calling next or aborting the turn.\",\n 'E_PIPELINE_SHORT_CIRCUITED',\n 500,\n false\n)\n\n/**\n * Thrown when a registry is initialised with a value that is defined but not a plain object.\n *\n * @remarks\n * Registries expect either `undefined` (empty start) or a plain object as their initial value.\n * Passing a primitive, array, class instance, or other non-object signals a programming error\n * in the caller.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_REGISTRY_VALUE = createException(\n 'E_INVALID_INITIAL_REGISTRY_VALUE',\n 'Attempted to initialize a registry with a defined non-object value.',\n 'E_INVALID_INITIAL_REGISTRY_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Memory} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Memory` requires all fields — `id`, `content`, `confidence`, `importance`, `createdAt`,\n * `updatedAt` — to be present and of the correct type. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_MEMORY_VALUE = createException(\n 'E_INVALID_INITIAL_MEMORY_VALUE',\n 'Attempted to initialize a memory with an invalid value.',\n 'E_INVALID_INITIAL_MEMORY_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Retrievable} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Retrievable` requires `id`, `content`, `trustTier`, `createdAt`, and `updatedAt` to be present\n * and of the correct type, and `trustTier` must be one of `'first-party'`, `'third-party-public'`,\n * or `'third-party-private'`. The `trustTier` decision must be made consciously by the retrieval\n * middleware at construction time — there is no default. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_RETRIEVABLE_VALUE = createException(\n 'E_INVALID_INITIAL_RETRIEVABLE_VALUE',\n 'Invalid initial value supplied to Retrievable constructor.',\n 'E_INVALID_INITIAL_RETRIEVABLE_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Message} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Message` requires `id`, `role` (`user` or `assistant`), `content`, `createdAt`, and\n * `updatedAt` to be present and of the correct type. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_MESSAGE_VALUE = createException(\n 'E_INVALID_INITIAL_MESSAGE_VALUE',\n 'Attempted to initialize a message with an invalid value.',\n 'E_INVALID_INITIAL_MESSAGE_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when an {@link @nhtio/adk!Identity} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Identity` requires both `identifier` (string or number) and `representation` (string or\n * {@link @nhtio/adk!Tokenizable}) to be present and of the correct type. Passing an incomplete or\n * incorrectly typed object signals a programming error in the caller.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_IDENTITY_VALUE = createException(\n 'E_INVALID_INITIAL_IDENTITY_VALUE',\n 'Attempted to initialize an identity with an invalid value.',\n 'E_INVALID_INITIAL_IDENTITY_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Thought} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Thought` requires `id`, `content`, `createdAt`, and `updatedAt` to be present and of the\n * correct type. Passing an incomplete or incorrectly typed object signals a programming error\n * in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_THOUGHT_VALUE = createException(\n 'E_INVALID_INITIAL_THOUGHT_VALUE',\n 'Attempted to initialize a thought with an invalid value.',\n 'E_INVALID_INITIAL_THOUGHT_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!TurnGate} is constructed with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Gates\n */\nexport const E_INVALID_INITIAL_TURN_GATE_VALUE = createException(\n 'E_INVALID_INITIAL_TURN_GATE_VALUE',\n 'Attempted to initialize a turn gate with an invalid value.',\n 'E_INVALID_INITIAL_TURN_GATE_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown synchronously in the caller's context when {@link @nhtio/adk!TurnGate.resolve} is called with a\n * value that fails the gate's schema.\n *\n * @remarks\n * Fatal — passing the wrong type to `resolve()` is a programming error. The internal promise is\n * NOT settled when this is thrown; the gate remains open.\n *\n * @group Gates\n */\nexport const E_INVALID_TURN_GATE_RESOLUTION = createException(\n 'E_INVALID_TURN_GATE_RESOLUTION',\n 'The value supplied to TurnGate.resolve() failed schema validation.',\n 'E_INVALID_TURN_GATE_RESOLUTION',\n 500,\n true\n)\n\n/**\n * Thrown (as a rejection reason) when a {@link @nhtio/adk!TurnGate} times out before being resolved.\n *\n * @remarks\n * Not fatal — a timeout is a recoverable runtime condition; the caller may retry or surface it\n * to the user.\n *\n * @warning\n * A timeout does **not** cancel the external event or clear any remote queue. The gate closes\n * locally, but whatever external system was expected to call `gate.resolve()` may still fire\n * later. Orphaned external state must be handled by the caller.\n *\n * @group Gates\n */\nexport const E_TURN_GATE_TIMEOUT = createException(\n 'E_TURN_GATE_TIMEOUT',\n 'The turn gate timed out before being resolved.',\n 'E_TURN_GATE_TIMEOUT',\n 408,\n false\n)\n\n/**\n * Thrown (as a rejection reason) when a {@link @nhtio/adk!TurnGate} is aborted — either because the turn's\n * `AbortSignal` fired or because {@link @nhtio/adk!TurnGate.abort} was called directly.\n *\n * @remarks\n * Not fatal — abort is an intentional cancellation, not an error in the caller.\n *\n * @group Gates\n */\nexport const E_TURN_GATE_ABORTED = createException(\n 'E_TURN_GATE_ABORTED',\n 'The turn gate was aborted before being resolved.',\n 'E_TURN_GATE_ABORTED',\n 499,\n false\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!SpooledArtifact} is constructed with a value that does not implement the\n * {@link @nhtio/adk!SpoolReader} interface.\n *\n * @remarks\n * Validated at construction time via {@link @nhtio/adk!implementsSpoolReader}. Passing anything that lacks\n * `line`, `byteLength`, or `lineCount` as callable functions signals a programming error in the\n * caller.\n *\n * @group Artifacts\n */\nexport const E_NOT_A_SPOOL_READER = createException(\n 'E_NOT_A_SPOOL_READER',\n 'The provided value does not implement the SpoolReader interface.',\n 'E_NOT_A_SPOOL_READER',\n 500,\n true\n)\n\n/**\n * Thrown when a Media is constructed with a value that does not implement the MediaReader\n * interface.\n *\n * @remarks\n * Validated at construction time. Passing anything that lacks `stream` or `byteLength` as\n * callable functions signals a programming error in the caller.\n *\n * @group Artifacts\n */\nexport const E_NOT_A_MEDIA_READER = createException(\n 'E_NOT_A_MEDIA_READER',\n 'The provided value does not implement the MediaReader interface.',\n 'E_NOT_A_MEDIA_READER',\n 500,\n true\n)\n\n/**\n * Thrown when a Media is initialised with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Artifacts\n */\nexport const E_INVALID_INITIAL_MEDIA_VALUE = createException(\n 'E_INVALID_INITIAL_MEDIA_VALUE',\n 'Attempted to initialize a media with an invalid value.',\n 'E_INVALID_INITIAL_MEDIA_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!ToolCall} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `ToolCall` requires `id`, `tool`, `args`, `checksum`, `isComplete`, `isError`, `createdAt`,\n * and `updatedAt` to be present and of the correct type. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_TOOL_CALL_VALUE = createException(\n 'E_INVALID_INITIAL_TOOL_CALL_VALUE',\n 'Attempted to initialize a tool call with an invalid value.',\n 'E_INVALID_INITIAL_TOOL_CALL_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Tool} is constructed with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Tools\n */\nexport const E_INVALID_INITIAL_TOOL_VALUE = createException(\n 'E_INVALID_INITIAL_TOOL_VALUE',\n 'Attempted to initialize a tool with an invalid value.',\n 'E_INVALID_INITIAL_TOOL_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown synchronously when {@link @nhtio/adk!Tool.validate} is called with arguments that fail the tool's\n * input schema.\n *\n * @remarks\n * Not fatal — an arg validation failure in the tool call loop is a caller mistake that can be\n * surfaced as an error response. The tool handler is NOT called when this is thrown.\n *\n * @group Tools\n */\nexport const E_INVALID_TOOL_ARGS = createException(\n 'E_INVALID_TOOL_ARGS',\n 'The arguments supplied to the tool failed input schema validation.',\n 'E_INVALID_TOOL_ARGS',\n 422,\n false\n)\n\n/**\n * Thrown (as a rejection reason) when a {@link @nhtio/adk!Tool}'s handler throws during execution.\n *\n * @remarks\n * Not fatal — a downstream tool failure is a recoverable runtime condition. The tool call loop\n * catches this error specifically to report the failure back to the model rather than crashing\n * the pipeline.\n *\n * @group Tools\n */\nexport const E_TOOL_DOWNSTREAM_ERROR = createException(\n 'E_TOOL_DOWNSTREAM_ERROR',\n 'The tool handler threw an error during execution.',\n 'E_TOOL_DOWNSTREAM_ERROR',\n 500,\n false\n)\n\n/**\n * Thrown when {@link @nhtio/adk!ToolRegistry.register} is called for a tool name that is already registered\n * and `overwrite` is not `true`.\n *\n * @remarks\n * Fatal — accidentally overwriting a registered tool indicates a programming error. Pass\n * `overwrite: true` to replace an existing tool intentionally.\n *\n * @group Tools\n */\nexport const E_TOOL_ALREADY_REGISTERED = createException(\n 'E_TOOL_ALREADY_REGISTERED',\n 'A tool with this name is already registered. Pass overwrite: true to replace it.',\n 'E_TOOL_ALREADY_REGISTERED',\n 409,\n true\n)\n\n/**\n * Thrown when {@link @nhtio/adk!DispatchContext} is constructed with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Dispatch\n */\nexport const E_INVALID_LLM_EXECUTION_CONTEXT = createException(\n 'E_INVALID_LLM_EXECUTION_CONTEXT',\n 'The LLM execution context cannot be instantiated with the provided value.',\n 'E_INVALID_LLM_EXECUTION_CONTEXT',\n 529,\n true\n)\n\n/**\n * Thrown (as a rejection reason) when {@link @nhtio/adk!DispatchContext.waitFor} is called on a\n * standalone context that was constructed without a `waitFor` function.\n *\n * @remarks\n * Not fatal — the caller can catch this and handle the case where gate suspension is not\n * supported for this execution context.\n *\n * @group Dispatch\n */\nexport const E_LLM_EXECUTION_GATE_NOT_SUPPORTED = createException(\n 'E_LLM_EXECUTION_GATE_NOT_SUPPORTED',\n 'waitFor was called on a standalone DispatchContext with no gate function provided.',\n 'E_LLM_EXECUTION_GATE_NOT_SUPPORTED',\n 501,\n false\n)\n\n/**\n * Thrown when {@link @nhtio/adk!DispatchContext.ack} or {@link @nhtio/adk!DispatchContext.nack} is called on a\n * context that has already been signalled.\n *\n * @remarks\n * Fatal — signalling twice is a programming error in the caller. The first signal wins; the\n * second call is rejected loudly so callers cannot accidentally race between ack and nack.\n *\n * @danger\n * Signalling is **not** silently idempotent. The first `ack()` or `nack()` wins; the second\n * throws immediately. Guard with `if (!ctx.isSignalled)` when more than one seam may signal.\n *\n * @group Dispatch\n */\nexport const E_LLM_EXECUTION_ALREADY_SIGNALLED = createException(\n 'E_LLM_EXECUTION_ALREADY_SIGNALLED',\n 'ack() or nack() was called on an DispatchContext that has already been signalled.',\n 'E_LLM_EXECUTION_ALREADY_SIGNALLED',\n 500,\n true\n)\n\n/**\n * Thrown when {@link @nhtio/adk!DispatchRunner.dispatch} receives an input that fails schema validation.\n *\n * @remarks\n * Fatal — invalid dispatch input indicates a programming error in the caller.\n *\n * @group Dispatch\n */\nexport const E_INVALID_LLM_DISPATCH_INPUT = createException(\n 'E_INVALID_LLM_DISPATCH_INPUT',\n 'The LLM execution runner received an invalid dispatch input.',\n 'E_INVALID_LLM_DISPATCH_INPUT',\n 529,\n true\n)\n\n/**\n * Emitted (via the observability `error` hook) and re-thrown when a non-abort error propagates\n * out of the input or output middleware pipeline during {@link @nhtio/adk!DispatchRunner.dispatch}.\n *\n * @remarks\n * Not fatal — pipeline errors are recoverable runtime conditions. `dispatch()` rejects with this\n * exception so callers can handle the failure via try/catch. Both `dispatchInputPipeline` and\n * `dispatchOutputPipeline` share this one code — the runner does not split input vs. output at\n * this layer.\n *\n * @group Pipelines\n */\nexport const E_DISPATCH_PIPELINE_ERROR = createException(\n 'E_DISPATCH_PIPELINE_ERROR',\n 'An error occurred in an LLM execution pipeline.',\n 'E_DISPATCH_PIPELINE_ERROR',\n 500,\n false\n)\n\n/**\n * Emitted (via the observability `error` hook) and re-thrown when the user-supplied executor\n * callback throws during {@link @nhtio/adk!DispatchRunner.dispatch}.\n *\n * @remarks\n * Not fatal — executor errors are recoverable runtime conditions. `dispatch()` rejects with this\n * exception so callers can handle the failure via try/catch.\n *\n * @group Dispatch\n */\nexport const E_LLM_EXECUTION_EXECUTOR_ERROR = createException(\n 'E_LLM_EXECUTION_EXECUTOR_ERROR',\n 'The LLM execution executor callback threw an error.',\n 'E_LLM_EXECUTION_EXECUTOR_ERROR',\n 500,\n false\n)\n"],"mappings":";;;;;;;;;;;AAWA,IAAa,+BAA+B,gBAC1C,gCACA,2EACA,gCACA,KACA,IACF;;;;;;;;;;;;AAaA,IAAa,yBAAyB,gBACpC,0BACA,uDACA,0BACA,KACA,IACF;;;;;;;;;;;;AAaA,IAAa,yBAAyB,gBACpC,0BACA,4CACA,0BACA,KACA,KACF;;;;;;;;;;;;A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F;;;;;;;;;;;AAYA,IAAa,0BAA0B,gBACrC,2BACA,qDACA,2BACA,KACA,KACF;;;;;;;;;;;AAYA,IAAa,4BAA4B,gBACvC,6BACA,oFACA,6BACA,KACA,IACF;;;;;;;;;AAUA,IAAa,kCAAkC,gBAC7C,mCACA,6EACA,mCACA,KACA,IACF;;;;;;;;;;;AAYA,IAAa,qCAAqC,gBAChD,sCACA,sFACA,sCACA,KACA,KACF;;;;;;;;;;;;;;;AAgBA,IAAa,oCAAoC,gBAC/C,qCACA,qFACA,qCACA,KACA,IACF;;;;;;;;;AAUA,IAAa,+BAA+B,gBAC1C,gCACA,gEACA,gCACA,KACA,IACF;;;;;;;;;;;;;AAcA,IAAa,4BAA4B,gBACvC,6BACA,mDACA,6BACA,KACA,KACF;;;;;;;;;;;AAYA,IAAa,iCAAiC,gBAC5C,kCACA,uDACA,kCACA,KACA,KACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"runtime-DyD9oQjH.js","names":[],"sources":["../src/lib/exceptions/runtime.ts"],"sourcesContent":["import { createException } from '../utils/exceptions'\n\n/**\n * Thrown by {@link @nhtio/adk!TurnRunner} when the supplied config object fails schema validation at\n * construction time.\n *\n * @remarks\n * Marked fatal — a misconfigured runner must not be allowed to execute turns.\n *\n * @group Turn Runner Construction\n */\nexport const E_INVALID_TURN_RUNNER_CONFIG = createException(\n 'E_INVALID_TURN_RUNNER_CONFIG',\n 'The turn runner cannot be instantiated with the provided configuration.',\n 'E_INVALID_TURN_RUNNER_CONFIG',\n 529,\n true\n)\n\n/**\n * Thrown by {@link @nhtio/adk!TurnRunner} when the {@link @nhtio/adk!TurnContext} supplied to `run` fails schema\n * validation.\n *\n * @remarks\n * Marked fatal — an invalid context indicates a programming error in the caller, not a\n * recoverable runtime condition. Thrown synchronously out of `run()` before `turnStart` is\n * emitted.\n *\n * @group Turn Input Validation\n */\nexport const E_INVALID_TURN_CONTEXT = createException(\n 'E_INVALID_TURN_CONTEXT',\n 'The turn runner received an invalid context object.',\n 'E_INVALID_TURN_CONTEXT',\n 529,\n true\n)\n\n/**\n * Emitted (via the `error` event) when a non-abort error propagates out of the input\n * middleware pipeline during {@link @nhtio/adk!TurnRunner.run}.\n *\n * @remarks\n * Not fatal — the turn runner emits this on the `error` event rather than throwing, so\n * registered listeners can handle or log the failure without crashing the pipeline. Dispatch\n * and output middleware are skipped; `turnEnd` still fires.\n *\n * @group Pipelines\n */\nexport const E_INPUT_PIPELINE_ERROR = createException(\n 'E_INPUT_PIPELINE_ERROR',\n 'An error occurred in the input pipeline.',\n 'E_INPUT_PIPELINE_ERROR',\n 500,\n false\n)\n\n/**\n * Emitted (via the `error` event) when a non-abort error propagates out of the output\n * middleware pipeline during {@link @nhtio/adk!TurnRunner.run}.\n *\n * @remarks\n * Not fatal — the turn runner emits this on the `error` event rather than throwing, so\n * registered listeners can handle or log the failure without crashing the pipeline. `turnEnd`\n * still fires.\n *\n * @group Pipelines\n */\nexport const E_OUTPUT_PIPELINE_ERROR = createException(\n 'E_OUTPUT_PIPELINE_ERROR',\n 'An error occurred in the output pipeline.',\n 'E_OUTPUT_PIPELINE_ERROR',\n 500,\n false\n)\n\n/**\n * Emitted (via the `error` event) when a middleware pipeline resolves without reaching its\n * terminal handler and without the turn being aborted. Indicates that some middleware\n * returned without calling `next` and without signalling a deliberate refusal via the turn's\n * abort controller.\n *\n * @remarks\n * Not fatal — the runner emits this on the `error` event so the failure is observable, then\n * proceeds to short-circuit the remainder of the turn the same way any other pipeline error\n * would. The constructor takes a single positional argument identifying the pipeline that\n * short-circuited: one of `'turn-input'`, `'turn-output'`, `'dispatch-input'`, or `'dispatch-output'`.\n *\n * Deliberate refusals should call `ctx.abort(reason)`, which sets the `'aborted'` outcome\n * instead of emitting this error.\n *\n * @warning\n * This is a **detection condition**, not a thrown exception. The runner constructs and emits\n * the code itself when it detects a missing `next()` on the unwind — nothing in user code\n * throws it. Upstream post-steps still run normally.\n *\n * @example\n * ```ts\n * throw new E_PIPELINE_SHORT_CIRCUITED(['turn-input'])\n * ```\n *\n * @group Pipelines\n */\nexport const E_PIPELINE_SHORT_CIRCUITED = createException<[string]>(\n 'E_PIPELINE_SHORT_CIRCUITED',\n \"The '%s' middleware pipeline short-circuited without calling next or aborting the turn.\",\n 'E_PIPELINE_SHORT_CIRCUITED',\n 500,\n false\n)\n\n/**\n * Thrown when a registry is initialised with a value that is defined but not a plain object.\n *\n * @remarks\n * Registries expect either `undefined` (empty start) or a plain object as their initial value.\n * Passing a primitive, array, class instance, or other non-object signals a programming error\n * in the caller.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_REGISTRY_VALUE = createException(\n 'E_INVALID_INITIAL_REGISTRY_VALUE',\n 'Attempted to initialize a registry with a defined non-object value.',\n 'E_INVALID_INITIAL_REGISTRY_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Memory} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Memory` requires all fields — `id`, `content`, `confidence`, `importance`, `createdAt`,\n * `updatedAt` — to be present and of the correct type. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_MEMORY_VALUE = createException(\n 'E_INVALID_INITIAL_MEMORY_VALUE',\n 'Attempted to initialize a memory with an invalid value.',\n 'E_INVALID_INITIAL_MEMORY_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Retrievable} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Retrievable` requires `id`, `content`, `trustTier`, `createdAt`, and `updatedAt` to be present\n * and of the correct type, and `trustTier` must be one of `'first-party'`, `'third-party-public'`,\n * or `'third-party-private'`. The `trustTier` decision must be made consciously by the retrieval\n * middleware at construction time — there is no default. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_RETRIEVABLE_VALUE = createException(\n 'E_INVALID_INITIAL_RETRIEVABLE_VALUE',\n 'Invalid initial value supplied to Retrievable constructor.',\n 'E_INVALID_INITIAL_RETRIEVABLE_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Message} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Message` requires `id`, `role` (`user` or `assistant`), `content`, `createdAt`, and\n * `updatedAt` to be present and of the correct type. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_MESSAGE_VALUE = createException(\n 'E_INVALID_INITIAL_MESSAGE_VALUE',\n 'Attempted to initialize a message with an invalid value.',\n 'E_INVALID_INITIAL_MESSAGE_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when an {@link @nhtio/adk!Identity} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Identity` requires both `identifier` (string or number) and `representation` (string or\n * {@link @nhtio/adk!Tokenizable}) to be present and of the correct type. Passing an incomplete or\n * incorrectly typed object signals a programming error in the caller.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_IDENTITY_VALUE = createException(\n 'E_INVALID_INITIAL_IDENTITY_VALUE',\n 'Attempted to initialize an identity with an invalid value.',\n 'E_INVALID_INITIAL_IDENTITY_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Thought} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Thought` requires `id`, `content`, `createdAt`, and `updatedAt` to be present and of the\n * correct type. Passing an incomplete or incorrectly typed object signals a programming error\n * in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_THOUGHT_VALUE = createException(\n 'E_INVALID_INITIAL_THOUGHT_VALUE',\n 'Attempted to initialize a thought with an invalid value.',\n 'E_INVALID_INITIAL_THOUGHT_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!TurnGate} is constructed with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Gates\n */\nexport const E_INVALID_INITIAL_TURN_GATE_VALUE = createException(\n 'E_INVALID_INITIAL_TURN_GATE_VALUE',\n 'Attempted to initialize a turn gate with an invalid value.',\n 'E_INVALID_INITIAL_TURN_GATE_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown synchronously in the caller's context when {@link @nhtio/adk!TurnGate.resolve} is called with a\n * value that fails the gate's schema.\n *\n * @remarks\n * Fatal — passing the wrong type to `resolve()` is a programming error. The internal promise is\n * NOT settled when this is thrown; the gate remains open.\n *\n * @group Gates\n */\nexport const E_INVALID_TURN_GATE_RESOLUTION = createException(\n 'E_INVALID_TURN_GATE_RESOLUTION',\n 'The value supplied to TurnGate.resolve() failed schema validation.',\n 'E_INVALID_TURN_GATE_RESOLUTION',\n 500,\n true\n)\n\n/**\n * Thrown (as a rejection reason) when a {@link @nhtio/adk!TurnGate} times out before being resolved.\n *\n * @remarks\n * Not fatal — a timeout is a recoverable runtime condition; the caller may retry or surface it\n * to the user.\n *\n * @warning\n * A timeout does **not** cancel the external event or clear any remote queue. The gate closes\n * locally, but whatever external system was expected to call `gate.resolve()` may still fire\n * later. Orphaned external state must be handled by the caller.\n *\n * @group Gates\n */\nexport const E_TURN_GATE_TIMEOUT = createException(\n 'E_TURN_GATE_TIMEOUT',\n 'The turn gate timed out before being resolved.',\n 'E_TURN_GATE_TIMEOUT',\n 408,\n false\n)\n\n/**\n * Thrown (as a rejection reason) when a {@link @nhtio/adk!TurnGate} is aborted — either because the turn's\n * `AbortSignal` fired or because {@link @nhtio/adk!TurnGate.abort} was called directly.\n *\n * @remarks\n * Not fatal — abort is an intentional cancellation, not an error in the caller.\n *\n * @group Gates\n */\nexport const E_TURN_GATE_ABORTED = createException(\n 'E_TURN_GATE_ABORTED',\n 'The turn gate was aborted before being resolved.',\n 'E_TURN_GATE_ABORTED',\n 499,\n false\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!SpooledArtifact} is constructed with a value that does not implement the\n * {@link @nhtio/adk!SpoolReader} interface.\n *\n * @remarks\n * Validated at construction time via {@link @nhtio/adk!implementsSpoolReader}. Passing anything that lacks\n * `line`, `byteLength`, or `lineCount` as callable functions signals a programming error in the\n * caller.\n *\n * @group Artifacts\n */\nexport const E_NOT_A_SPOOL_READER = createException(\n 'E_NOT_A_SPOOL_READER',\n 'The provided value does not implement the SpoolReader interface.',\n 'E_NOT_A_SPOOL_READER',\n 500,\n true\n)\n\n/**\n * Thrown when a Media is constructed with a value that does not implement the MediaReader\n * interface.\n *\n * @remarks\n * Validated at construction time. Passing anything that lacks `stream` or `byteLength` as\n * callable functions signals a programming error in the caller.\n *\n * @group Artifacts\n */\nexport const E_NOT_A_MEDIA_READER = createException(\n 'E_NOT_A_MEDIA_READER',\n 'The provided value does not implement the MediaReader interface.',\n 'E_NOT_A_MEDIA_READER',\n 500,\n true\n)\n\n/**\n * Thrown when a Media is initialised with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Artifacts\n */\nexport const E_INVALID_INITIAL_MEDIA_VALUE = createException(\n 'E_INVALID_INITIAL_MEDIA_VALUE',\n 'Attempted to initialize a media with an invalid value.',\n 'E_INVALID_INITIAL_MEDIA_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!ToolCall} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `ToolCall` requires `id`, `tool`, `args`, `checksum`, `isComplete`, `isError`, `createdAt`,\n * and `updatedAt` to be present and of the correct type. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_TOOL_CALL_VALUE = createException(\n 'E_INVALID_INITIAL_TOOL_CALL_VALUE',\n 'Attempted to initialize a tool call with an invalid value.',\n 'E_INVALID_INITIAL_TOOL_CALL_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Tool} is constructed with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Tools\n */\nexport const E_INVALID_INITIAL_TOOL_VALUE = createException(\n 'E_INVALID_INITIAL_TOOL_VALUE',\n 'Attempted to initialize a tool with an invalid value.',\n 'E_INVALID_INITIAL_TOOL_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown synchronously when {@link @nhtio/adk!Tool.validate} is called with arguments that fail the tool's\n * input schema.\n *\n * @remarks\n * Not fatal — an arg validation failure in the tool call loop is a caller mistake that can be\n * surfaced as an error response. The tool handler is NOT called when this is thrown.\n *\n * @group Tools\n */\nexport const E_INVALID_TOOL_ARGS = createException(\n 'E_INVALID_TOOL_ARGS',\n 'The arguments supplied to the tool failed input schema validation.',\n 'E_INVALID_TOOL_ARGS',\n 422,\n false\n)\n\n/**\n * Thrown (as a rejection reason) when a {@link @nhtio/adk!Tool}'s handler throws during execution.\n *\n * @remarks\n * Not fatal — a downstream tool failure is a recoverable runtime condition. The tool call loop\n * catches this error specifically to report the failure back to the model rather than crashing\n * the pipeline.\n *\n * @group Tools\n */\nexport const E_TOOL_DOWNSTREAM_ERROR = createException(\n 'E_TOOL_DOWNSTREAM_ERROR',\n 'The tool handler threw an error during execution.',\n 'E_TOOL_DOWNSTREAM_ERROR',\n 500,\n false\n)\n\n/**\n * Thrown when {@link @nhtio/adk!ToolRegistry.register} is called for a tool name that is already registered\n * and `overwrite` is not `true`.\n *\n * @remarks\n * Fatal — accidentally overwriting a registered tool indicates a programming error. Pass\n * `overwrite: true` to replace an existing tool intentionally.\n *\n * @group Tools\n */\nexport const E_TOOL_ALREADY_REGISTERED = createException(\n 'E_TOOL_ALREADY_REGISTERED',\n 'A tool with this name is already registered. Pass overwrite: true to replace it.',\n 'E_TOOL_ALREADY_REGISTERED',\n 409,\n true\n)\n\n/**\n * Thrown when {@link @nhtio/adk!DispatchContext} is constructed with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Dispatch\n */\nexport const E_INVALID_LLM_EXECUTION_CONTEXT = createException(\n 'E_INVALID_LLM_EXECUTION_CONTEXT',\n 'The LLM execution context cannot be instantiated with the provided value.',\n 'E_INVALID_LLM_EXECUTION_CONTEXT',\n 529,\n true\n)\n\n/**\n * Thrown (as a rejection reason) when {@link @nhtio/adk!DispatchContext.waitFor} is called on a\n * standalone context that was constructed without a `waitFor` function.\n *\n * @remarks\n * Not fatal — the caller can catch this and handle the case where gate suspension is not\n * supported for this execution context.\n *\n * @group Dispatch\n */\nexport const E_LLM_EXECUTION_GATE_NOT_SUPPORTED = createException(\n 'E_LLM_EXECUTION_GATE_NOT_SUPPORTED',\n 'waitFor was called on a standalone DispatchContext with no gate function provided.',\n 'E_LLM_EXECUTION_GATE_NOT_SUPPORTED',\n 501,\n false\n)\n\n/**\n * Thrown when {@link @nhtio/adk!DispatchContext.ack} or {@link @nhtio/adk!DispatchContext.nack} is called on a\n * context that has already been signalled.\n *\n * @remarks\n * Fatal — signalling twice is a programming error in the caller. The first signal wins; the\n * second call is rejected loudly so callers cannot accidentally race between ack and nack.\n *\n * @danger\n * Signalling is **not** silently idempotent. The first `ack()` or `nack()` wins; the second\n * throws immediately. Guard with `if (!ctx.isSignalled)` when more than one seam may signal.\n *\n * @group Dispatch\n */\nexport const E_LLM_EXECUTION_ALREADY_SIGNALLED = createException(\n 'E_LLM_EXECUTION_ALREADY_SIGNALLED',\n 'ack() or nack() was called on an DispatchContext that has already been signalled.',\n 'E_LLM_EXECUTION_ALREADY_SIGNALLED',\n 500,\n true\n)\n\n/**\n * Thrown when {@link @nhtio/adk!DispatchRunner.dispatch} receives an input that fails schema validation.\n *\n * @remarks\n * Fatal — invalid dispatch input indicates a programming error in the caller.\n *\n * @group Dispatch\n */\nexport const E_INVALID_LLM_DISPATCH_INPUT = createException(\n 'E_INVALID_LLM_DISPATCH_INPUT',\n 'The LLM execution runner received an invalid dispatch input.',\n 'E_INVALID_LLM_DISPATCH_INPUT',\n 529,\n true\n)\n\n/**\n * Emitted (via the observability `error` hook) and re-thrown when a non-abort error propagates\n * out of the input or output middleware pipeline during {@link @nhtio/adk!DispatchRunner.dispatch}.\n *\n * @remarks\n * Not fatal — pipeline errors are recoverable runtime conditions. `dispatch()` rejects with this\n * exception so callers can handle the failure via try/catch. Both `dispatchInputPipeline` and\n * `dispatchOutputPipeline` share this one code — the runner does not split input vs. output at\n * this layer.\n *\n * @group Pipelines\n */\nexport const E_DISPATCH_PIPELINE_ERROR = createException(\n 'E_DISPATCH_PIPELINE_ERROR',\n 'An error occurred in an LLM execution pipeline.',\n 'E_DISPATCH_PIPELINE_ERROR',\n 500,\n false\n)\n\n/**\n * Emitted (via the observability `error` hook) and re-thrown when the user-supplied executor\n * callback throws during {@link @nhtio/adk!DispatchRunner.dispatch}.\n *\n * @remarks\n * Not fatal — executor errors are recoverable runtime conditions. `dispatch()` rejects with this\n * exception so callers can handle the failure via try/catch.\n *\n * @group Dispatch\n */\nexport const E_LLM_EXECUTION_EXECUTOR_ERROR = createException(\n 'E_LLM_EXECUTION_EXECUTOR_ERROR',\n 'The LLM execution executor callback threw an error.',\n 'E_LLM_EXECUTION_EXECUTOR_ERROR',\n 500,\n false\n)\n"],"mappings":";;;;;;;;;;;AAWA,IAAa,+BAA+B,mBAAA,gBAC1C,gCACA,2EACA,gCACA,KACA,IACF;;;;;;;;;;;;AAaA,IAAa,yBAAyB,mBAAA,gBACpC,0BACA,uDACA,0BACA,KACA,IACF;;;;;;;;;;;;AAaA,IAAa,yBAAyB,mBAAA,gBACpC,0BACA,4CACA,0BACA,KACA,KACF;;;;;;;;;;;;AAaA,IAAa,0BAA0B,mBAAA,gBACrC,2BACA,6CACA,2BACA,KACA,KACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAa,6BAA6B,mBAAA,gBACxC,8BACA,2FACA,8BACA,KACA,KACF;;;;;;;;;;;AAYA,IAAa,mCAAmC,mBAAA,gBAC9C,oCACA,uEACA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;;AAYA,IAAa,4BAA4B,mBAAA,gBACvC,6BACA,oFACA,6BACA,KACA,IACF;;;;;;;;;AAUA,IAAa,kCAAkC,mBAAA,gBAC7C,mCACA,6EACA,mCACA,KACA,IACF;;;;;;;;;;;AAYA,IAAa,qCAAqC,mBAAA,gBAChD,sCACA,sFACA,sCACA,KACA,KACF;;;;;;;;;;;;;;;AAgBA,IAAa,oCAAoC,mBAAA,gBAC/C,qCACA,qFACA,qCACA,KACA,IACF;;;;;;;;;AAUA,IAAa,+BAA+B,mBAAA,gBAC1C,gCACA,gEACA,gCACA,KACA,IACF;;;;;;;;;;;;;AAcA,IAAa,4BAA4B,mBAAA,gBACvC,6BACA,mDACA,6BACA,KACA,KACF;;;;;;;;;;;AAYA,IAAa,iCAAiC,mBAAA,gBAC5C,kCACA,uDACA,kCACA,KACA,KACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"turn_runner-C1-mup84.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 MediaBytesStoreFn,\n RetrievableBytesStoreFn,\n} from './turn_runner_context'\n\n/**\n * Configuration supplied to {@link @nhtio/adk!TurnRunner} at construction time.\n *\n * @remarks\n * Validated against `turnRunnerConfigSchema` at construction — a misconfigured runner throws\n * immediately rather than failing on the first turn.\n *\n * All fetch and mutation callbacks are required: they are injected into each {@link @nhtio/adk!TurnContext}\n * so middleware can call fetch, refresh, and persistence methods directly on the context without\n * coupling to the runner.\n *\n * `tools` is optional at the caller level and defaults to `[]` after schema resolution — a runner\n * with no baseline tools is valid.\n */\nexport interface TurnRunnerConfig {\n /** Performs the LLM API/SDK call for each iteration of the dispatch loop; receives the active {@link @nhtio/adk!DispatchContext} and an {@link @nhtio/adk!DispatchExecutorHelpers} object for managing per-id stream state. */\n executorCallback: DispatchExecutorFn\n /** Called once per turn to supply memories; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchMemoriesCallback: MemoryRetrievalFn\n /** Called once per turn to supply conversation history; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchMessagesCallback: MessageRetrievalFn\n /** Called once per turn to supply thought traces; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchThoughtsCallback: ThoughtRetrievalFn\n /** Called once per turn to supply tool call records; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchToolCallsCallback: ToolCallRetrievalFn\n /** Called to supply available tools; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchToolsCallback: ToolsRetrievalFn\n /** Called to refresh and return standing instructions; receives the active {@link @nhtio/adk!TurnContext}. */\n refreshStandingInstructionsCallback: StandingInstructionsRefreshFn\n /** Persists a new standing instruction. */\n storeStandingInstructionCallback: StandingInstructionStoreFn\n /** Updates an existing standing instruction in the persistence layer. */\n mutateStandingInstructionCallback: StandingInstructionMutateFn\n /** Removes a standing instruction from the persistence layer. */\n deleteStandingInstructionCallback: StandingInstructionDeleteFn\n /** Persists a new memory. */\n storeMemoryCallback: MemoryStoreFn\n /** Updates an existing memory in the persistence layer. */\n mutateMemoryCallback: MemoryMutateFn\n /** Removes a memory from the persistence layer by ID. */\n deleteMemoryCallback: MemoryDeleteFn\n /** Called once per turn to supply retrievable (RAG) records; receives the active {@link @nhtio/adk!TurnContext}. */\n fetchRetrievablesCallback: RetrievableRetrievalFn\n /** Persists a new retrievable record. */\n storeRetrievableCallback: RetrievableStoreFn\n /** Updates an existing retrievable record in the persistence layer. */\n mutateRetrievableCallback: RetrievableMutateFn\n /** Removes a retrievable record from the persistence layer by ID. */\n deleteRetrievableCallback: RetrievableDeleteFn\n /** Persists a new message. */\n storeMessageCallback: MessageStoreFn\n /** Updates an existing message in the persistence layer. */\n mutateMessageCallback: MessageMutateFn\n /** Removes a message from the persistence layer by ID. */\n deleteMessageCallback: MessageDeleteFn\n /** Persists a new thought. */\n storeThoughtCallback: ThoughtStoreFn\n /** Updates an existing thought in the persistence layer. */\n mutateThoughtCallback: ThoughtMutateFn\n /** Removes a thought from the persistence layer by ID. */\n deleteThoughtCallback: ThoughtDeleteFn\n /** Persists a new tool call. */\n storeToolCallCallback: ToolCallStoreFn\n /** Updates an existing tool call in the persistence layer. */\n mutateToolCallCallback: ToolCallMutateFn\n /** Removes a tool call from the persistence layer by ID. */\n deleteToolCallCallback: ToolCallDeleteFn\n /** Persists tool-generated media bytes into consumer storage; returns a `MediaReader`. */\n storeMediaBytesCallback: MediaBytesStoreFn\n /** Persists extracted retrievable text bytes into consumer storage; returns a `SpoolReader`. */\n storeRetrievableBytesCallback: RetrievableBytesStoreFn\n /** Baseline tools available on every turn. Middleware may trim or extend this per-turn via `ctx.tools`. Defaults to `[]`. */\n tools?: Tool[]\n /** Turn-level input middleware, executed in order against the {@link @nhtio/adk!TurnContext} before the LLM dispatch. Defaults to `[]`. */\n turnInputPipeline?: TurnPipelineMiddlewareFn[]\n /** Turn-level output middleware, executed in order against the {@link @nhtio/adk!TurnContext} after the LLM dispatch resolves successfully. Defaults to `[]`. */\n turnOutputPipeline?: TurnPipelineMiddlewareFn[]\n /** LLM-iteration input middleware, executed in order against the {@link @nhtio/adk!DispatchContext} before the executor on each iteration. Defaults to `[]`. */\n dispatchInputPipeline?: DispatchPipelineMiddlewareFn[]\n /** LLM-iteration output middleware, executed in order against the {@link @nhtio/adk!DispatchContext} after the executor on each iteration. Defaults to `[]`. */\n dispatchOutputPipeline?: DispatchPipelineMiddlewareFn[]\n}\n\n/**\n * Fully-resolved {@link TurnRunnerConfig} after schema validation.\n *\n * @remarks\n * All optional fields are guaranteed present (e.g. `tools` defaults to `[]`). The runner stores\n * this type internally so field access never needs to guard for undefined.\n */\nexport type ResolvedTurnRunnerConfig = Required<TurnRunnerConfig>\n\n/**\n * Validator schema used to validate a {@link TurnRunnerConfig} at {@link @nhtio/adk!TurnRunner} construction time.\n *\n * @remarks\n * Validates that all callbacks are functions of the correct arity, and that `tools` — when\n * provided — is an array of valid {@link @nhtio/adk!Tool} instances. Defaults `tools` to `[]`.\n *\n * Throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} (via the {@link @nhtio/adk!TurnRunner} constructor) when\n * validation fails.\n */\nexport const turnRunnerConfigSchema = validator.object<TurnRunnerConfig>({\n executorCallback: validator.function().required(),\n fetchMemoriesCallback: validator.function().arity(1).required(),\n fetchMessagesCallback: validator.function().arity(1).required(),\n fetchThoughtsCallback: validator.function().arity(1).required(),\n fetchToolCallsCallback: validator.function().arity(1).required(),\n fetchToolsCallback: validator.function().arity(1).required(),\n refreshStandingInstructionsCallback: validator.function().arity(1).required(),\n storeStandingInstructionCallback: validator.function().arity(2).required(),\n mutateStandingInstructionCallback: validator.function().arity(2).required(),\n deleteStandingInstructionCallback: validator.function().arity(2).required(),\n storeMemoryCallback: validator.function().arity(2).required(),\n mutateMemoryCallback: validator.function().arity(2).required(),\n deleteMemoryCallback: validator.function().arity(2).required(),\n fetchRetrievablesCallback: validator.function().arity(1).required(),\n storeRetrievableCallback: validator.function().arity(2).required(),\n mutateRetrievableCallback: validator.function().arity(2).required(),\n deleteRetrievableCallback: validator.function().arity(2).required(),\n storeMessageCallback: validator.function().arity(2).required(),\n mutateMessageCallback: validator.function().arity(2).required(),\n deleteMessageCallback: validator.function().arity(2).required(),\n storeThoughtCallback: validator.function().arity(2).required(),\n mutateThoughtCallback: validator.function().arity(2).required(),\n deleteThoughtCallback: validator.function().arity(2).required(),\n storeToolCallCallback: validator.function().arity(2).required(),\n mutateToolCallCallback: validator.function().arity(2).required(),\n deleteToolCallCallback: validator.function().arity(2).required(),\n storeMediaBytesCallback: validator.function().arity(3).required(),\n storeRetrievableBytesCallback: validator.function().arity(3).required(),\n tools: validator\n .array()\n .items(\n validator.any().custom((value: unknown, helpers: { error: (code: string) => unknown }) => {\n if (Tool.isTool(value)) return value\n return helpers.error('any.invalid')\n })\n )\n .default([]),\n turnInputPipeline: validator.array().items(validator.function()).default([]),\n turnOutputPipeline: validator.array().items(validator.function()).default([]),\n dispatchInputPipeline: validator.array().items(validator.function()).default([]),\n dispatchOutputPipeline: validator.array().items(validator.function()).default([]),\n})\n","import { DateTime } from 'luxon'\nimport { Middleware } from '@nhtio/middleware'\nimport { TurnGate } from './classes/turn_gate'\nimport { DispatchRunner } from './dispatch_runner'\nimport { ToolRegistry } from './classes/tool_registry'\nimport { isInstanceOf, isError } from './utils/guards'\nimport { TypedEventEmitter } from '@nhtio/tiny-typed-emitter'\nimport { passesSchema, validateOrThrow } from './utils/validation'\nimport { turnRunnerConfigSchema } from './contracts/turn_runner_config'\nimport { TurnContext, RawTurnContext } from './contracts/turn_runner_context'\nimport {\n E_INVALID_TURN_RUNNER_CONFIG,\n E_INPUT_PIPELINE_ERROR,\n E_OUTPUT_PIPELINE_ERROR,\n E_PIPELINE_SHORT_CIRCUITED,\n} from './exceptions/runtime'\nimport type { Runner } from '@nhtio/middleware'\nimport type { RawTurnGate } from './classes/turn_gate'\nimport type { ResolvedTurnRunnerConfig, TurnRunnerConfig } from './contracts/turn_runner_config'\nimport type {\n OpenGateFn,\n TurnEvents,\n TurnEvent,\n TurnEventListener,\n TurnPipelineMiddlewareFn,\n TurnObservabilityEvents,\n TurnObservabilityEvent,\n TurnObservabilityEventListener,\n} from './types/turn_runner'\n\nexport type {\n TurnPipelineMiddlewareFn,\n TurnStreamableContent,\n TurnToolCallContent,\n TurnStartEvent,\n TurnEndEvent,\n TurnGateClosedEvent,\n ToolExecutionStartEvent,\n ToolExecutionEndEvent,\n EmitMessageFn,\n EmitThoughtFn,\n EmitToolCallFn,\n EmitToolExecutionStartFn,\n EmitToolExecutionEndFn,\n OpenGateFn,\n TurnEvents,\n TurnEvent,\n TurnEventListener,\n TurnObservabilityEvents,\n TurnObservabilityEvent,\n TurnObservabilityEventListener,\n} from './types/turn_runner'\n\n/**\n * Executes a single agent turn through paired input and output middleware pipelines.\n *\n * @remarks\n * Construction validates `config` eagerly and throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} if it\n * does not satisfy the schema — fail-fast so misconfiguration surfaces before any turn runs.\n *\n * Each call to {@link TurnRunner.run} threads a {@link @nhtio/adk!TurnContext} through the input pipeline,\n * invokes the model, then threads the result through the output pipeline. Middleware on each side\n * can read and mutate the context for pre- and post-processing (e.g. message normalisation, tool\n * call dispatch, response filtering).\n *\n * **Two event buses:**\n * - Functional bus (`on` / `off` / `once`): `message`, `thought`, `toolCall` — pipeline-affecting\n * events that middleware raises throughout turn execution.\n * - Observability bus (`observe` / `unobserve` / `observeOnce`): `turnStart`, `turnEnd`,\n * `turnGateOpen`, `turnGateClosed`, `error` — instrumentation-only events that monitor execution\n * without participating in it.\n *\n * Streaming content is surfaced via `message` and `thought` events; tool call lifecycle via\n * `toolCall`; non-fatal pipeline errors via the observability `error` event; gate lifecycle via\n * `turnGateOpen` and `turnGateClosed` — all throughout execution.\n *\n * @example\n * ```ts\n * const runner = new TurnRunner({\n * fetchMemoriesCallback: async (ctx) => memoryStore.query(ctx),\n * fetchMessagesCallback: async (ctx) => messageStore.history(ctx),\n * fetchThoughtsCallback: async (ctx) => thoughtStore.history(ctx),\n * fetchToolCallsCallback: async (ctx) => toolCallStore.history(ctx),\n * })\n * // Functional bus — pipeline events\n * runner.on('message', (chunk) => process.stdout.write(chunk.aDelta))\n * // Observability bus — instrumentation\n * runner.observe('error', (err) => console.error(err.toString()))\n * runner.observe('turnStart', ({ turnId }) => console.log('turn started', turnId))\n * runner.observe('turnGateOpen', (gate) => {\n * if (gate.reason === 'tool_approval') {\n * gate.resolve(true) // approve immediately for this example\n * }\n * })\n * await runner.run({\n * turnAbortController: new AbortController(),\n * systemPrompt: 'You are a helpful assistant.',\n * standingInstructions: [],\n * })\n * ```\n */\nexport class TurnRunner {\n /**\n * Returns `true` if `value` is a {@link TurnRunner} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link TurnRunner} instance.\n */\n public static isTurnRunner(value: unknown): value is TurnRunner {\n return isInstanceOf(value, 'TurnRunner', TurnRunner)\n }\n\n #config: ResolvedTurnRunnerConfig\n #inputRunner: Runner<TurnPipelineMiddlewareFn>\n #outputRunner: Runner<TurnPipelineMiddlewareFn>\n #functionalEmitter: TypedEventEmitter<TurnEvents>\n #observabilityEmitter: TypedEventEmitter<TurnObservabilityEvents>\n\n /**\n * @param config - Construction-time configuration validated against {@link turnRunnerConfigSchema}.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_RUNNER_CONFIG} when `config` does not satisfy the schema.\n */\n constructor(config: TurnRunnerConfig) {\n const isValid = passesSchema(turnRunnerConfigSchema, config)\n if (!isValid) {\n throw new E_INVALID_TURN_RUNNER_CONFIG()\n }\n // Store the resolved config so optional fields (e.g. tools) are always present.\n this.#config = validateOrThrow<ResolvedTurnRunnerConfig>(turnRunnerConfigSchema, config, true)\n const turnInputPipeline = new Middleware<TurnPipelineMiddlewareFn>()\n const turnOutputPipeline = new Middleware<TurnPipelineMiddlewareFn>()\n const wrap =\n (fn: TurnPipelineMiddlewareFn): TurnPipelineMiddlewareFn =>\n (ctx, next) => {\n // Skip downstream user middlewares once an abort has been signalled. The\n // wrapper still calls next() so the pipeline reaches its terminal resolver\n // (keeping the short-circuit detector quiet); the original middleware body\n // does not run, so it has nothing to clean up.\n if (ctx.aborted) return next()\n return fn(ctx, next)\n }\n for (const fn of this.#config.turnInputPipeline) turnInputPipeline.add(wrap(fn))\n for (const fn of this.#config.turnOutputPipeline) turnOutputPipeline.add(wrap(fn))\n this.#inputRunner = turnInputPipeline.runner()\n this.#outputRunner = turnOutputPipeline.runner()\n this.#functionalEmitter = new TypedEventEmitter<TurnEvents>()\n this.#observabilityEmitter = new TypedEventEmitter<TurnObservabilityEvents>()\n }\n\n // ── Functional bus ───────────────────────────────────────────────────────\n\n /**\n * Removes a previously registered functional listener for `event`.\n *\n * @param event - The event to stop listening to.\n * @param listener - The listener function to remove.\n * @returns `this` for chaining.\n */\n off<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.off(event, listener)\n return this\n }\n\n /**\n * Registers a persistent functional listener for `event`.\n *\n * @param event - The event to listen to.\n * @param listener - The function to call on each emission.\n * @returns `this` for chaining.\n */\n on<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.on(event, listener)\n return this\n }\n\n /**\n * Registers a one-time functional listener for `event` that is automatically removed after the\n * first emission.\n *\n * @param event - The event to listen to.\n * @param listener - The function to call on the next emission.\n * @returns `this` for chaining.\n */\n once<K>(event: TurnEvent<K>, listener: TurnEventListener<K>): this {\n this.#functionalEmitter.once(event, listener)\n return this\n }\n\n // ── Observability bus ────────────────────────────────────────────────────\n\n /**\n * Removes a previously registered observability listener for `event`.\n *\n * @param event - The event to stop observing.\n * @param listener - The listener function to remove.\n * @returns `this` for chaining.\n */\n unobserve<K>(\n event: TurnObservabilityEvent<K>,\n listener: TurnObservabilityEventListener<K>\n ): this {\n this.#observabilityEmitter.off(event, listener)\n return this\n }\n\n /**\n * Registers a persistent observability listener for `event`.\n *\n * @remarks\n * Use the observability bus (`observe` / `unobserve` / `observeOnce`) for instrumentation:\n * turn lifecycle, gate lifecycle, and non-fatal errors. Use the functional bus (`on` / `off` /\n * `once`) for pipeline-affecting events: `message`, `thought`, `toolCall`.\n *\n * @param event - The event to observe.\n * @param listener - The function to call on each emission.\n * @returns `this` for chaining.\n */\n observe<K>(event: TurnObservabilityEvent<K>, listener: TurnObservabilityEventListener<K>): this {\n this.#observabilityEmitter.on(event, listener)\n return this\n }\n\n /**\n * Registers a one-time observability listener for `event` that is automatically removed after\n * the first emission.\n *\n * @param event - The event to observe once.\n * @param listener - The function to call on the next emission.\n * @returns `this` for chaining.\n */\n observeOnce<K>(\n event: TurnObservabilityEvent<K>,\n listener: TurnObservabilityEventListener<K>\n ): this {\n this.#observabilityEmitter.once(event, listener)\n return this\n }\n\n // ── Turn execution ───────────────────────────────────────────────────────\n\n /**\n * Executes a single agent turn against the provided raw context.\n *\n * @remarks\n * Returns `Promise<void>` intentionally — all meaningful output surfaces via events, not return\n * values. Register listeners before calling `run`: observability events (`turnStart`, `turnEnd`)\n * bracket execution; functional events (`message`, `thought`, `toolCall`) fire throughout;\n * observability `error` carries non-fatal pipeline failures; `turnGateOpen` and `turnGateClosed`\n * fire when middleware suspends via `ctx.waitFor()`. Awaiting this method only tells you the\n * pipeline has finished, not what it produced.\n *\n * Constructs a validated {@link @nhtio/adk!TurnContext} from `context` (throwing\n * {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} on failure), then runs the input middleware pipeline.\n * Abort signals are silently swallowed.\n *\n * @param context - Raw input validated and wrapped into a {@link @nhtio/adk!TurnContext} before execution.\n * @throws {@link @nhtio/adk!E_INVALID_TURN_CONTEXT} when `context` does not satisfy the schema.\n */\n async run(context: RawTurnContext): Promise<void> {\n const abortController = context.turnAbortController ?? new AbortController()\n\n // Forward declaration so openGate can reference turnContext.id before it is assigned.\n let turnContextId: string\n\n const openGate: OpenGateFn = <T>(raw: Omit<RawTurnGate, 'turnId' | 'abortSignal'>) => {\n const gate = new TurnGate<T>({\n ...raw,\n turnId: turnContextId,\n abortSignal: abortController.signal,\n })\n this.#observabilityEmitter.emit('turnGateOpen', gate)\n const promise = gate._promise()\n promise.then(\n () => {\n this.#observabilityEmitter.emit('turnGateClosed', {\n gateId: gate.id,\n turnId: gate.turnId,\n result: 'resolved',\n settledAt: DateTime.now(),\n })\n },\n (err: unknown) => {\n let result: 'rejected' | 'aborted' | 'timeout' = 'rejected'\n if (isInstanceOf(err, 'E_TURN_GATE_ABORTED')) result = 'aborted'\n else if (isInstanceOf(err, 'E_TURN_GATE_TIMEOUT')) result = 'timeout'\n this.#observabilityEmitter.emit('turnGateClosed', {\n gateId: gate.id,\n turnId: gate.turnId,\n result,\n settledAt: DateTime.now(),\n })\n }\n )\n return promise\n }\n\n const tools = new ToolRegistry(this.#config.tools)\n\n const turnContext = new TurnContext(\n { ...context, turnAbortController: abortController },\n {\n fetchMemories: this.#config.fetchMemoriesCallback,\n fetchMessages: this.#config.fetchMessagesCallback,\n fetchThoughts: this.#config.fetchThoughtsCallback,\n fetchToolCalls: this.#config.fetchToolCallsCallback,\n fetchTools: this.#config.fetchToolsCallback,\n refreshStandingInstructions: this.#config.refreshStandingInstructionsCallback,\n storeStandingInstruction: this.#config.storeStandingInstructionCallback,\n mutateStandingInstruction: this.#config.mutateStandingInstructionCallback,\n deleteStandingInstruction: this.#config.deleteStandingInstructionCallback,\n storeMemory: this.#config.storeMemoryCallback,\n mutateMemory: this.#config.mutateMemoryCallback,\n deleteMemory: this.#config.deleteMemoryCallback,\n fetchRetrievables: this.#config.fetchRetrievablesCallback,\n storeRetrievable: this.#config.storeRetrievableCallback,\n mutateRetrievable: this.#config.mutateRetrievableCallback,\n deleteRetrievable: this.#config.deleteRetrievableCallback,\n storeMessage: this.#config.storeMessageCallback,\n mutateMessage: this.#config.mutateMessageCallback,\n deleteMessage: this.#config.deleteMessageCallback,\n storeThought: this.#config.storeThoughtCallback,\n mutateThought: this.#config.mutateThoughtCallback,\n deleteThought: this.#config.deleteThoughtCallback,\n storeToolCall: this.#config.storeToolCallCallback,\n mutateToolCall: this.#config.mutateToolCallCallback,\n deleteToolCall: this.#config.deleteToolCallCallback,\n storeMediaBytes: this.#config.storeMediaBytesCallback,\n storeRetrievableBytes: this.#config.storeRetrievableBytesCallback,\n emitMessage: (content) => this.#functionalEmitter.emit('message', content),\n emitThought: (content) => this.#functionalEmitter.emit('thought', content),\n emitToolCall: (content) => this.#functionalEmitter.emit('toolCall', content),\n emitToolExecutionStart: (event) =>\n this.#observabilityEmitter.emit('toolExecutionStart', event),\n emitToolExecutionEnd: (event) => this.#observabilityEmitter.emit('toolExecutionEnd', event),\n openGate,\n tools,\n }\n )\n\n turnContextId = turnContext.id\n\n const startedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnStart', { turnId: turnContext.id, startedAt })\n\n const emitTurnEnd = () => {\n const endedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnEnd', {\n turnId: turnContext.id,\n startedAt,\n endedAt,\n durationMs: endedAt.diff(startedAt).milliseconds,\n })\n }\n\n // 1. Input pipeline\n let inputFailed = false\n let inputReached = false\n await this.#inputRunner\n .errorHandler(async (error) => {\n if (!isError(error) || !isInstanceOf(error, 'AbortError')) {\n inputFailed = true\n const err = new E_INPUT_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n this.#observabilityEmitter.emit('error', err)\n }\n })\n .finalHandler(async () => {\n inputReached = true\n })\n .run((fn, next) => Promise.resolve(fn(turnContext, next)))\n\n if (!inputReached && !inputFailed && !turnContext.aborted) {\n inputFailed = true\n const err = new E_PIPELINE_SHORT_CIRCUITED(['turn-input'])\n this.#observabilityEmitter.emit('error', err)\n }\n\n if (inputFailed || turnContext.aborted) {\n emitTurnEnd()\n return\n }\n\n // 2. LLM execution dispatch\n let dispatchFailed = false\n try {\n await DispatchRunner.dispatch({\n source: turnContext,\n executor: this.#config.executorCallback,\n turnInputPipeline: this.#config.dispatchInputPipeline,\n turnOutputPipeline: this.#config.dispatchOutputPipeline,\n observers: {\n dispatchStart: [\n (e) => {\n this.#observabilityEmitter.emit('dispatchStart', e)\n },\n ],\n dispatchEnd: [\n (e) => {\n this.#observabilityEmitter.emit('dispatchEnd', e)\n },\n ],\n iterationStart: [\n (e) => {\n this.#observabilityEmitter.emit('iterationStart', e)\n },\n ],\n iterationEnd: [\n (e) => {\n this.#observabilityEmitter.emit('iterationEnd', e)\n },\n ],\n log: [\n (e) => {\n this.#observabilityEmitter.emit('log', e)\n },\n ],\n },\n })\n } catch (err) {\n dispatchFailed = true\n const wrapped = isInstanceOf(err, 'BaseException') ? (err as InstanceType<typeof Error>) : err\n this.#observabilityEmitter.emit('error', wrapped as any)\n }\n\n if (dispatchFailed || turnContext.aborted) {\n emitTurnEnd()\n return\n }\n\n // 3. Output pipeline\n let outputFailed = false\n let outputReached = false\n await this.#outputRunner\n .errorHandler(async (error) => {\n if (!isError(error) || !isInstanceOf(error, 'AbortError')) {\n outputFailed = true\n const err = new E_OUTPUT_PIPELINE_ERROR({\n cause: isError(error) ? error : undefined,\n })\n this.#observabilityEmitter.emit('error', err)\n }\n })\n .finalHandler(async () => {\n outputReached = true\n })\n .run((fn, next) => Promise.resolve(fn(turnContext, next)))\n\n if (!outputReached && !outputFailed && !turnContext.aborted) {\n const err = new E_PIPELINE_SHORT_CIRCUITED(['turn-output'])\n this.#observabilityEmitter.emit('error', err)\n }\n\n emitTurnEnd()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiEA,IAAM,oBAAoB,UAAU,OAAoB;CACtD,IAAI,UAAU,OAAO,EAAE,SAAS;CAChC,QAAQ,UAAU,OAAO,EAAE,SAAS;CACpC,QAAQ,UAAU,OAAO,EAAE,SAAS;CACpC,SAAS,UAAU,IAAI,EAA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