@nhtio/adk 1.20260924.0 → 1.20260928.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (317) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/artifact_methods-Cg0go7Q4.mjs +1 -0
  3. package/artifact_methods-CxeKTocm.cjs +1 -0
  4. package/batteries/artifacts/ecmascript.cjs +1 -1
  5. package/batteries/artifacts/ecmascript.mjs +1 -1
  6. package/batteries/artifacts/toon.cjs +1 -1
  7. package/batteries/artifacts/toon.mjs +1 -1
  8. package/batteries/artifacts/xml.cjs +1 -1
  9. package/batteries/artifacts/xml.mjs +1 -1
  10. package/batteries/artifacts/yaml.cjs +1 -1
  11. package/batteries/artifacts/yaml.mjs +1 -1
  12. package/batteries/artifacts.cjs +4 -4
  13. package/batteries/artifacts.mjs +4 -4
  14. package/batteries/dev-tools/forge.cjs +3 -3
  15. package/batteries/dev-tools/forge.mjs +3 -3
  16. package/batteries/dev-tools.cjs +3 -3
  17. package/batteries/dev-tools.mjs +3 -3
  18. package/batteries/encoding.cjs +7 -7
  19. package/batteries/encoding.mjs +7 -7
  20. package/batteries/generation/gemini/adapter.cjs +1 -1
  21. package/batteries/generation/gemini/adapter.mjs +1 -1
  22. package/batteries/generation/local_diffusion/adapter.cjs +1 -1
  23. package/batteries/generation/local_diffusion/adapter.mjs +1 -1
  24. package/batteries/generation/openai/adapter.cjs +1 -1
  25. package/batteries/generation/openai/adapter.mjs +1 -1
  26. package/batteries/llm/anthropic_messages/adapter.cjs +6 -6
  27. package/batteries/llm/anthropic_messages/adapter.mjs +6 -6
  28. package/batteries/llm/anthropic_messages/count_tokens.cjs +1 -1
  29. package/batteries/llm/anthropic_messages/count_tokens.mjs +1 -1
  30. package/batteries/llm/anthropic_messages/helpers.cjs +3 -3
  31. package/batteries/llm/anthropic_messages/helpers.mjs +3 -3
  32. package/batteries/llm/anthropic_messages/validation.cjs +2 -2
  33. package/batteries/llm/anthropic_messages/validation.mjs +2 -2
  34. package/batteries/llm/anthropic_messages.cjs +2 -2
  35. package/batteries/llm/anthropic_messages.mjs +2 -2
  36. package/batteries/llm/bedrock_converse/adapter.cjs +162 -21
  37. package/batteries/llm/bedrock_converse/adapter.cjs.map +1 -1
  38. package/batteries/llm/bedrock_converse/adapter.mjs +162 -21
  39. package/batteries/llm/bedrock_converse/adapter.mjs.map +1 -1
  40. package/batteries/llm/bedrock_converse/helpers.cjs +1 -1
  41. package/batteries/llm/bedrock_converse/helpers.mjs +1 -1
  42. package/batteries/llm/bedrock_converse/validation.cjs +2 -2
  43. package/batteries/llm/bedrock_converse/validation.mjs +2 -2
  44. package/batteries/llm/bedrock_converse.cjs +2 -2
  45. package/batteries/llm/bedrock_converse.mjs +2 -2
  46. package/batteries/llm/claude_code_cli/adapter.cjs +66 -25
  47. package/batteries/llm/claude_code_cli/adapter.cjs.map +1 -1
  48. package/batteries/llm/claude_code_cli/adapter.mjs +66 -25
  49. package/batteries/llm/claude_code_cli/adapter.mjs.map +1 -1
  50. package/batteries/llm/claude_code_cli/helpers.cjs +3 -3
  51. package/batteries/llm/claude_code_cli/helpers.mjs +3 -3
  52. package/batteries/llm/claude_code_cli/line_queue.d.ts +39 -0
  53. package/batteries/llm/claude_code_cli/message_id_state.d.ts +48 -0
  54. package/batteries/llm/claude_code_cli/types.d.ts +76 -0
  55. package/batteries/llm/claude_code_cli/validation.cjs +5 -2
  56. package/batteries/llm/claude_code_cli/validation.cjs.map +1 -1
  57. package/batteries/llm/claude_code_cli/validation.mjs +5 -2
  58. package/batteries/llm/claude_code_cli/validation.mjs.map +1 -1
  59. package/batteries/llm/claude_code_cli/wire.cjs.map +1 -1
  60. package/batteries/llm/claude_code_cli/wire.d.ts +45 -1
  61. package/batteries/llm/claude_code_cli/wire.mjs.map +1 -1
  62. package/batteries/llm/claude_code_cli/wrapper.d.ts +5 -4
  63. package/batteries/llm/claude_code_cli.cjs +2 -2
  64. package/batteries/llm/claude_code_cli.mjs +2 -2
  65. package/batteries/llm/gemini_generate_content/adapter.cjs +160 -19
  66. package/batteries/llm/gemini_generate_content/adapter.cjs.map +1 -1
  67. package/batteries/llm/gemini_generate_content/adapter.mjs +160 -19
  68. package/batteries/llm/gemini_generate_content/adapter.mjs.map +1 -1
  69. package/batteries/llm/gemini_generate_content/helpers.cjs +1 -1
  70. package/batteries/llm/gemini_generate_content/helpers.mjs +1 -1
  71. package/batteries/llm/gemini_generate_content/validation.cjs +2 -2
  72. package/batteries/llm/gemini_generate_content/validation.mjs +2 -2
  73. package/batteries/llm/gemini_generate_content.cjs +1 -1
  74. package/batteries/llm/gemini_generate_content.mjs +1 -1
  75. package/batteries/llm/litert_lm/adapter.cjs +6 -6
  76. package/batteries/llm/litert_lm/adapter.mjs +6 -6
  77. package/batteries/llm/litert_lm/helpers.cjs +3 -3
  78. package/batteries/llm/litert_lm/helpers.mjs +3 -3
  79. package/batteries/llm/litert_lm/validation.cjs +2 -2
  80. package/batteries/llm/litert_lm/validation.mjs +2 -2
  81. package/batteries/llm/litert_lm.cjs +1 -1
  82. package/batteries/llm/litert_lm.mjs +1 -1
  83. package/batteries/llm/ollama/adapter.cjs +6 -6
  84. package/batteries/llm/ollama/adapter.mjs +6 -6
  85. package/batteries/llm/ollama/helpers.cjs +4 -4
  86. package/batteries/llm/ollama/helpers.mjs +4 -4
  87. package/batteries/llm/ollama/validation.cjs +2 -2
  88. package/batteries/llm/ollama/validation.mjs +2 -2
  89. package/batteries/llm/ollama.cjs +2 -2
  90. package/batteries/llm/ollama.mjs +2 -2
  91. package/batteries/llm/openai_chat_completions/adapter.cjs +6 -6
  92. package/batteries/llm/openai_chat_completions/adapter.mjs +6 -6
  93. package/batteries/llm/openai_chat_completions/helpers.cjs +4 -4
  94. package/batteries/llm/openai_chat_completions/helpers.mjs +4 -4
  95. package/batteries/llm/openai_chat_completions/validation.cjs +2 -2
  96. package/batteries/llm/openai_chat_completions/validation.mjs +2 -2
  97. package/batteries/llm/openai_chat_completions.cjs +2 -2
  98. package/batteries/llm/openai_chat_completions.mjs +2 -2
  99. package/batteries/llm/openai_responses/adapter.cjs +6 -6
  100. package/batteries/llm/openai_responses/adapter.mjs +6 -6
  101. package/batteries/llm/openai_responses/helpers.cjs +3 -3
  102. package/batteries/llm/openai_responses/helpers.mjs +3 -3
  103. package/batteries/llm/openai_responses/validation.cjs +2 -2
  104. package/batteries/llm/openai_responses/validation.mjs +2 -2
  105. package/batteries/llm/openai_responses.cjs +2 -2
  106. package/batteries/llm/openai_responses.mjs +2 -2
  107. package/batteries/llm/transformers_js/adapter.cjs +6 -6
  108. package/batteries/llm/transformers_js/adapter.mjs +6 -6
  109. package/batteries/llm/transformers_js/helpers.cjs +3 -3
  110. package/batteries/llm/transformers_js/helpers.mjs +3 -3
  111. package/batteries/llm/transformers_js/validation.cjs +2 -2
  112. package/batteries/llm/transformers_js/validation.mjs +2 -2
  113. package/batteries/llm/transformers_js.cjs +1 -1
  114. package/batteries/llm/transformers_js.mjs +1 -1
  115. package/batteries/llm/webllm_chat_completions/adapter.cjs +6 -6
  116. package/batteries/llm/webllm_chat_completions/adapter.mjs +6 -6
  117. package/batteries/llm/webllm_chat_completions/helpers.cjs +1 -1
  118. package/batteries/llm/webllm_chat_completions/helpers.mjs +1 -1
  119. package/batteries/llm/webllm_chat_completions/validation.cjs +2 -2
  120. package/batteries/llm/webllm_chat_completions/validation.mjs +2 -2
  121. package/batteries/llm/webllm_chat_completions.cjs +2 -2
  122. package/batteries/llm/webllm_chat_completions.mjs +2 -2
  123. package/batteries/llm.cjs +2 -2
  124. package/batteries/llm.mjs +2 -2
  125. package/batteries/media/forge.cjs +4 -4
  126. package/batteries/media/forge.mjs +4 -4
  127. package/batteries/media/lint.cjs +1 -1
  128. package/batteries/media/lint.mjs +1 -1
  129. package/batteries/orchestration/dispatch_reasoner.cjs +4 -4
  130. package/batteries/orchestration/dispatch_reasoner.mjs +4 -4
  131. package/batteries/orchestration/executor.cjs +2 -2
  132. package/batteries/orchestration/executor.mjs +2 -2
  133. package/batteries/orchestration/forge.cjs +4 -4
  134. package/batteries/orchestration/forge.mjs +4 -4
  135. package/batteries/orchestration/validation.cjs +2 -2
  136. package/batteries/orchestration/validation.mjs +2 -2
  137. package/batteries/orchestration.cjs +4 -4
  138. package/batteries/orchestration.mjs +4 -4
  139. package/batteries/sandbox/js.cjs +1 -1
  140. package/batteries/sandbox/js.mjs +1 -1
  141. package/batteries/sandbox/tools.cjs +1 -1
  142. package/batteries/sandbox/tools.mjs +1 -1
  143. package/batteries/sandbox.cjs +3 -3
  144. package/batteries/sandbox.mjs +3 -3
  145. package/batteries/skills.cjs +9 -9
  146. package/batteries/skills.mjs +9 -9
  147. package/batteries/tools/_shared.cjs +1 -1
  148. package/batteries/tools/_shared.mjs +1 -1
  149. package/batteries/tools/color.cjs +2 -2
  150. package/batteries/tools/color.mjs +2 -2
  151. package/batteries/tools/comparison.cjs +2 -2
  152. package/batteries/tools/comparison.mjs +2 -2
  153. package/batteries/tools/data_structure.cjs +2 -2
  154. package/batteries/tools/data_structure.mjs +2 -2
  155. package/batteries/tools/datetime_extended.cjs +3 -3
  156. package/batteries/tools/datetime_extended.mjs +3 -3
  157. package/batteries/tools/datetime_math.cjs +3 -3
  158. package/batteries/tools/datetime_math.mjs +3 -3
  159. package/batteries/tools/encoding.cjs +2 -2
  160. package/batteries/tools/encoding.mjs +2 -2
  161. package/batteries/tools/formatting.cjs +2 -2
  162. package/batteries/tools/formatting.mjs +2 -2
  163. package/batteries/tools/geo_basics.cjs +2 -2
  164. package/batteries/tools/geo_basics.mjs +2 -2
  165. package/batteries/tools/math.cjs +2 -2
  166. package/batteries/tools/math.mjs +2 -2
  167. package/batteries/tools/memory.cjs +5 -5
  168. package/batteries/tools/memory.mjs +5 -5
  169. package/batteries/tools/parsing.cjs +3 -3
  170. package/batteries/tools/parsing.mjs +3 -3
  171. package/batteries/tools/retrievables.cjs +5 -5
  172. package/batteries/tools/retrievables.mjs +5 -5
  173. package/batteries/tools/scrapper.cjs +1 -1
  174. package/batteries/tools/scrapper.mjs +1 -1
  175. package/batteries/tools/searxng.cjs +1 -1
  176. package/batteries/tools/searxng.mjs +1 -1
  177. package/batteries/tools/standing_instructions.cjs +3 -3
  178. package/batteries/tools/standing_instructions.mjs +3 -3
  179. package/batteries/tools/statistics.cjs +3 -3
  180. package/batteries/tools/statistics.mjs +3 -3
  181. package/batteries/tools/string_processing.cjs +2 -2
  182. package/batteries/tools/string_processing.mjs +2 -2
  183. package/batteries/tools/structured_data.cjs +2 -2
  184. package/batteries/tools/structured_data.mjs +2 -2
  185. package/batteries/tools/text_analysis.cjs +3 -3
  186. package/batteries/tools/text_analysis.mjs +3 -3
  187. package/batteries/tools/text_comparison.cjs +2 -2
  188. package/batteries/tools/text_comparison.mjs +2 -2
  189. package/batteries/tools/time.cjs +3 -3
  190. package/batteries/tools/time.mjs +3 -3
  191. package/batteries/tools/unit_conversion.cjs +2 -2
  192. package/batteries/tools/unit_conversion.mjs +2 -2
  193. package/batteries/tools.cjs +2 -2
  194. package/batteries/tools.mjs +2 -2
  195. package/batteries/validation.cjs +4 -4
  196. package/batteries/validation.mjs +4 -4
  197. package/batteries/vector/conformance.cjs +59 -0
  198. package/batteries/vector/conformance.cjs.map +1 -1
  199. package/batteries/vector/conformance.mjs +59 -0
  200. package/batteries/vector/conformance.mjs.map +1 -1
  201. package/batteries/vector/lancedb.cjs +1 -1
  202. package/batteries/vector/lancedb.cjs.map +1 -1
  203. package/batteries/vector/lancedb.mjs +1 -1
  204. package/batteries/vector/lancedb.mjs.map +1 -1
  205. package/batteries/vector/retrievable.cjs +1 -1
  206. package/batteries/vector/retrievable.mjs +1 -1
  207. package/batteries/vector/sqlite_vec/index.d.ts +1 -1
  208. package/batteries/vector/sqlite_vec.cjs +19 -30
  209. package/batteries/vector/sqlite_vec.cjs.map +1 -1
  210. package/batteries/vector/sqlite_vec.mjs +20 -31
  211. package/batteries/vector/sqlite_vec.mjs.map +1 -1
  212. package/batteries.cjs +4 -4
  213. package/batteries.mjs +4 -4
  214. package/{chat_common-B7fvGTKv.cjs → chat_common-CNayzS1V.cjs} +2 -2
  215. package/{chat_common-B7fvGTKv.cjs.map → chat_common-CNayzS1V.cjs.map} +1 -1
  216. package/{chat_common-CeoHwSsz.mjs → chat_common-DKw8FDol.mjs} +2 -2
  217. package/{chat_common-CeoHwSsz.mjs.map → chat_common-DKw8FDol.mjs.map} +1 -1
  218. package/claude-code-cli-wrapper.cjs +104 -22
  219. package/claude-code-cli-wrapper.cjs.map +1 -1
  220. package/claude-code-cli-wrapper.mjs +104 -22
  221. package/claude-code-cli-wrapper.mjs.map +1 -1
  222. package/{common-7gCR3zQu.cjs → common-CqetsItm.cjs} +7 -7
  223. package/{common-7gCR3zQu.cjs.map → common-CqetsItm.cjs.map} +1 -1
  224. package/{common-B5maOoF_.mjs → common-oI1niK9Z.mjs} +7 -7
  225. package/{common-B5maOoF_.mjs.map → common-oI1niK9Z.mjs.map} +1 -1
  226. package/common.cjs +7 -7
  227. package/common.mjs +7 -7
  228. package/{dispatch_runner-DO7jo_gl.mjs → dispatch_runner-BZDXUe0G.mjs} +5 -5
  229. package/{dispatch_runner-DO7jo_gl.mjs.map → dispatch_runner-BZDXUe0G.mjs.map} +1 -1
  230. package/{dispatch_runner-FlriTyoq.cjs → dispatch_runner-DDUxXJC3.cjs} +5 -5
  231. package/{dispatch_runner-FlriTyoq.cjs.map → dispatch_runner-DDUxXJC3.cjs.map} +1 -1
  232. package/dispatch_runner.cjs +1 -1
  233. package/dispatch_runner.mjs +1 -1
  234. package/{ecmascript-bgwVyZG1.mjs → ecmascript-B9Z2C24U.mjs} +3 -3
  235. package/{ecmascript-bgwVyZG1.mjs.map → ecmascript-B9Z2C24U.mjs.map} +1 -1
  236. package/{ecmascript-BydSB03Y.cjs → ecmascript-BYfmjg7y.cjs} +3 -3
  237. package/{ecmascript-BydSB03Y.cjs.map → ecmascript-BYfmjg7y.cjs.map} +1 -1
  238. package/eslint/rules.cjs +1 -1
  239. package/eslint/rules.mjs +1 -1
  240. package/eslint.cjs +2 -2
  241. package/eslint.mjs +2 -2
  242. package/exceptions.cjs +1 -1
  243. package/exceptions.mjs +1 -1
  244. package/forge.cjs +2 -2
  245. package/forge.mjs +2 -2
  246. package/guards.cjs +7 -7
  247. package/guards.mjs +7 -7
  248. package/{helpers-Dcp4CrOz.cjs → helpers-DPlh_7Bn.cjs} +3 -3
  249. package/{helpers-Dcp4CrOz.cjs.map → helpers-DPlh_7Bn.cjs.map} +1 -1
  250. package/{helpers-C1T0DV8Q.mjs → helpers-mbn_EsDV.mjs} +3 -3
  251. package/{helpers-C1T0DV8Q.mjs.map → helpers-mbn_EsDV.mjs.map} +1 -1
  252. package/index.cjs +11 -11
  253. package/index.mjs +11 -11
  254. package/mcp/adk-docs-corpus.json +2 -2
  255. package/package.json +425 -425
  256. package/{retrievable-BBwiACtw.cjs → retrievable-Bq-O3k6r.cjs} +3 -3
  257. package/{retrievable-BBwiACtw.cjs.map → retrievable-Bq-O3k6r.cjs.map} +1 -1
  258. package/{retrievable-CrGKx4sc.mjs → retrievable-CXTAUuuv.mjs} +3 -3
  259. package/{retrievable-CrGKx4sc.mjs.map → retrievable-CXTAUuuv.mjs.map} +1 -1
  260. package/{scrapper-BibKj8qE.cjs → scrapper-B8xG9lTD.cjs} +4 -4
  261. package/{scrapper-BibKj8qE.cjs.map → scrapper-B8xG9lTD.cjs.map} +1 -1
  262. package/{scrapper-_JzgbLG5.mjs → scrapper-DiQ5FfDL.mjs} +4 -4
  263. package/{scrapper-_JzgbLG5.mjs.map → scrapper-DiQ5FfDL.mjs.map} +1 -1
  264. package/{searxng-D-nA2gEI.mjs → searxng-BFTJ6rTE.mjs} +4 -4
  265. package/{searxng-D-nA2gEI.mjs.map → searxng-BFTJ6rTE.mjs.map} +1 -1
  266. package/{searxng-C6xrLW-v.cjs → searxng-EJhWRnIE.cjs} +4 -4
  267. package/{searxng-C6xrLW-v.cjs.map → searxng-EJhWRnIE.cjs.map} +1 -1
  268. package/server.json +2 -2
  269. package/skills/adk-assembly/SKILL.md +2 -2
  270. package/{spooled_artifact-BLgbGT8b.cjs → spooled_artifact---DmicFW.cjs} +384 -384
  271. package/spooled_artifact---DmicFW.cjs.map +1 -0
  272. package/{spooled_artifact-BkOe4-j-.mjs → spooled_artifact-Bw_7swIp.mjs} +385 -385
  273. package/spooled_artifact-Bw_7swIp.mjs.map +1 -0
  274. package/spooled_artifact.cjs +2 -2
  275. package/spooled_artifact.mjs +2 -2
  276. package/{spooled_markdown_artifact-8zdejfcJ.cjs → spooled_markdown_artifact-Rjzj-kyh.cjs} +3 -3
  277. package/{spooled_markdown_artifact-8zdejfcJ.cjs.map → spooled_markdown_artifact-Rjzj-kyh.cjs.map} +1 -1
  278. package/{spooled_markdown_artifact-Dnl-lCGv.mjs → spooled_markdown_artifact-vd6eNtIP.mjs} +3 -3
  279. package/{spooled_markdown_artifact-Dnl-lCGv.mjs.map → spooled_markdown_artifact-vd6eNtIP.mjs.map} +1 -1
  280. package/{thought-BrQt6HAb.mjs → thought-CxSaF6Xf.mjs} +3 -3
  281. package/{thought-BrQt6HAb.mjs.map → thought-CxSaF6Xf.mjs.map} +1 -1
  282. package/{thought-COeZTQ-B.cjs → thought-Dp3sMWW6.cjs} +3 -3
  283. package/{thought-COeZTQ-B.cjs.map → thought-Dp3sMWW6.cjs.map} +1 -1
  284. package/{tokenizable-DDIdXbJN.cjs → tokenizable-BcodRtoW.cjs} +29 -29
  285. package/{tokenizable-DDIdXbJN.cjs.map → tokenizable-BcodRtoW.cjs.map} +1 -1
  286. package/{tokenizable-xPXj1AQX.mjs → tokenizable-VB4Av8GF.mjs} +30 -30
  287. package/{tokenizable-xPXj1AQX.mjs.map → tokenizable-VB4Av8GF.mjs.map} +1 -1
  288. package/{tool_call-JbjeUpRK.cjs → tool_call-B9px4W9k.cjs} +4 -4
  289. package/{tool_call-JbjeUpRK.cjs.map → tool_call-B9px4W9k.cjs.map} +1 -1
  290. package/{tool_call-8crmZsO8.mjs → tool_call-Cfaj-6zK.mjs} +4 -4
  291. package/{tool_call-8crmZsO8.mjs.map → tool_call-Cfaj-6zK.mjs.map} +1 -1
  292. package/{tools-BC4NJqZD.mjs → tools-D0MBDh2R.mjs} +6 -6
  293. package/{tools-BC4NJqZD.mjs.map → tools-D0MBDh2R.mjs.map} +1 -1
  294. package/{tools-D4mdzi0a.cjs → tools-aNbi6JyA.cjs} +6 -6
  295. package/{tools-D4mdzi0a.cjs.map → tools-aNbi6JyA.cjs.map} +1 -1
  296. package/{toon-BA9Q7NHG.mjs → toon-BSTQnHed.mjs} +5 -5
  297. package/{toon-BA9Q7NHG.mjs.map → toon-BSTQnHed.mjs.map} +1 -1
  298. package/{toon-b-0pFKZ8.cjs → toon-DmLwZ6H1.cjs} +5 -5
  299. package/{toon-b-0pFKZ8.cjs.map → toon-DmLwZ6H1.cjs.map} +1 -1
  300. package/{turn_runner-BmVXcBZ2.mjs → turn_runner-BHHD6h77.mjs} +5 -5
  301. package/{turn_runner-BmVXcBZ2.mjs.map → turn_runner-BHHD6h77.mjs.map} +1 -1
  302. package/{turn_runner-DX-3s3ih.cjs → turn_runner-Dj7JsUTQ.cjs} +5 -5
  303. package/{turn_runner-DX-3s3ih.cjs.map → turn_runner-Dj7JsUTQ.cjs.map} +1 -1
  304. package/turn_runner.cjs +1 -1
  305. package/turn_runner.mjs +1 -1
  306. package/{xml-B1JIGLpU.mjs → xml-CYseDztH.mjs} +5 -5
  307. package/{xml-B1JIGLpU.mjs.map → xml-CYseDztH.mjs.map} +1 -1
  308. package/{xml-fvwTsoRv.cjs → xml-zJul8jMQ.cjs} +5 -5
  309. package/{xml-fvwTsoRv.cjs.map → xml-zJul8jMQ.cjs.map} +1 -1
  310. package/{yaml-1mP4uxdf.mjs → yaml-BPBoiOjx.mjs} +5 -5
  311. package/{yaml-1mP4uxdf.mjs.map → yaml-BPBoiOjx.mjs.map} +1 -1
  312. package/{yaml-DPUTumla.cjs → yaml-D0PzoRAr.cjs} +5 -5
  313. package/{yaml-DPUTumla.cjs.map → yaml-D0PzoRAr.cjs.map} +1 -1
  314. package/artifact_methods-7KatxCSd.cjs +0 -1
  315. package/artifact_methods-q52ETLwI.mjs +0 -1
  316. package/spooled_artifact-BLgbGT8b.cjs.map +0 -1
  317. package/spooled_artifact-BkOe4-j-.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"turn_runner-DX-3s3ih.cjs","names":["#id","#turnId","#reason","#payload","#createdAt","#settled","#schema","#controller","#promise","#resolve","#reject","#config","#inputPipeline","#outputPipeline","#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 /** Unique identifier for this gate instance. */\n declare readonly id: string\n /** Id of the turn this gate belongs to. */\n declare readonly turnId: string\n /** Human-readable reason the gate was opened. */\n declare readonly reason: string\n /** Optional caller-supplied payload describing what the gate is waiting on. */\n declare readonly payload: unknown\n /** When the gate was created. */\n declare readonly createdAt: DateTime\n /** Whether the gate has been settled (resolved or rejected) and no longer blocks the turn. */\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 ToolCallGroupReplaceFn,\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 /** Optionally replaces a complete tool-call group atomically. */\n replaceToolCallGroupCallback?: ToolCallGroupReplaceFn\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 replaceToolCallGroupCallback: validator.function().arity(3).optional(),\n storeMediaBytesCallback: validator.function().arity(3).required(),\n storeRetrievableBytesCallback: validator.function().arity(3).required(),\n tools: validator\n .array()\n .items(\n // `.optional()`, not `.required()`: this `.any()` is a type-argument inside `items(...)`,\n // describing what a tool element looks like — it must NOT impose array cardinality. A\n // `.required()` item turns the array into `array.includesRequiredUnknowns` (\"must contain\n // ≥1 tool\"), which contradicts the contract above (`tools` is optional, defaults to `[]`).\n // `.optional()` satisfies adk/require-validator-any-required by declaring disposition\n // explicitly while leaving the empty-array default valid.\n validator\n .any()\n .optional()\n .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 { runWithEstimationWarnings } from './utils/estimation_context'\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 { RawTurnGate } from './classes/turn_gate'\nimport type { WarningEvent } from './types/dispatch_runner'\nimport type { EstimationWarning } from './utils/estimation_context'\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 #inputPipeline: Middleware<TurnPipelineMiddlewareFn>\n #outputPipeline: Middleware<TurnPipelineMiddlewareFn>\n #functionalEmitter: TypedEventEmitter<TurnEvents>\n #observabilityEmitter: TypedEventEmitter<TurnObservabilityEvents>\n\n /**\n * @param config - Construction-time configuration validated against the turn-runner config schema.\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, {\n abortEarly: false,\n })\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 // Hold the Middleware; derive a fresh Runner per turn (a Runner's internal cursor never\n // resets across .run() calls, so caching one here would only execute the pipeline once).\n this.#inputPipeline = turnInputPipeline\n this.#outputPipeline = turnOutputPipeline\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 replaceToolCallGroup: this.#config.replaceToolCallGroupCallback,\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 // Publish a turn-level warn-sink for the duration of the run so a token estimation done directly in a\n // TURN pipeline (outside any dispatch) can degrade-and-warn instead of throwing. A nested\n // DispatchRunner.dispatch() pushes its own sink on top (see estimation_context), so estimations inside\n // a dispatch route to the richer dispatch-scoped sink and this turn-level one is the fallback. No\n // dispatchId/iteration here — those belong to a dispatch scope, not the turn.\n const emitEstimationWarning = (w: EstimationWarning): void => {\n const event: WarningEvent = {\n emittedAt: DateTime.now(),\n source: 'turn-runner',\n kind: 'token-estimation-degraded',\n message: `token estimation for encoding \"${String(w.encoding)}\" failed; fell back to a char-based estimate`,\n error: w.error,\n payload: { encoding: w.encoding, textPreview: w.textPreview },\n }\n this.#observabilityEmitter.emit('warning', event)\n }\n\n await runWithEstimationWarnings(emitEstimationWarning, async () => {\n const startedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnStart', {\n turnId: turnContext.id,\n startedAt,\n })\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.#inputPipeline\n .runner()\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 // Re-forward a DispatchRunner-emitted `warning` (e.g. token-estimation degraded) up to the turn\n // bus, so a consumer subscribed only to the TurnRunner still sees it — mirrors the log/dispatch*\n // bridges above. Non-fatal; the dispatch continues.\n warning: [\n (e) => {\n this.#observabilityEmitter.emit('warning', e)\n },\n ],\n },\n })\n } catch (err) {\n dispatchFailed = true\n const wrapped = isInstanceOf(err, 'BaseException')\n ? (err as InstanceType<typeof Error>)\n : 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.#outputPipeline\n .runner()\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}\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,SA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e,IAC5C,MACD;IACJ,KAAKA,sBAAsB,KAAK,SAAS,OAAc;GACzD;GAEA,IAAI,kBAAkB,YAAY,SAAS;IACzC,YAAY;IACZ;GACF;GAGA,IAAI,eAAe;GACnB,IAAI,gBAAgB;GACpB,MAAM,KAAKF,gBACR,OAAO,EACP,aAAa,OAAO,UAAU;IAC7B,IAAI,CAAC,eAAA,QAAQ,KAAK,KAAK,CAAC,eAAA,aAAa,OAAO,YAAY,GAAG;KACzD,eAAe;KACf,MAAM,MAAM,IAAI,oBAAA,wBAAwB,EACtC,OAAO,eAAA,QAAQ,KAAK,IAAI,QAAQ,KAAA,EAClC,CAAC;KACD,KAAKE,sBAAsB,KAAK,SAAS,GAAG;IAC9C;GACF,CAAC,EACA,aAAa,YAAY;IACxB,gBAAgB;GAClB,CAAC,EACA,KAAK,IAAI,SAAS,QAAQ,QAAQ,GAAG,aAAa,IAAI,CAAC,CAAC;GAE3D,IAAI,CAAC,iBAAiB,CAAC,gBAAgB,CAAC,YAAY,SAAS;IAC3D,MAAM,MAAM,IAAI,oBAAA,2BAA2B,CAAC,aAAa,CAAC;IAC1D,KAAKA,sBAAsB,KAAK,SAAS,GAAG;GAC9C;GAEA,YAAY;EACd,CAAC;CACH;AACF"}
1
+ {"version":3,"file":"turn_runner-Dj7JsUTQ.cjs","names":["#id","#turnId","#reason","#payload","#createdAt","#settled","#schema","#controller","#promise","#resolve","#reject","#config","#inputPipeline","#outputPipeline","#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 /** Unique identifier for this gate instance. */\n declare readonly id: string\n /** Id of the turn this gate belongs to. */\n declare readonly turnId: string\n /** Human-readable reason the gate was opened. */\n declare readonly reason: string\n /** Optional caller-supplied payload describing what the gate is waiting on. */\n declare readonly payload: unknown\n /** When the gate was created. */\n declare readonly createdAt: DateTime\n /** Whether the gate has been settled (resolved or rejected) and no longer blocks the turn. */\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 ToolCallGroupReplaceFn,\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 /** Optionally replaces a complete tool-call group atomically. */\n replaceToolCallGroupCallback?: ToolCallGroupReplaceFn\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 replaceToolCallGroupCallback: validator.function().arity(3).optional(),\n storeMediaBytesCallback: validator.function().arity(3).required(),\n storeRetrievableBytesCallback: validator.function().arity(3).required(),\n tools: validator\n .array()\n .items(\n // `.optional()`, not `.required()`: this `.any()` is a type-argument inside `items(...)`,\n // describing what a tool element looks like — it must NOT impose array cardinality. A\n // `.required()` item turns the array into `array.includesRequiredUnknowns` (\"must contain\n // ≥1 tool\"), which contradicts the contract above (`tools` is optional, defaults to `[]`).\n // `.optional()` satisfies adk/require-validator-any-required by declaring disposition\n // explicitly while leaving the empty-array default valid.\n validator\n .any()\n .optional()\n .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 { runWithEstimationWarnings } from './utils/estimation_context'\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 { RawTurnGate } from './classes/turn_gate'\nimport type { WarningEvent } from './types/dispatch_runner'\nimport type { EstimationWarning } from './utils/estimation_context'\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 #inputPipeline: Middleware<TurnPipelineMiddlewareFn>\n #outputPipeline: Middleware<TurnPipelineMiddlewareFn>\n #functionalEmitter: TypedEventEmitter<TurnEvents>\n #observabilityEmitter: TypedEventEmitter<TurnObservabilityEvents>\n\n /**\n * @param config - Construction-time configuration validated against the turn-runner config schema.\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, {\n abortEarly: false,\n })\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 // Hold the Middleware; derive a fresh Runner per turn (a Runner's internal cursor never\n // resets across .run() calls, so caching one here would only execute the pipeline once).\n this.#inputPipeline = turnInputPipeline\n this.#outputPipeline = turnOutputPipeline\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 replaceToolCallGroup: this.#config.replaceToolCallGroupCallback,\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 // Publish a turn-level warn-sink for the duration of the run so a token estimation done directly in a\n // TURN pipeline (outside any dispatch) can degrade-and-warn instead of throwing. A nested\n // DispatchRunner.dispatch() pushes its own sink on top (see estimation_context), so estimations inside\n // a dispatch route to the richer dispatch-scoped sink and this turn-level one is the fallback. No\n // dispatchId/iteration here — those belong to a dispatch scope, not the turn.\n const emitEstimationWarning = (w: EstimationWarning): void => {\n const event: WarningEvent = {\n emittedAt: DateTime.now(),\n source: 'turn-runner',\n kind: 'token-estimation-degraded',\n message: `token estimation for encoding \"${String(w.encoding)}\" failed; fell back to a char-based estimate`,\n error: w.error,\n payload: { encoding: w.encoding, textPreview: w.textPreview },\n }\n this.#observabilityEmitter.emit('warning', event)\n }\n\n await runWithEstimationWarnings(emitEstimationWarning, async () => {\n const startedAt = DateTime.now()\n this.#observabilityEmitter.emit('turnStart', {\n turnId: turnContext.id,\n startedAt,\n })\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.#inputPipeline\n .runner()\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 // Re-forward a DispatchRunner-emitted `warning` (e.g. token-estimation degraded) up to the turn\n // bus, so a consumer subscribed only to the TurnRunner still sees it — mirrors the log/dispatch*\n // bridges above. Non-fatal; the dispatch continues.\n warning: [\n (e) => {\n this.#observabilityEmitter.emit('warning', e)\n },\n ],\n },\n })\n } catch (err) {\n dispatchFailed = true\n const wrapped = isInstanceOf(err, 'BaseException')\n ? (err as InstanceType<typeof Error>)\n : 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.#outputPipeline\n .runner()\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}\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,eAAA,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;;;;;;;;;;;;;;;;AAiB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a,CAAC;IAC1D,KAAKA,sBAAsB,KAAK,SAAS,GAAG;GAC9C;GAEA,YAAY;EACd,CAAC;CACH;AACF"}
package/turn_runner.cjs CHANGED
@@ -1,4 +1,4 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  require("./chunk-Cek0wNdY.cjs");
3
- const require_turn_runner = require("./turn_runner-DX-3s3ih.cjs");
3
+ const require_turn_runner = require("./turn_runner-Dj7JsUTQ.cjs");
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-BmVXcBZ2.mjs";
1
+ import { t as TurnRunner } from "./turn_runner-BHHD6h77.mjs";
2
2
  export { TurnRunner };
@@ -1,13 +1,13 @@
1
1
  import { t as createException } from "./exceptions-DRYLe-J4.mjs";
2
2
  import { n as isInstanceOf, r as isObject, t as isError } from "./guards-BEpY7lBI.mjs";
3
- import { a as resolveArtifactById, d as ArtifactTool, f as Tool, l as resolveSpoolReader, n as collectArtifactCompatibleIds, r as defaultSerialise, t as SpooledArtifact } from "./spooled_artifact-BkOe4-j-.mjs";
4
- import "./common-B5maOoF_.mjs";
5
- import { n as SpooledJsonArtifact } from "./spooled_markdown_artifact-Dnl-lCGv.mjs";
3
+ import { a as resolveArtifactById, f as ArtifactTool, l as resolveSpoolReader, n as collectArtifactCompatibleIds, p as Tool, r as defaultSerialise, t as SpooledArtifact } from "./spooled_artifact-Bw_7swIp.mjs";
4
+ import "./common-oI1niK9Z.mjs";
5
+ import { n as SpooledJsonArtifact } from "./spooled_markdown_artifact-vd6eNtIP.mjs";
6
6
  import "./factories.mjs";
7
7
  import "./guards.mjs";
8
8
  import "./spooled_artifact.mjs";
9
- import { v6 } from "uuid";
10
9
  import { validator } from "@nhtio/validation";
10
+ import { v6 } from "uuid";
11
11
  import { JSONPath } from "jsonpath-plus";
12
12
  //#region src/batteries/artifacts/xml/exceptions.ts
13
13
  /**
@@ -555,4 +555,4 @@ var jsonToXmlTool = new Tool({
555
555
  //#endregion
556
556
  export { E_XML_PARSE_FAILED as a, E_XML_PARSER_PEER_MISSING as i, jsonToXmlTool as n, xmlToJsonTool as r, SpooledXmlArtifact as t };
557
557
 
558
- //# sourceMappingURL=xml-B1JIGLpU.mjs.map
558
+ //# sourceMappingURL=xml-CYseDztH.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"xml-B1JIGLpU.mjs","names":["#attributeNamePrefix","#ignoreAttributes","#resolveParsed","#parsed"],"sources":["../src/batteries/artifacts/xml/exceptions.ts","../src/batteries/artifacts/xml/index.ts"],"sourcesContent":["/**\n * Battery-scoped exceptions for the XML artifact battery.\n *\n * @remarks\n * Internal sibling of the `@nhtio/adk/batteries/artifacts/xml` entry — re-exported from the battery's\n * own barrel per the battery-scoped-exceptions rule. These are the typed errors the\n * implementor-facing API throws; the agent-facing forge catches them and renders readable\n * failure strings the model can act on.\n */\n\nimport { createException } from '@nhtio/adk/factories'\n\n/**\n * Thrown when the fast-xml-parser optional peer is not installed or fails to load.\n *\n * @remarks\n * The message template includes the package name, a description of its purpose, the underlying\n * error, and the exact install command, so the consumer sees a complete, actionable message\n * regardless of call site.\n */\nexport const E_XML_PARSER_PEER_MISSING = createException<[string]>(\n 'E_XML_PARSER_PEER_MISSING',\n 'the XML battery could not load its peer dependency \"fast-xml-parser\" (needed for XML format artifact queries): %s — install it (pnpm add fast-xml-parser)',\n 'E_XML_PARSER_PEER_MISSING',\n 500,\n true\n)\n\n/**\n * Thrown when XML parsing fails due to malformed markup.\n *\n * @remarks\n * Printf args: `[errorDetail]` — includes the parser's own reason for the failure.\n */\nexport const E_XML_PARSE_FAILED = createException<[string]>(\n 'E_XML_PARSE_FAILED',\n 'XML parse failed: %s',\n 'E_XML_PARSE_FAILED',\n 422,\n false\n)\n","/**\n * A structured artifact battery for XML documents.\n *\n * @module @nhtio/adk/batteries/artifacts/xml\n *\n * @remarks\n * Provides {@link SpooledXmlArtifact} — a `SpooledArtifact` specialisation that parses XML\n * into a JSON projection and offers path-based query tools over that projection. The XML-to-JSON\n * mapping defaults to `ignoreAttributes: false` and `attributeNamePrefix: '_'`, both settable\n * per instance through the constructor; `preserveOrder: false` is fixed. Under the default\n * mapping:\n *\n * - Element attributes become keys prefixed with `_` (e.g., `root-element` with `href=\"x\"`\n * becomes `{ a: { _href: 'x', ... } }`).\n * - Element text content becomes a `#text` key when the element also has attributes or siblings.\n * - Repeated sibling elements collapse into an array.\n * - The full projection is queryable via JSONPath expressions (e.g., `$..name` finds all name\n * elements anywhere in the tree). Attributes are accessed via underscore-prefixed keys,\n * e.g. `$..[\"_href\"]` for the href attribute (recursive descent).\n *\n * The battery also exports two converter `Tool` constants: `xmlToJsonTool` and `jsonToXmlTool`.\n * These accept either inline XML/JSON text or a reference to an artifact produced earlier in\n * the turn, and return the converted result as a new `SpooledJsonArtifact` or\n * `SpooledXmlArtifact`.\n *\n * Battery exceptions are defined in this module's `exceptions.ts` file — `createException`\n * re-exported from `@nhtio/adk/factories`. Decoding a {@link SpooledXmlArtifact} instance via\n * `decode()` throws until `registerArtifactEncodables()` has run (see\n * {@link @nhtio/adk/batteries/artifacts!registerArtifactEncodables}).\n */\n\nimport { v6 as uuidv6 } from 'uuid'\nimport { JSONPath } from 'jsonpath-plus'\nimport { validator } from '@nhtio/validation'\nimport { resolveSpoolReader } from '@nhtio/adk/common'\nimport { SpooledJsonArtifact } from '@nhtio/adk/common'\nimport { isInstanceOf, isError, isObject } from '@nhtio/adk/guards'\nimport { E_XML_PARSER_PEER_MISSING, E_XML_PARSE_FAILED } from './exceptions'\nimport { ArtifactTool, Tool, ToolRegistry, ReaderDescriptor } from '@nhtio/adk/common'\n\n// Well-known @nhtio/encoder contract keys, resolved through the global symbol registry.\n// These are identical to the symbols core uses, with no import edge on the optional peer.\nconst ENCODE_METHOD: unique symbol = Symbol.for('@nhtio/encoder:toEncoded')\nconst DECODE_METHOD: unique symbol = Symbol.for('@nhtio/encoder:fromEncoded')\nimport {\n SpooledArtifact,\n collectArtifactCompatibleIds,\n resolveArtifactById,\n defaultSerialise,\n} from '@nhtio/adk/spooled_artifact'\nimport type { SpoolReader } from '@nhtio/adk/types'\nimport type { XMLParser, XMLBuilder } from 'fast-xml-parser'\nimport type { ToolMethodDescriptor, DispatchContext } from '@nhtio/adk/types'\n\n/** Snapshot payload for the encoder contract; the encoder treats it as opaque. */\ntype AdkEncodableSnapshot = unknown\n\n/**\n * Lazy-loaded promise for the `fast-xml-parser` module, cached at module scope.\n */\nlet xmlParserPromise:\n | Promise<{ XMLParser: typeof XMLParser; XMLBuilder: typeof XMLBuilder }>\n | undefined\n\n/**\n * Lazily import and cache the `fast-xml-parser` module with battery-scoped error handling.\n *\n * @returns The imported module.\n * @throws {@link E_XML_PARSER_PEER_MISSING} when the module is unavailable.\n */\nasync function getXmlParser(): Promise<{\n XMLParser: typeof XMLParser\n XMLBuilder: typeof XMLBuilder\n}> {\n xmlParserPromise ??= import('fast-xml-parser').catch((err) => {\n const detail = isError(err) ? err.message : String(err)\n throw new E_XML_PARSER_PEER_MISSING([detail])\n })\n return xmlParserPromise\n}\n\n/**\n * A {@link @nhtio/adk!SpooledArtifact} specialisation that adds XML-aware read operations.\n *\n * @remarks\n * The artifact parses XML into a JSON projection on first access and caches it for the\n * lifetime of the instance. The projection uses `ignoreAttributes` and `attributeNamePrefix` as\n * supplied to the constructor — defaulting to `false` and `'_'` — with `preserveOrder: false`.\n *\n * Under this mapping, an XML element like:\n *\n * `root-element` with an `href` attribute and text content becomes a JSON object like:\n * `{ root: { element: { _href: 'value', '#text': 'content' } } }`\n *\n * Attributes are prefixed with `_` by default rather than the conventional `@_`, because\n * `jsonpath-plus` reads a leading `@` in a path segment as its type-selector sigil before\n * honouring quotes: `$..[\"@_href\"]` throws `Unknown value type _hr`, while `$..[\"_href\"]`\n * matches. Text nodes use the `#text` key.\n *\n * All XML methods are async, consistent with {@link @nhtio/adk!SpooledArtifact}.\n *\n * Path-based methods (`xml_get`, `xml_filter`, `xml_pluck`) use\n * [JSONPath-Plus](https://github.com/JSONPath-Plus/JSONPath) expressions over the projection.\n * Full JSONPath syntax is supported, including recursive descent (`..`), filter expressions,\n * and union selectors.\n */\nexport class SpooledXmlArtifact extends SpooledArtifact {\n #parsed: Record<string, unknown> | undefined\n #attributeNamePrefix: string\n #ignoreAttributes: boolean\n\n /**\n * @param reader - The backing store to read from.\n * @param options - Optional parser configuration.\n * @param options.attributeNamePrefix - Prefix for attribute keys (default: '_'). Set to '@_'\n * if you need the conventional XML-to-JSON mapping, but be aware that naming such a key in a\n * JSONPath segment fails — `$..[\"@_attr\"]` throws `Unknown value type _at`, and quoting does\n * not escape it. A filter expression still reaches it (`$..[?(@['@_attr'])]`); a wildcard\n * does too, but only when placed exactly one level above the key, so the working path\n * depends on whether repeated elements collapsed into an array.\n * @param options.ignoreAttributes - When true, ignore element attributes (default: false).\n */\n constructor(\n reader: SpoolReader,\n options?: {\n attributeNamePrefix?: string\n ignoreAttributes?: boolean\n }\n ) {\n super(reader)\n this.#attributeNamePrefix = options?.attributeNamePrefix ?? '_'\n this.#ignoreAttributes = options?.ignoreAttributes ?? false\n }\n\n /**\n * Returns `true` if `value` is a {@link SpooledXmlArtifact} instance.\n *\n * @remarks\n * Uses the cross-realm-safe {@link @nhtio/adk!isInstanceOf} guard. Safe against the\n * dual-module-copy case where two distinct `SpooledXmlArtifact` classes coexist in the same\n * realm.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link SpooledXmlArtifact} instance.\n */\n public static isSpooledXmlArtifact(value: unknown): value is SpooledXmlArtifact {\n return isInstanceOf(value, 'SpooledXmlArtifact', SpooledXmlArtifact)\n }\n\n /**\n * Returns the effective XML-to-JSON parser configuration for this artifact.\n *\n * @remarks\n * When converting an XML artifact to JSON by call_id, the converter inherits the source\n * artifact's attribute prefix and ignoreAttributes setting. This accessor exposes those\n * options so the converter can apply them consistently.\n *\n * @returns An object with `attributeNamePrefix` and `ignoreAttributes` keys.\n */\n public getParserOptions(): {\n attributeNamePrefix: string\n ignoreAttributes: boolean\n } {\n return {\n attributeNamePrefix: this.#attributeNamePrefix,\n ignoreAttributes: this.#ignoreAttributes,\n }\n }\n\n /**\n * The XML-specific artifact-query descriptors this class adds on top of the base set.\n *\n * @remarks\n * Lists `artifact_xml_root`, `artifact_xml_keys`, `artifact_xml_tags`, `artifact_xml_length`,\n * `artifact_xml_get`, `artifact_xml_filter`, `artifact_xml_pluck`. The base seven descriptors\n * (`artifact_head`, etc.) are NOT included here — they are forged separately by\n * {@link SpooledXmlArtifact.forgeTools}.\n */\n public static toolMethods: ReadonlyArray<ToolMethodDescriptor> = Object.freeze([\n {\n name: 'artifact_xml_root',\n method: 'xml_root',\n description: 'The root element name of the XML document produced earlier in this turn.',\n },\n {\n name: 'artifact_xml_keys',\n method: 'xml_keys',\n description:\n 'Keys directly under the root element of the XML document produced earlier in this turn.',\n },\n {\n name: 'artifact_xml_tags',\n method: 'xml_tags',\n description:\n 'Every distinct element name in the XML document produced earlier in this turn, deduplicated. ' +\n 'Call this before writing a path to an unfamiliar document — it tells you what elements are present.',\n },\n {\n name: 'artifact_xml_length',\n method: 'xml_length',\n description:\n 'Element count when the root element contains an array of children; otherwise 1. ' +\n 'The XML document was produced earlier in this turn.',\n },\n {\n name: 'artifact_xml_get',\n method: 'xml_get',\n argsSchema: validator.object({\n path: validator\n .string()\n .required()\n .description(\n 'JSONPath expression to query the document. Attributes appear with a leading underscore (e.g., _href). Use bracket notation for recursive descent: $..[\"_href\"].'\n ),\n }),\n description:\n 'Query the XML document via JSONPath. The document was produced earlier in this turn. ' +\n 'Attributes appear as underscore-prefixed keys (e.g., _href for an href attribute). Use bracket notation in recursive-descent queries: $..[\"_href\"].',\n },\n {\n name: 'artifact_xml_filter',\n method: 'xml_filter',\n argsSchema: validator.object({\n path: validator\n .string()\n .required()\n .description(\n 'JSONPath expression to filter the document. Attributes appear with a leading underscore (e.g., _href).'\n ),\n }),\n description:\n 'Return XML elements whose content matches a JSONPath filter. Differs from artifact_xml_get: get returns matched values; filter returns the element objects containing them. The document was produced earlier in this turn. Attributes appear as underscore-prefixed keys (e.g., _href).',\n },\n {\n name: 'artifact_xml_pluck',\n method: 'xml_pluck',\n argsSchema: validator.object({\n path: validator\n .string()\n .required()\n .description(\n 'JSONPath expression to pluck values. Attributes appear with a leading underscore (e.g., _href).'\n ),\n }),\n description:\n 'Alias for artifact_xml_get — extract values matching a JSONPath. The document was produced earlier in this turn. ' +\n 'Attributes appear as underscore-prefixed keys (e.g., _href).',\n },\n ])\n\n /**\n * The root element name of the XML document.\n *\n * @returns The name of the root element.\n * @throws Error when the document is malformed or empty.\n */\n async xml_root(): Promise<string> {\n const parsed = await this.#resolveParsed()\n const keys = Object.keys(parsed)\n if (keys.length === 0) {\n throw new Error('XML document is empty')\n }\n return keys[0]\n }\n\n /**\n * Keys directly under the root element.\n *\n * @returns Array of key names at the root level.\n */\n async xml_keys(): Promise<string[]> {\n const parsed = await this.#resolveParsed()\n const rootKey = Object.keys(parsed)[0]\n if (!rootKey) return []\n const rootContent = parsed[rootKey]\n if (!isObject(rootContent)) return []\n return Object.keys(rootContent)\n }\n\n /**\n * Every distinct element name in the document, deduplicated.\n *\n * @remarks\n * Walks the entire projection recursively, excluding attribute keys (prefixed with the\n * configured `attributeNamePrefix`, default `_`) and `#text` keys. This is what a model\n * calls before it can write a path into an unfamiliar document.\n *\n * @returns Sorted array of unique element names.\n */\n async xml_tags(): Promise<string[]> {\n const parsed = await this.#resolveParsed()\n const tags = new Set<string>()\n const attributePrefix = this.#attributeNamePrefix\n\n function walk(obj: unknown): void {\n if (!isObject(obj)) return\n for (const [key, value] of Object.entries(obj)) {\n // Skip attribute keys and text nodes\n if (key.startsWith(attributePrefix) || key === '#text') {\n continue\n }\n tags.add(key)\n if (Array.isArray(value)) {\n for (const item of value) {\n walk(item)\n }\n } else {\n walk(value)\n }\n }\n }\n\n walk(parsed)\n return Array.from(tags).sort()\n }\n\n /**\n * Element count when the root contains an array of children; otherwise 1.\n *\n * @returns Number of elements.\n */\n async xml_length(): Promise<number> {\n const parsed = await this.#resolveParsed()\n const rootKey = Object.keys(parsed)[0]\n if (!rootKey) return 0\n const rootContent = parsed[rootKey]\n if (Array.isArray(rootContent)) {\n return rootContent.length\n }\n return 1\n }\n\n /**\n * Query the document via JSONPath expression.\n *\n * @param path - A JSONPath expression (e.g., `'$..name'`).\n * @returns Array of matched values.\n */\n async xml_get(path: string): Promise<unknown[]> {\n const parsed = await this.#resolveParsed()\n const results = JSONPath({ path, json: parsed })\n return results\n }\n\n /**\n * Returns the elements (subtrees) that match a JSONPath expression.\n *\n * @remarks\n * Evaluates the path against the XML projection and returns the elements that\n * contain matching values. Unlike xml_get (which returns matched values), xml_filter\n * returns the element objects containing those matches.\n *\n * Candidate set definition for XML's single-rooted projection:\n * - If the root element contains an array of repeated siblings (e.g., root.item\n * where item is an array property), filters across those siblings and returns\n * elements that have matching content.\n * - If the root element contains a single object, evaluates the path against it\n * and returns it when matched.\n *\n * The path is evaluated using JSONPath-Plus with resultType 'all' to extract\n * parent elements of matched values. The immediate parent object of any matched\n * value is included in the result, deduplicating elements.\n *\n * Example: for XML with root containing multiple 'item' elements each with an\n * 'id' attribute, xml_filter('$.root.item[*]._id') returns the item elements\n * that have an id attribute, whereas xml_get would return the id values themselves.\n *\n * @param path - A JSONPath expression (e.g. '$.root.item[*]._id' or '$[?(@.status)]').\n * @returns Array of matching element subtrees. Empty array when no matches found.\n */\n async xml_filter(path: string): Promise<unknown[]> {\n const parsed = await this.#resolveParsed()\n const rootKey = Object.keys(parsed)[0]\n if (!rootKey) return []\n\n const rootContent = parsed[rootKey]\n\n // If the root content is an array of siblings, filter the array elements\n if (Array.isArray(rootContent)) {\n // Evaluate the path against each sibling element to see if it matches\n return rootContent.filter((element) => {\n const matches = JSONPath({ path, json: element as object })\n return Array.isArray(matches) && matches.length > 0\n })\n }\n\n // If the root content is a single object, use 'all' resultType to get parent objects\n if (isObject(rootContent)) {\n // Evaluate the path against the full parsed document to get match information\n const allMatches = JSONPath({\n path,\n json: parsed,\n resultType: 'all',\n }) as unknown\n\n if (!Array.isArray(allMatches) || allMatches.length === 0) {\n return []\n }\n\n // Extract parent objects, deduplicating by reference\n const parentSet = new Set<object>()\n for (const match of allMatches) {\n const m = match as Record<string, unknown>\n if (isObject(m.parent)) {\n parentSet.add(m.parent as object)\n }\n }\n\n return Array.from(parentSet)\n }\n\n // For scalar or other types, return empty\n return []\n }\n\n /**\n * Alias for xml_get — extract values matching a JSONPath.\n *\n * @param path - A JSONPath expression (e.g., `'$..name'`).\n * @returns Array of matched values.\n */\n async xml_pluck(path: string): Promise<unknown[]> {\n return this.xml_get(path)\n }\n\n /**\n * Standard subclass extension pattern: call `SpooledArtifact.forgeTools(ctx)` to produce\n * the base seven `artifact_*` tools narrowed to any `SpooledArtifact` in the turn, then\n * register one `ArtifactTool` per XML-specific descriptor narrowed to XML artifacts.\n */\n public static override forgeTools(ctx: DispatchContext): ToolRegistry {\n const registry = SpooledArtifact.forgeTools(ctx)\n const requires = SpooledXmlArtifact\n const compatibleIds = collectArtifactCompatibleIds(ctx, requires)\n if (compatibleIds.length === 0) return registry\n\n for (const descriptor of this.toolMethods) {\n const callIdSchema = validator\n .string()\n .valid(...compatibleIds)\n .required()\n .description('ToolCall id of the artifact to query.')\n\n const argsSchema = (\n descriptor.argsSchema ?? validator.object<Record<string, never>>({})\n ).append({\n callId: callIdSchema,\n })\n\n const tool = new ArtifactTool({\n name: descriptor.name,\n description: descriptor.description,\n inputSchema: argsSchema,\n ephemeral: true,\n onCollision: 'replace',\n handler: async (rawArgs, ctxInner) => {\n const args = rawArgs as Record<string, unknown> & { callId: string }\n const resolved = resolveArtifactById(ctxInner, args.callId, requires)\n if (!resolved) return `Error: no artifact with id ${args.callId} in this turn`\n const artifact = resolved.artifact\n const methodArgs: unknown[] = []\n if (\n descriptor.method === 'xml_get' ||\n descriptor.method === 'xml_filter' ||\n descriptor.method === 'xml_pluck'\n ) {\n methodArgs.push(args.path as string)\n }\n const fn = (artifact as unknown as Record<string, (...a: unknown[]) => unknown>)[\n descriptor.method\n ]\n if (typeof fn !== 'function') {\n return `Error: artifact has no method ${descriptor.method}`\n }\n const result = await Promise.resolve(fn.apply(artifact, methodArgs))\n const serialise = descriptor.serialise ?? defaultSerialise\n return serialise(result)\n },\n })\n registry.register(tool)\n }\n return registry\n }\n\n /**\n * Parses and caches the XML projection.\n *\n * @returns The parsed projection as a JSON object.\n * @throws {@link E_XML_PARSE_FAILED} when XML parsing fails.\n */\n async #resolveParsed(): Promise<Record<string, unknown>> {\n if (this.#parsed !== undefined) {\n return this.#parsed\n }\n\n const parser = await getXmlParser()\n const xmlParser = new parser.XMLParser({\n ignoreAttributes: this.#ignoreAttributes,\n attributeNamePrefix: this.#attributeNamePrefix,\n preserveOrder: false,\n })\n\n const content = await this.asString()\n try {\n this.#parsed = xmlParser.parse(content) as Record<string, unknown>\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n throw new E_XML_PARSE_FAILED([detail])\n }\n return this.#parsed\n }\n\n /**\n * Serialise this SpooledXmlArtifact into an `@nhtio/encoder` snapshot — the reader **handle**\n * plus the constructor options for `attributeNamePrefix` and `ignoreAttributes`.\n *\n * @remarks\n * Overrides {@link SpooledArtifact.[ENCODE_METHOD]} to carry the constructor's options\n * (the parsed projection cache is derived and not encoded). Round-trips via\n * {@link SpooledXmlArtifact.[DECODE_METHOD]}.\n *\n * @returns A snapshot consumed by {@link SpooledXmlArtifact.[DECODE_METHOD]}.\n */\n [ENCODE_METHOD](): AdkEncodableSnapshot {\n return {\n reader: this.readerDescriptor(),\n attributeNamePrefix: this.#attributeNamePrefix,\n ignoreAttributes: this.#ignoreAttributes,\n }\n }\n\n /**\n * Reconstruct a {@link SpooledXmlArtifact} from a {@link SpooledXmlArtifact.[ENCODE_METHOD]}\n * snapshot.\n *\n * @param data - The snapshot produced by {@link SpooledXmlArtifact.[ENCODE_METHOD]}.\n * @returns A fresh {@link SpooledXmlArtifact} backed by a freshly-resolved reader.\n */\n static [DECODE_METHOD](data: AdkEncodableSnapshot): SpooledXmlArtifact {\n const snapshot = data as {\n reader: ReaderDescriptor\n attributeNamePrefix?: string\n ignoreAttributes?: boolean\n }\n return new SpooledXmlArtifact(resolveSpoolReader(snapshot.reader), {\n attributeNamePrefix: snapshot.attributeNamePrefix,\n ignoreAttributes: snapshot.ignoreAttributes,\n })\n }\n}\n\n/**\n * A tool that converts XML (inline or from an artifact) to JSON.\n *\n * @remarks\n * Input is either `text` (inline XML) or `call_id` (an XML artifact from earlier in this turn).\n * Provide exactly one. Returns a new {@link SpooledJsonArtifact}.\n */\nexport const xmlToJsonTool = new Tool({\n name: 'xml_to_json',\n description:\n 'Convert XML (inline or from an artifact produced earlier in this turn) to JSON. ' +\n 'Returns a queryable JSON artifact.',\n inputSchema: validator.object({\n text: validator\n .string()\n .optional()\n .allow('')\n .description('Inline XML text. Provide this or call_id, not both.'),\n call_id: validator\n .string()\n .optional()\n .allow('')\n .description('ToolCall id of an XML artifact produced earlier in this turn.'),\n }),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (rawArgs, ctx) => {\n const args = rawArgs as { text?: string; call_id?: string }\n const text = (args.text ?? '').trim()\n const callId = (args.call_id ?? '').trim()\n\n // Validate input\n if (!text && !callId) {\n return 'Error: provide either text or call_id, not both or neither'\n }\n if (text && callId) {\n return 'Error: provide either text or call_id, not both'\n }\n\n let xmlContent: string\n let sourceId: string\n let attributeNamePrefix: string\n let ignoreAttributes: boolean\n\n if (callId) {\n const resolved = resolveArtifactById(ctx, callId, SpooledXmlArtifact)\n if (!resolved) {\n return `Error: no artifact with id ${callId} in this turn`\n }\n const xmlArtifact = resolved.artifact as SpooledXmlArtifact\n xmlContent = await xmlArtifact.asString()\n sourceId = callId\n // Inherit the source artifact's parser configuration\n const sourceOptions = xmlArtifact.getParserOptions()\n attributeNamePrefix = sourceOptions.attributeNamePrefix\n ignoreAttributes = sourceOptions.ignoreAttributes\n } else {\n xmlContent = text\n sourceId = uuidv6()\n // Use defaults for inline conversions\n attributeNamePrefix = '_'\n ignoreAttributes = false\n }\n\n // Parse XML to JSON projection\n const parser = await getXmlParser()\n const xmlParser = new parser.XMLParser({\n ignoreAttributes,\n attributeNamePrefix,\n preserveOrder: false,\n })\n\n let parsed: unknown\n try {\n parsed = xmlParser.parse(xmlContent)\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n return `Error: XML parse failed: ${detail}`\n }\n\n // Convert to JSON string\n const jsonString = JSON.stringify(parsed)\n\n // Spool and return\n const reader = await ctx.storeRetrievableBytes(`${ctx.id}:xml_to_json:${sourceId}`, jsonString)\n return new SpooledJsonArtifact(reader)\n },\n})\n\n/**\n * A tool that converts JSON (inline or from an artifact) to XML.\n *\n * @remarks\n * Input is either `text` (inline JSON) or `call_id` (a JSON artifact from earlier in this turn).\n * Provide exactly one. Returns a new {@link SpooledXmlArtifact}.\n *\n * Note: XML has no faithful JSON inverse. A JSON document that never came from XML may not\n * rebuild into sensible markup. This tool converts on a best-effort basis; the result may not\n * round-trip perfectly back to the original JSON.\n */\nexport const jsonToXmlTool = new Tool({\n name: 'json_to_xml',\n description:\n 'Convert JSON (inline or from an artifact produced earlier in this turn) to XML. ' +\n 'Returns a queryable XML artifact. ' +\n 'Note: XML has no faithful JSON inverse — a JSON document that never came from XML may not rebuild into sensible markup.',\n inputSchema: validator.object({\n text: validator\n .string()\n .optional()\n .allow('')\n .description('Inline JSON text. Provide this or call_id, not both.'),\n call_id: validator\n .string()\n .optional()\n .allow('')\n .description('ToolCall id of a JSON artifact produced earlier in this turn.'),\n }),\n artifactConstructor: () => SpooledXmlArtifact,\n handler: async (rawArgs, ctx) => {\n const args = rawArgs as { text?: string; call_id?: string }\n const text = (args.text ?? '').trim()\n const callId = (args.call_id ?? '').trim()\n\n // Validate input\n if (!text && !callId) {\n return 'Error: provide either text or call_id, not both or neither'\n }\n if (text && callId) {\n return 'Error: provide either text or call_id, not both'\n }\n\n let jsonContent: unknown\n let sourceId: string\n\n if (callId) {\n const resolved = resolveArtifactById(ctx, callId, SpooledJsonArtifact)\n if (!resolved) {\n return `Error: no artifact with id ${callId} in this turn`\n }\n const jsonString = await resolved.artifact.asString()\n try {\n jsonContent = JSON.parse(jsonString)\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n return `Error: JSON parse failed: ${detail}`\n }\n sourceId = callId\n } else {\n try {\n jsonContent = JSON.parse(text)\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n return `Error: JSON parse failed: ${detail}`\n }\n sourceId = uuidv6()\n }\n\n // Convert JSON to XML via builder\n const parser = await getXmlParser()\n const xmlBuilder = new parser.XMLBuilder({\n ignoreAttributes: false,\n attributeNamePrefix: '_',\n format: false,\n })\n\n let xmlString: string\n try {\n xmlString = xmlBuilder.build(jsonContent) as string\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n return `Error: XML build failed: ${detail}`\n }\n\n // Spool and return\n const reader = await ctx.storeRetrievableBytes(`${ctx.id}:json_to_xml:${sourceId}`, xmlString)\n return new SpooledXmlArtifact(reader)\n },\n})\n\n/**\n * Re-export the exceptions for battery-scoped error handling.\n *\n * @remarks\n * Battery exceptions are defined in `exceptions.ts` and re-exported here per the\n * battery-scoped-exceptions pattern — consumers of `@nhtio/adk/batteries/artifacts/xml`\n * can import these exception classes directly.\n */\nexport { E_XML_PARSER_PEER_MISSING, E_XML_PARSE_FAILED } from './exceptions'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,4BAA4B,gBACvC,6BACA,+JACA,6BACA,KACA,IACF;;;;;;;AAQA,IAAa,qBAAqB,gBAChC,sBACA,wBACA,sBACA,KACA,KACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACEA,IAAM,gBAA+B,OAAO,IAAI,0BAA0B;AAC1E,IAAM,gBAA+B,OAAO,IAAI,4BAA4B;;;;AAiB5E,IAAI;;;;;;;AAUJ,eAAe,eAGZ;CACD,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AAO,IAAI,mBAAmB,MADT,IAAI,sBAAsB,GAAG,IAAI,GAAG,eAAe,YAAY,SAAS,CACzD;CACtC;AACF,CAAC"}
1
+ {"version":3,"file":"xml-CYseDztH.mjs","names":["#attributeNamePrefix","#ignoreAttributes","#resolveParsed","#parsed"],"sources":["../src/batteries/artifacts/xml/exceptions.ts","../src/batteries/artifacts/xml/index.ts"],"sourcesContent":["/**\n * Battery-scoped exceptions for the XML artifact battery.\n *\n * @remarks\n * Internal sibling of the `@nhtio/adk/batteries/artifacts/xml` entry — re-exported from the battery's\n * own barrel per the battery-scoped-exceptions rule. These are the typed errors the\n * implementor-facing API throws; the agent-facing forge catches them and renders readable\n * failure strings the model can act on.\n */\n\nimport { createException } from '@nhtio/adk/factories'\n\n/**\n * Thrown when the fast-xml-parser optional peer is not installed or fails to load.\n *\n * @remarks\n * The message template includes the package name, a description of its purpose, the underlying\n * error, and the exact install command, so the consumer sees a complete, actionable message\n * regardless of call site.\n */\nexport const E_XML_PARSER_PEER_MISSING = createException<[string]>(\n 'E_XML_PARSER_PEER_MISSING',\n 'the XML battery could not load its peer dependency \"fast-xml-parser\" (needed for XML format artifact queries): %s — install it (pnpm add fast-xml-parser)',\n 'E_XML_PARSER_PEER_MISSING',\n 500,\n true\n)\n\n/**\n * Thrown when XML parsing fails due to malformed markup.\n *\n * @remarks\n * Printf args: `[errorDetail]` — includes the parser's own reason for the failure.\n */\nexport const E_XML_PARSE_FAILED = createException<[string]>(\n 'E_XML_PARSE_FAILED',\n 'XML parse failed: %s',\n 'E_XML_PARSE_FAILED',\n 422,\n false\n)\n","/**\n * A structured artifact battery for XML documents.\n *\n * @module @nhtio/adk/batteries/artifacts/xml\n *\n * @remarks\n * Provides {@link SpooledXmlArtifact} — a `SpooledArtifact` specialisation that parses XML\n * into a JSON projection and offers path-based query tools over that projection. The XML-to-JSON\n * mapping defaults to `ignoreAttributes: false` and `attributeNamePrefix: '_'`, both settable\n * per instance through the constructor; `preserveOrder: false` is fixed. Under the default\n * mapping:\n *\n * - Element attributes become keys prefixed with `_` (e.g., `root-element` with `href=\"x\"`\n * becomes `{ a: { _href: 'x', ... } }`).\n * - Element text content becomes a `#text` key when the element also has attributes or siblings.\n * - Repeated sibling elements collapse into an array.\n * - The full projection is queryable via JSONPath expressions (e.g., `$..name` finds all name\n * elements anywhere in the tree). Attributes are accessed via underscore-prefixed keys,\n * e.g. `$..[\"_href\"]` for the href attribute (recursive descent).\n *\n * The battery also exports two converter `Tool` constants: `xmlToJsonTool` and `jsonToXmlTool`.\n * These accept either inline XML/JSON text or a reference to an artifact produced earlier in\n * the turn, and return the converted result as a new `SpooledJsonArtifact` or\n * `SpooledXmlArtifact`.\n *\n * Battery exceptions are defined in this module's `exceptions.ts` file — `createException`\n * re-exported from `@nhtio/adk/factories`. Decoding a {@link SpooledXmlArtifact} instance via\n * `decode()` throws until `registerArtifactEncodables()` has run (see\n * {@link @nhtio/adk/batteries/artifacts!registerArtifactEncodables}).\n */\n\nimport { v6 as uuidv6 } from 'uuid'\nimport { JSONPath } from 'jsonpath-plus'\nimport { validator } from '@nhtio/validation'\nimport { resolveSpoolReader } from '@nhtio/adk/common'\nimport { SpooledJsonArtifact } from '@nhtio/adk/common'\nimport { isInstanceOf, isError, isObject } from '@nhtio/adk/guards'\nimport { E_XML_PARSER_PEER_MISSING, E_XML_PARSE_FAILED } from './exceptions'\nimport { ArtifactTool, Tool, ToolRegistry, ReaderDescriptor } from '@nhtio/adk/common'\n\n// Well-known @nhtio/encoder contract keys, resolved through the global symbol registry.\n// These are identical to the symbols core uses, with no import edge on the optional peer.\nconst ENCODE_METHOD: unique symbol = Symbol.for('@nhtio/encoder:toEncoded')\nconst DECODE_METHOD: unique symbol = Symbol.for('@nhtio/encoder:fromEncoded')\nimport {\n SpooledArtifact,\n collectArtifactCompatibleIds,\n resolveArtifactById,\n defaultSerialise,\n} from '@nhtio/adk/spooled_artifact'\nimport type { SpoolReader } from '@nhtio/adk/types'\nimport type { XMLParser, XMLBuilder } from 'fast-xml-parser'\nimport type { ToolMethodDescriptor, DispatchContext } from '@nhtio/adk/types'\n\n/** Snapshot payload for the encoder contract; the encoder treats it as opaque. */\ntype AdkEncodableSnapshot = unknown\n\n/**\n * Lazy-loaded promise for the `fast-xml-parser` module, cached at module scope.\n */\nlet xmlParserPromise:\n | Promise<{ XMLParser: typeof XMLParser; XMLBuilder: typeof XMLBuilder }>\n | undefined\n\n/**\n * Lazily import and cache the `fast-xml-parser` module with battery-scoped error handling.\n *\n * @returns The imported module.\n * @throws {@link E_XML_PARSER_PEER_MISSING} when the module is unavailable.\n */\nasync function getXmlParser(): Promise<{\n XMLParser: typeof XMLParser\n XMLBuilder: typeof XMLBuilder\n}> {\n xmlParserPromise ??= import('fast-xml-parser').catch((err) => {\n const detail = isError(err) ? err.message : String(err)\n throw new E_XML_PARSER_PEER_MISSING([detail])\n })\n return xmlParserPromise\n}\n\n/**\n * A {@link @nhtio/adk!SpooledArtifact} specialisation that adds XML-aware read operations.\n *\n * @remarks\n * The artifact parses XML into a JSON projection on first access and caches it for the\n * lifetime of the instance. The projection uses `ignoreAttributes` and `attributeNamePrefix` as\n * supplied to the constructor — defaulting to `false` and `'_'` — with `preserveOrder: false`.\n *\n * Under this mapping, an XML element like:\n *\n * `root-element` with an `href` attribute and text content becomes a JSON object like:\n * `{ root: { element: { _href: 'value', '#text': 'content' } } }`\n *\n * Attributes are prefixed with `_` by default rather than the conventional `@_`, because\n * `jsonpath-plus` reads a leading `@` in a path segment as its type-selector sigil before\n * honouring quotes: `$..[\"@_href\"]` throws `Unknown value type _hr`, while `$..[\"_href\"]`\n * matches. Text nodes use the `#text` key.\n *\n * All XML methods are async, consistent with {@link @nhtio/adk!SpooledArtifact}.\n *\n * Path-based methods (`xml_get`, `xml_filter`, `xml_pluck`) use\n * [JSONPath-Plus](https://github.com/JSONPath-Plus/JSONPath) expressions over the projection.\n * Full JSONPath syntax is supported, including recursive descent (`..`), filter expressions,\n * and union selectors.\n */\nexport class SpooledXmlArtifact extends SpooledArtifact {\n #parsed: Record<string, unknown> | undefined\n #attributeNamePrefix: string\n #ignoreAttributes: boolean\n\n /**\n * @param reader - The backing store to read from.\n * @param options - Optional parser configuration.\n * @param options.attributeNamePrefix - Prefix for attribute keys (default: '_'). Set to '@_'\n * if you need the conventional XML-to-JSON mapping, but be aware that naming such a key in a\n * JSONPath segment fails — `$..[\"@_attr\"]` throws `Unknown value type _at`, and quoting does\n * not escape it. A filter expression still reaches it (`$..[?(@['@_attr'])]`); a wildcard\n * does too, but only when placed exactly one level above the key, so the working path\n * depends on whether repeated elements collapsed into an array.\n * @param options.ignoreAttributes - When true, ignore element attributes (default: false).\n */\n constructor(\n reader: SpoolReader,\n options?: {\n attributeNamePrefix?: string\n ignoreAttributes?: boolean\n }\n ) {\n super(reader)\n this.#attributeNamePrefix = options?.attributeNamePrefix ?? '_'\n this.#ignoreAttributes = options?.ignoreAttributes ?? false\n }\n\n /**\n * Returns `true` if `value` is a {@link SpooledXmlArtifact} instance.\n *\n * @remarks\n * Uses the cross-realm-safe {@link @nhtio/adk!isInstanceOf} guard. Safe against the\n * dual-module-copy case where two distinct `SpooledXmlArtifact` classes coexist in the same\n * realm.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link SpooledXmlArtifact} instance.\n */\n public static isSpooledXmlArtifact(value: unknown): value is SpooledXmlArtifact {\n return isInstanceOf(value, 'SpooledXmlArtifact', SpooledXmlArtifact)\n }\n\n /**\n * Returns the effective XML-to-JSON parser configuration for this artifact.\n *\n * @remarks\n * When converting an XML artifact to JSON by call_id, the converter inherits the source\n * artifact's attribute prefix and ignoreAttributes setting. This accessor exposes those\n * options so the converter can apply them consistently.\n *\n * @returns An object with `attributeNamePrefix` and `ignoreAttributes` keys.\n */\n public getParserOptions(): {\n attributeNamePrefix: string\n ignoreAttributes: boolean\n } {\n return {\n attributeNamePrefix: this.#attributeNamePrefix,\n ignoreAttributes: this.#ignoreAttributes,\n }\n }\n\n /**\n * The XML-specific artifact-query descriptors this class adds on top of the base set.\n *\n * @remarks\n * Lists `artifact_xml_root`, `artifact_xml_keys`, `artifact_xml_tags`, `artifact_xml_length`,\n * `artifact_xml_get`, `artifact_xml_filter`, `artifact_xml_pluck`. The base seven descriptors\n * (`artifact_head`, etc.) are NOT included here — they are forged separately by\n * {@link SpooledXmlArtifact.forgeTools}.\n */\n public static toolMethods: ReadonlyArray<ToolMethodDescriptor> = Object.freeze([\n {\n name: 'artifact_xml_root',\n method: 'xml_root',\n description: 'The root element name of the XML document produced earlier in this turn.',\n },\n {\n name: 'artifact_xml_keys',\n method: 'xml_keys',\n description:\n 'Keys directly under the root element of the XML document produced earlier in this turn.',\n },\n {\n name: 'artifact_xml_tags',\n method: 'xml_tags',\n description:\n 'Every distinct element name in the XML document produced earlier in this turn, deduplicated. ' +\n 'Call this before writing a path to an unfamiliar document — it tells you what elements are present.',\n },\n {\n name: 'artifact_xml_length',\n method: 'xml_length',\n description:\n 'Element count when the root element contains an array of children; otherwise 1. ' +\n 'The XML document was produced earlier in this turn.',\n },\n {\n name: 'artifact_xml_get',\n method: 'xml_get',\n argsSchema: validator.object({\n path: validator\n .string()\n .required()\n .description(\n 'JSONPath expression to query the document. Attributes appear with a leading underscore (e.g., _href). Use bracket notation for recursive descent: $..[\"_href\"].'\n ),\n }),\n description:\n 'Query the XML document via JSONPath. The document was produced earlier in this turn. ' +\n 'Attributes appear as underscore-prefixed keys (e.g., _href for an href attribute). Use bracket notation in recursive-descent queries: $..[\"_href\"].',\n },\n {\n name: 'artifact_xml_filter',\n method: 'xml_filter',\n argsSchema: validator.object({\n path: validator\n .string()\n .required()\n .description(\n 'JSONPath expression to filter the document. Attributes appear with a leading underscore (e.g., _href).'\n ),\n }),\n description:\n 'Return XML elements whose content matches a JSONPath filter. Differs from artifact_xml_get: get returns matched values; filter returns the element objects containing them. The document was produced earlier in this turn. Attributes appear as underscore-prefixed keys (e.g., _href).',\n },\n {\n name: 'artifact_xml_pluck',\n method: 'xml_pluck',\n argsSchema: validator.object({\n path: validator\n .string()\n .required()\n .description(\n 'JSONPath expression to pluck values. Attributes appear with a leading underscore (e.g., _href).'\n ),\n }),\n description:\n 'Alias for artifact_xml_get — extract values matching a JSONPath. The document was produced earlier in this turn. ' +\n 'Attributes appear as underscore-prefixed keys (e.g., _href).',\n },\n ])\n\n /**\n * The root element name of the XML document.\n *\n * @returns The name of the root element.\n * @throws Error when the document is malformed or empty.\n */\n async xml_root(): Promise<string> {\n const parsed = await this.#resolveParsed()\n const keys = Object.keys(parsed)\n if (keys.length === 0) {\n throw new Error('XML document is empty')\n }\n return keys[0]\n }\n\n /**\n * Keys directly under the root element.\n *\n * @returns Array of key names at the root level.\n */\n async xml_keys(): Promise<string[]> {\n const parsed = await this.#resolveParsed()\n const rootKey = Object.keys(parsed)[0]\n if (!rootKey) return []\n const rootContent = parsed[rootKey]\n if (!isObject(rootContent)) return []\n return Object.keys(rootContent)\n }\n\n /**\n * Every distinct element name in the document, deduplicated.\n *\n * @remarks\n * Walks the entire projection recursively, excluding attribute keys (prefixed with the\n * configured `attributeNamePrefix`, default `_`) and `#text` keys. This is what a model\n * calls before it can write a path into an unfamiliar document.\n *\n * @returns Sorted array of unique element names.\n */\n async xml_tags(): Promise<string[]> {\n const parsed = await this.#resolveParsed()\n const tags = new Set<string>()\n const attributePrefix = this.#attributeNamePrefix\n\n function walk(obj: unknown): void {\n if (!isObject(obj)) return\n for (const [key, value] of Object.entries(obj)) {\n // Skip attribute keys and text nodes\n if (key.startsWith(attributePrefix) || key === '#text') {\n continue\n }\n tags.add(key)\n if (Array.isArray(value)) {\n for (const item of value) {\n walk(item)\n }\n } else {\n walk(value)\n }\n }\n }\n\n walk(parsed)\n return Array.from(tags).sort()\n }\n\n /**\n * Element count when the root contains an array of children; otherwise 1.\n *\n * @returns Number of elements.\n */\n async xml_length(): Promise<number> {\n const parsed = await this.#resolveParsed()\n const rootKey = Object.keys(parsed)[0]\n if (!rootKey) return 0\n const rootContent = parsed[rootKey]\n if (Array.isArray(rootContent)) {\n return rootContent.length\n }\n return 1\n }\n\n /**\n * Query the document via JSONPath expression.\n *\n * @param path - A JSONPath expression (e.g., `'$..name'`).\n * @returns Array of matched values.\n */\n async xml_get(path: string): Promise<unknown[]> {\n const parsed = await this.#resolveParsed()\n const results = JSONPath({ path, json: parsed })\n return results\n }\n\n /**\n * Returns the elements (subtrees) that match a JSONPath expression.\n *\n * @remarks\n * Evaluates the path against the XML projection and returns the elements that\n * contain matching values. Unlike xml_get (which returns matched values), xml_filter\n * returns the element objects containing those matches.\n *\n * Candidate set definition for XML's single-rooted projection:\n * - If the root element contains an array of repeated siblings (e.g., root.item\n * where item is an array property), filters across those siblings and returns\n * elements that have matching content.\n * - If the root element contains a single object, evaluates the path against it\n * and returns it when matched.\n *\n * The path is evaluated using JSONPath-Plus with resultType 'all' to extract\n * parent elements of matched values. The immediate parent object of any matched\n * value is included in the result, deduplicating elements.\n *\n * Example: for XML with root containing multiple 'item' elements each with an\n * 'id' attribute, xml_filter('$.root.item[*]._id') returns the item elements\n * that have an id attribute, whereas xml_get would return the id values themselves.\n *\n * @param path - A JSONPath expression (e.g. '$.root.item[*]._id' or '$[?(@.status)]').\n * @returns Array of matching element subtrees. Empty array when no matches found.\n */\n async xml_filter(path: string): Promise<unknown[]> {\n const parsed = await this.#resolveParsed()\n const rootKey = Object.keys(parsed)[0]\n if (!rootKey) return []\n\n const rootContent = parsed[rootKey]\n\n // If the root content is an array of siblings, filter the array elements\n if (Array.isArray(rootContent)) {\n // Evaluate the path against each sibling element to see if it matches\n return rootContent.filter((element) => {\n const matches = JSONPath({ path, json: element as object })\n return Array.isArray(matches) && matches.length > 0\n })\n }\n\n // If the root content is a single object, use 'all' resultType to get parent objects\n if (isObject(rootContent)) {\n // Evaluate the path against the full parsed document to get match information\n const allMatches = JSONPath({\n path,\n json: parsed,\n resultType: 'all',\n }) as unknown\n\n if (!Array.isArray(allMatches) || allMatches.length === 0) {\n return []\n }\n\n // Extract parent objects, deduplicating by reference\n const parentSet = new Set<object>()\n for (const match of allMatches) {\n const m = match as Record<string, unknown>\n if (isObject(m.parent)) {\n parentSet.add(m.parent as object)\n }\n }\n\n return Array.from(parentSet)\n }\n\n // For scalar or other types, return empty\n return []\n }\n\n /**\n * Alias for xml_get — extract values matching a JSONPath.\n *\n * @param path - A JSONPath expression (e.g., `'$..name'`).\n * @returns Array of matched values.\n */\n async xml_pluck(path: string): Promise<unknown[]> {\n return this.xml_get(path)\n }\n\n /**\n * Standard subclass extension pattern: call `SpooledArtifact.forgeTools(ctx)` to produce\n * the base seven `artifact_*` tools narrowed to any `SpooledArtifact` in the turn, then\n * register one `ArtifactTool` per XML-specific descriptor narrowed to XML artifacts.\n */\n public static override forgeTools(ctx: DispatchContext): ToolRegistry {\n const registry = SpooledArtifact.forgeTools(ctx)\n const requires = SpooledXmlArtifact\n const compatibleIds = collectArtifactCompatibleIds(ctx, requires)\n if (compatibleIds.length === 0) return registry\n\n for (const descriptor of this.toolMethods) {\n const callIdSchema = validator\n .string()\n .valid(...compatibleIds)\n .required()\n .description('ToolCall id of the artifact to query.')\n\n const argsSchema = (\n descriptor.argsSchema ?? validator.object<Record<string, never>>({})\n ).append({\n callId: callIdSchema,\n })\n\n const tool = new ArtifactTool({\n name: descriptor.name,\n description: descriptor.description,\n inputSchema: argsSchema,\n ephemeral: true,\n onCollision: 'replace',\n handler: async (rawArgs, ctxInner) => {\n const args = rawArgs as Record<string, unknown> & { callId: string }\n const resolved = resolveArtifactById(ctxInner, args.callId, requires)\n if (!resolved) return `Error: no artifact with id ${args.callId} in this turn`\n const artifact = resolved.artifact\n const methodArgs: unknown[] = []\n if (\n descriptor.method === 'xml_get' ||\n descriptor.method === 'xml_filter' ||\n descriptor.method === 'xml_pluck'\n ) {\n methodArgs.push(args.path as string)\n }\n const fn = (artifact as unknown as Record<string, (...a: unknown[]) => unknown>)[\n descriptor.method\n ]\n if (typeof fn !== 'function') {\n return `Error: artifact has no method ${descriptor.method}`\n }\n const result = await Promise.resolve(fn.apply(artifact, methodArgs))\n const serialise = descriptor.serialise ?? defaultSerialise\n return serialise(result)\n },\n })\n registry.register(tool)\n }\n return registry\n }\n\n /**\n * Parses and caches the XML projection.\n *\n * @returns The parsed projection as a JSON object.\n * @throws {@link E_XML_PARSE_FAILED} when XML parsing fails.\n */\n async #resolveParsed(): Promise<Record<string, unknown>> {\n if (this.#parsed !== undefined) {\n return this.#parsed\n }\n\n const parser = await getXmlParser()\n const xmlParser = new parser.XMLParser({\n ignoreAttributes: this.#ignoreAttributes,\n attributeNamePrefix: this.#attributeNamePrefix,\n preserveOrder: false,\n })\n\n const content = await this.asString()\n try {\n this.#parsed = xmlParser.parse(content) as Record<string, unknown>\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n throw new E_XML_PARSE_FAILED([detail])\n }\n return this.#parsed\n }\n\n /**\n * Serialise this SpooledXmlArtifact into an `@nhtio/encoder` snapshot — the reader **handle**\n * plus the constructor options for `attributeNamePrefix` and `ignoreAttributes`.\n *\n * @remarks\n * Overrides {@link SpooledArtifact.[ENCODE_METHOD]} to carry the constructor's options\n * (the parsed projection cache is derived and not encoded). Round-trips via\n * {@link SpooledXmlArtifact.[DECODE_METHOD]}.\n *\n * @returns A snapshot consumed by {@link SpooledXmlArtifact.[DECODE_METHOD]}.\n */\n [ENCODE_METHOD](): AdkEncodableSnapshot {\n return {\n reader: this.readerDescriptor(),\n attributeNamePrefix: this.#attributeNamePrefix,\n ignoreAttributes: this.#ignoreAttributes,\n }\n }\n\n /**\n * Reconstruct a {@link SpooledXmlArtifact} from a {@link SpooledXmlArtifact.[ENCODE_METHOD]}\n * snapshot.\n *\n * @param data - The snapshot produced by {@link SpooledXmlArtifact.[ENCODE_METHOD]}.\n * @returns A fresh {@link SpooledXmlArtifact} backed by a freshly-resolved reader.\n */\n static [DECODE_METHOD](data: AdkEncodableSnapshot): SpooledXmlArtifact {\n const snapshot = data as {\n reader: ReaderDescriptor\n attributeNamePrefix?: string\n ignoreAttributes?: boolean\n }\n return new SpooledXmlArtifact(resolveSpoolReader(snapshot.reader), {\n attributeNamePrefix: snapshot.attributeNamePrefix,\n ignoreAttributes: snapshot.ignoreAttributes,\n })\n }\n}\n\n/**\n * A tool that converts XML (inline or from an artifact) to JSON.\n *\n * @remarks\n * Input is either `text` (inline XML) or `call_id` (an XML artifact from earlier in this turn).\n * Provide exactly one. Returns a new {@link SpooledJsonArtifact}.\n */\nexport const xmlToJsonTool = new Tool({\n name: 'xml_to_json',\n description:\n 'Convert XML (inline or from an artifact produced earlier in this turn) to JSON. ' +\n 'Returns a queryable JSON artifact.',\n inputSchema: validator.object({\n text: validator\n .string()\n .optional()\n .allow('')\n .description('Inline XML text. Provide this or call_id, not both.'),\n call_id: validator\n .string()\n .optional()\n .allow('')\n .description('ToolCall id of an XML artifact produced earlier in this turn.'),\n }),\n artifactConstructor: () => SpooledJsonArtifact,\n handler: async (rawArgs, ctx) => {\n const args = rawArgs as { text?: string; call_id?: string }\n const text = (args.text ?? '').trim()\n const callId = (args.call_id ?? '').trim()\n\n // Validate input\n if (!text && !callId) {\n return 'Error: provide either text or call_id, not both or neither'\n }\n if (text && callId) {\n return 'Error: provide either text or call_id, not both'\n }\n\n let xmlContent: string\n let sourceId: string\n let attributeNamePrefix: string\n let ignoreAttributes: boolean\n\n if (callId) {\n const resolved = resolveArtifactById(ctx, callId, SpooledXmlArtifact)\n if (!resolved) {\n return `Error: no artifact with id ${callId} in this turn`\n }\n const xmlArtifact = resolved.artifact as SpooledXmlArtifact\n xmlContent = await xmlArtifact.asString()\n sourceId = callId\n // Inherit the source artifact's parser configuration\n const sourceOptions = xmlArtifact.getParserOptions()\n attributeNamePrefix = sourceOptions.attributeNamePrefix\n ignoreAttributes = sourceOptions.ignoreAttributes\n } else {\n xmlContent = text\n sourceId = uuidv6()\n // Use defaults for inline conversions\n attributeNamePrefix = '_'\n ignoreAttributes = false\n }\n\n // Parse XML to JSON projection\n const parser = await getXmlParser()\n const xmlParser = new parser.XMLParser({\n ignoreAttributes,\n attributeNamePrefix,\n preserveOrder: false,\n })\n\n let parsed: unknown\n try {\n parsed = xmlParser.parse(xmlContent)\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n return `Error: XML parse failed: ${detail}`\n }\n\n // Convert to JSON string\n const jsonString = JSON.stringify(parsed)\n\n // Spool and return\n const reader = await ctx.storeRetrievableBytes(`${ctx.id}:xml_to_json:${sourceId}`, jsonString)\n return new SpooledJsonArtifact(reader)\n },\n})\n\n/**\n * A tool that converts JSON (inline or from an artifact) to XML.\n *\n * @remarks\n * Input is either `text` (inline JSON) or `call_id` (a JSON artifact from earlier in this turn).\n * Provide exactly one. Returns a new {@link SpooledXmlArtifact}.\n *\n * Note: XML has no faithful JSON inverse. A JSON document that never came from XML may not\n * rebuild into sensible markup. This tool converts on a best-effort basis; the result may not\n * round-trip perfectly back to the original JSON.\n */\nexport const jsonToXmlTool = new Tool({\n name: 'json_to_xml',\n description:\n 'Convert JSON (inline or from an artifact produced earlier in this turn) to XML. ' +\n 'Returns a queryable XML artifact. ' +\n 'Note: XML has no faithful JSON inverse — a JSON document that never came from XML may not rebuild into sensible markup.',\n inputSchema: validator.object({\n text: validator\n .string()\n .optional()\n .allow('')\n .description('Inline JSON text. Provide this or call_id, not both.'),\n call_id: validator\n .string()\n .optional()\n .allow('')\n .description('ToolCall id of a JSON artifact produced earlier in this turn.'),\n }),\n artifactConstructor: () => SpooledXmlArtifact,\n handler: async (rawArgs, ctx) => {\n const args = rawArgs as { text?: string; call_id?: string }\n const text = (args.text ?? '').trim()\n const callId = (args.call_id ?? '').trim()\n\n // Validate input\n if (!text && !callId) {\n return 'Error: provide either text or call_id, not both or neither'\n }\n if (text && callId) {\n return 'Error: provide either text or call_id, not both'\n }\n\n let jsonContent: unknown\n let sourceId: string\n\n if (callId) {\n const resolved = resolveArtifactById(ctx, callId, SpooledJsonArtifact)\n if (!resolved) {\n return `Error: no artifact with id ${callId} in this turn`\n }\n const jsonString = await resolved.artifact.asString()\n try {\n jsonContent = JSON.parse(jsonString)\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n return `Error: JSON parse failed: ${detail}`\n }\n sourceId = callId\n } else {\n try {\n jsonContent = JSON.parse(text)\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n return `Error: JSON parse failed: ${detail}`\n }\n sourceId = uuidv6()\n }\n\n // Convert JSON to XML via builder\n const parser = await getXmlParser()\n const xmlBuilder = new parser.XMLBuilder({\n ignoreAttributes: false,\n attributeNamePrefix: '_',\n format: false,\n })\n\n let xmlString: string\n try {\n xmlString = xmlBuilder.build(jsonContent) as string\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n return `Error: XML build failed: ${detail}`\n }\n\n // Spool and return\n const reader = await ctx.storeRetrievableBytes(`${ctx.id}:json_to_xml:${sourceId}`, xmlString)\n return new SpooledXmlArtifact(reader)\n },\n})\n\n/**\n * Re-export the exceptions for battery-scoped error handling.\n *\n * @remarks\n * Battery exceptions are defined in `exceptions.ts` and re-exported here per the\n * battery-scoped-exceptions pattern — consumers of `@nhtio/adk/batteries/artifacts/xml`\n * can import these exception classes directly.\n */\nexport { E_XML_PARSER_PEER_MISSING, E_XML_PARSE_FAILED } from './exceptions'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoBA,IAAa,4BAA4B,gBACvC,6BACA,+JACA,6BACA,KACA,IACF;;;;;;;AAQA,IAAa,qBAAqB,gBAChC,sBACA,wBACA,sBACA,KACA,KACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACEA,IAAM,gBAA+B,OAAO,IAAI,0BAA0B;AAC1E,IAAM,gBAA+B,OAAO,IAAI,4BAA4B;;;;AAiB5E,IAAI;;;;;;;AAUJ,eAAe,eAGZ;CACD,qBAAqB,OAAO,mBAAmB,OAAO,QAAQ;EAE5D,MAAM,IAAI,0BAA0B,CADrB,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG,CACX,CAAC;CAC9C,CAAC;CACD,OAAO;AACT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Qz.cjs");
2
2
  const require_guards = require("./guards-5-XmJgD2.cjs");
3
- const require_spooled_artifact = require("./spooled_artifact-BLgbGT8b.cjs");
4
- require("./common-7gCR3zQu.cjs");
5
- const require_spooled_markdown_artifact = require("./spooled_markdown_artifact-8zdejfcJ.cjs");
3
+ const require_spooled_artifact = require("./spooled_artifact---DmicFW.cjs");
4
+ require("./common-CqetsItm.cjs");
5
+ const require_spooled_markdown_artifact = require("./spooled_markdown_artifact-Rjzj-kyh.cjs");
6
6
  require("./factories.cjs");
7
7
  require("./guards.cjs");
8
8
  require("./spooled_artifact.cjs");
9
- let uuid = require("uuid");
10
9
  let _nhtio_validation = require("@nhtio/validation");
10
+ let uuid = require("uuid");
11
11
  let jsonpath_plus = require("jsonpath-plus");
12
12
  //#region src/batteries/artifacts/xml/exceptions.ts
13
13
  /**
@@ -584,4 +584,4 @@ Object.defineProperty(exports, "xmlToJsonTool", {
584
584
  }
585
585
  });
586
586
 
587
- //# sourceMappingURL=xml-fvwTsoRv.cjs.map
587
+ //# sourceMappingURL=xml-zJul8jMQ.cjs.map