@nhtio/adk 1.20260925.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 (332) hide show
  1. package/CHANGELOG.md +39 -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/isolation/child_process.cjs +1 -1
  27. package/batteries/isolation/child_process.mjs +1 -1
  28. package/batteries/isolation.cjs +1 -1
  29. package/batteries/isolation.mjs +1 -1
  30. package/batteries/llm/anthropic_messages/adapter.cjs +6 -6
  31. package/batteries/llm/anthropic_messages/adapter.mjs +6 -6
  32. package/batteries/llm/anthropic_messages/count_tokens.cjs +1 -1
  33. package/batteries/llm/anthropic_messages/count_tokens.mjs +1 -1
  34. package/batteries/llm/anthropic_messages/helpers.cjs +3 -3
  35. package/batteries/llm/anthropic_messages/helpers.mjs +3 -3
  36. package/batteries/llm/anthropic_messages/validation.cjs +2 -2
  37. package/batteries/llm/anthropic_messages/validation.mjs +2 -2
  38. package/batteries/llm/anthropic_messages.cjs +2 -2
  39. package/batteries/llm/anthropic_messages.mjs +2 -2
  40. package/batteries/llm/bedrock_converse/adapter.cjs +6 -6
  41. package/batteries/llm/bedrock_converse/adapter.mjs +6 -6
  42. package/batteries/llm/bedrock_converse/helpers.cjs +1 -1
  43. package/batteries/llm/bedrock_converse/helpers.mjs +1 -1
  44. package/batteries/llm/bedrock_converse/validation.cjs +2 -2
  45. package/batteries/llm/bedrock_converse/validation.mjs +2 -2
  46. package/batteries/llm/bedrock_converse.cjs +2 -2
  47. package/batteries/llm/bedrock_converse.mjs +2 -2
  48. package/batteries/llm/claude_code_cli/adapter.cjs +7 -7
  49. package/batteries/llm/claude_code_cli/adapter.mjs +7 -7
  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/validation.cjs +2 -2
  53. package/batteries/llm/claude_code_cli/validation.mjs +2 -2
  54. package/batteries/llm/claude_code_cli.cjs +2 -2
  55. package/batteries/llm/claude_code_cli.mjs +2 -2
  56. package/batteries/llm/gemini_generate_content/adapter.cjs +6 -6
  57. package/batteries/llm/gemini_generate_content/adapter.mjs +6 -6
  58. package/batteries/llm/gemini_generate_content/helpers.cjs +1 -1
  59. package/batteries/llm/gemini_generate_content/helpers.mjs +1 -1
  60. package/batteries/llm/gemini_generate_content/validation.cjs +2 -2
  61. package/batteries/llm/gemini_generate_content/validation.mjs +2 -2
  62. package/batteries/llm/gemini_generate_content.cjs +1 -1
  63. package/batteries/llm/gemini_generate_content.mjs +1 -1
  64. package/batteries/llm/litert_lm/adapter.cjs +6 -6
  65. package/batteries/llm/litert_lm/adapter.mjs +6 -6
  66. package/batteries/llm/litert_lm/helpers.cjs +3 -3
  67. package/batteries/llm/litert_lm/helpers.mjs +3 -3
  68. package/batteries/llm/litert_lm/validation.cjs +2 -2
  69. package/batteries/llm/litert_lm/validation.mjs +2 -2
  70. package/batteries/llm/litert_lm.cjs +1 -1
  71. package/batteries/llm/litert_lm.mjs +1 -1
  72. package/batteries/llm/ollama/adapter.cjs +6 -6
  73. package/batteries/llm/ollama/adapter.mjs +6 -6
  74. package/batteries/llm/ollama/helpers.cjs +4 -4
  75. package/batteries/llm/ollama/helpers.mjs +4 -4
  76. package/batteries/llm/ollama/validation.cjs +2 -2
  77. package/batteries/llm/ollama/validation.mjs +2 -2
  78. package/batteries/llm/ollama.cjs +2 -2
  79. package/batteries/llm/ollama.mjs +2 -2
  80. package/batteries/llm/openai_chat_completions/adapter.cjs +6 -6
  81. package/batteries/llm/openai_chat_completions/adapter.mjs +6 -6
  82. package/batteries/llm/openai_chat_completions/helpers.cjs +4 -4
  83. package/batteries/llm/openai_chat_completions/helpers.mjs +4 -4
  84. package/batteries/llm/openai_chat_completions/validation.cjs +2 -2
  85. package/batteries/llm/openai_chat_completions/validation.mjs +2 -2
  86. package/batteries/llm/openai_chat_completions.cjs +2 -2
  87. package/batteries/llm/openai_chat_completions.mjs +2 -2
  88. package/batteries/llm/openai_responses/adapter.cjs +6 -6
  89. package/batteries/llm/openai_responses/adapter.mjs +6 -6
  90. package/batteries/llm/openai_responses/helpers.cjs +3 -3
  91. package/batteries/llm/openai_responses/helpers.mjs +3 -3
  92. package/batteries/llm/openai_responses/validation.cjs +2 -2
  93. package/batteries/llm/openai_responses/validation.mjs +2 -2
  94. package/batteries/llm/openai_responses.cjs +2 -2
  95. package/batteries/llm/openai_responses.mjs +2 -2
  96. package/batteries/llm/transformers_js/adapter.cjs +6 -6
  97. package/batteries/llm/transformers_js/adapter.mjs +6 -6
  98. package/batteries/llm/transformers_js/helpers.cjs +3 -3
  99. package/batteries/llm/transformers_js/helpers.mjs +3 -3
  100. package/batteries/llm/transformers_js/validation.cjs +2 -2
  101. package/batteries/llm/transformers_js/validation.mjs +2 -2
  102. package/batteries/llm/transformers_js.cjs +1 -1
  103. package/batteries/llm/transformers_js.mjs +1 -1
  104. package/batteries/llm/webllm_chat_completions/adapter.cjs +6 -6
  105. package/batteries/llm/webllm_chat_completions/adapter.mjs +6 -6
  106. package/batteries/llm/webllm_chat_completions/helpers.cjs +1 -1
  107. package/batteries/llm/webllm_chat_completions/helpers.mjs +1 -1
  108. package/batteries/llm/webllm_chat_completions/validation.cjs +2 -2
  109. package/batteries/llm/webllm_chat_completions/validation.mjs +2 -2
  110. package/batteries/llm/webllm_chat_completions.cjs +2 -2
  111. package/batteries/llm/webllm_chat_completions.mjs +2 -2
  112. package/batteries/llm.cjs +2 -2
  113. package/batteries/llm.mjs +2 -2
  114. package/batteries/media/forge.cjs +4 -4
  115. package/batteries/media/forge.mjs +4 -4
  116. package/batteries/media/lint.cjs +1 -1
  117. package/batteries/media/lint.mjs +1 -1
  118. package/batteries/orchestration/cells/jexl.cjs +1 -1
  119. package/batteries/orchestration/cells/jexl.mjs +1 -1
  120. package/batteries/orchestration/cells/lua.cjs +1 -1
  121. package/batteries/orchestration/cells/lua.mjs +1 -1
  122. package/batteries/orchestration/cells/structured.cjs +1 -1
  123. package/batteries/orchestration/cells/structured.mjs +1 -1
  124. package/batteries/orchestration/dispatch_reasoner.cjs +4 -4
  125. package/batteries/orchestration/dispatch_reasoner.mjs +4 -4
  126. package/batteries/orchestration/executor.cjs +2 -2
  127. package/batteries/orchestration/executor.mjs +2 -2
  128. package/batteries/orchestration/forge.cjs +3 -3
  129. package/batteries/orchestration/forge.mjs +3 -3
  130. package/batteries/orchestration/validation.cjs +2 -2
  131. package/batteries/orchestration/validation.mjs +2 -2
  132. package/batteries/orchestration.cjs +3 -3
  133. package/batteries/orchestration.mjs +3 -3
  134. package/batteries/sandbox/js.cjs +1 -1
  135. package/batteries/sandbox/js.mjs +1 -1
  136. package/batteries/sandbox/tools.cjs +1 -1
  137. package/batteries/sandbox/tools.mjs +1 -1
  138. package/batteries/sandbox.cjs +4 -4
  139. package/batteries/sandbox.mjs +4 -4
  140. package/batteries/skills/in_memory.cjs +1 -1
  141. package/batteries/skills/in_memory.mjs +1 -1
  142. package/batteries/skills.cjs +9 -9
  143. package/batteries/skills.mjs +9 -9
  144. package/batteries/specialists/stt/transformers_js.cjs +1 -1
  145. package/batteries/specialists/stt/transformers_js.mjs +1 -1
  146. package/batteries/specialists/stt.cjs +1 -1
  147. package/batteries/specialists/stt.mjs +1 -1
  148. package/batteries/specialists.cjs +1 -1
  149. package/batteries/specialists.mjs +1 -1
  150. package/batteries/tools/_shared.cjs +2 -2
  151. package/batteries/tools/_shared.mjs +2 -2
  152. package/batteries/tools/color.cjs +2 -2
  153. package/batteries/tools/color.mjs +2 -2
  154. package/batteries/tools/comparison.cjs +2 -2
  155. package/batteries/tools/comparison.mjs +2 -2
  156. package/batteries/tools/data_structure.cjs +2 -2
  157. package/batteries/tools/data_structure.mjs +2 -2
  158. package/batteries/tools/datetime_extended.cjs +2 -2
  159. package/batteries/tools/datetime_extended.mjs +2 -2
  160. package/batteries/tools/datetime_math.cjs +2 -2
  161. package/batteries/tools/datetime_math.mjs +2 -2
  162. package/batteries/tools/encoding.cjs +2 -2
  163. package/batteries/tools/encoding.mjs +2 -2
  164. package/batteries/tools/formatting.cjs +2 -2
  165. package/batteries/tools/formatting.mjs +2 -2
  166. package/batteries/tools/geo_basics.cjs +2 -2
  167. package/batteries/tools/geo_basics.mjs +2 -2
  168. package/batteries/tools/math.cjs +2 -2
  169. package/batteries/tools/math.mjs +2 -2
  170. package/batteries/tools/memory.cjs +4 -4
  171. package/batteries/tools/memory.mjs +4 -4
  172. package/batteries/tools/parsing.cjs +3 -3
  173. package/batteries/tools/parsing.mjs +3 -3
  174. package/batteries/tools/retrievables.cjs +4 -4
  175. package/batteries/tools/retrievables.mjs +4 -4
  176. package/batteries/tools/scrapper.cjs +1 -1
  177. package/batteries/tools/scrapper.mjs +1 -1
  178. package/batteries/tools/searxng.cjs +1 -1
  179. package/batteries/tools/searxng.mjs +1 -1
  180. package/batteries/tools/standing_instructions.cjs +3 -3
  181. package/batteries/tools/standing_instructions.mjs +3 -3
  182. package/batteries/tools/statistics.cjs +3 -3
  183. package/batteries/tools/statistics.mjs +3 -3
  184. package/batteries/tools/string_processing.cjs +2 -2
  185. package/batteries/tools/string_processing.mjs +2 -2
  186. package/batteries/tools/structured_data.cjs +2 -2
  187. package/batteries/tools/structured_data.mjs +2 -2
  188. package/batteries/tools/text_analysis.cjs +3 -3
  189. package/batteries/tools/text_analysis.mjs +3 -3
  190. package/batteries/tools/text_comparison.cjs +2 -2
  191. package/batteries/tools/text_comparison.mjs +2 -2
  192. package/batteries/tools/time.cjs +2 -2
  193. package/batteries/tools/time.mjs +2 -2
  194. package/batteries/tools/unit_conversion.cjs +2 -2
  195. package/batteries/tools/unit_conversion.mjs +2 -2
  196. package/batteries/tools.cjs +2 -2
  197. package/batteries/tools.mjs +2 -2
  198. package/batteries/validation.cjs +5 -5
  199. package/batteries/validation.mjs +5 -5
  200. package/batteries/vector/conformance.cjs +59 -0
  201. package/batteries/vector/conformance.cjs.map +1 -1
  202. package/batteries/vector/conformance.mjs +59 -0
  203. package/batteries/vector/conformance.mjs.map +1 -1
  204. package/batteries/vector/lancedb.cjs +1 -1
  205. package/batteries/vector/lancedb.cjs.map +1 -1
  206. package/batteries/vector/lancedb.mjs +1 -1
  207. package/batteries/vector/lancedb.mjs.map +1 -1
  208. package/batteries/vector/retrievable.cjs +1 -1
  209. package/batteries/vector/retrievable.mjs +1 -1
  210. package/batteries/vector/sqlite_vec/index.d.ts +1 -1
  211. package/batteries/vector/sqlite_vec.cjs +19 -30
  212. package/batteries/vector/sqlite_vec.cjs.map +1 -1
  213. package/batteries/vector/sqlite_vec.mjs +20 -31
  214. package/batteries/vector/sqlite_vec.mjs.map +1 -1
  215. package/batteries.cjs +6 -6
  216. package/batteries.mjs +6 -6
  217. package/{chat_common-4huaTp6d.cjs → chat_common-CNayzS1V.cjs} +2 -2
  218. package/{chat_common-4huaTp6d.cjs.map → chat_common-CNayzS1V.cjs.map} +1 -1
  219. package/{chat_common-D_XGNjcK.mjs → chat_common-DKw8FDol.mjs} +2 -2
  220. package/{chat_common-D_XGNjcK.mjs.map → chat_common-DKw8FDol.mjs.map} +1 -1
  221. package/{common-BiRzOsxe.cjs → common-CqetsItm.cjs} +7 -7
  222. package/{common-BiRzOsxe.cjs.map → common-CqetsItm.cjs.map} +1 -1
  223. package/{common-DsLvTGmm.mjs → common-oI1niK9Z.mjs} +7 -7
  224. package/{common-DsLvTGmm.mjs.map → common-oI1niK9Z.mjs.map} +1 -1
  225. package/common.cjs +7 -7
  226. package/common.mjs +7 -7
  227. package/{dispatch_runner-DDH_dGPU.mjs → dispatch_runner-BZDXUe0G.mjs} +4 -4
  228. package/{dispatch_runner-DDH_dGPU.mjs.map → dispatch_runner-BZDXUe0G.mjs.map} +1 -1
  229. package/{dispatch_runner-C5S3KCqH.cjs → dispatch_runner-DDUxXJC3.cjs} +4 -4
  230. package/{dispatch_runner-C5S3KCqH.cjs.map → dispatch_runner-DDUxXJC3.cjs.map} +1 -1
  231. package/dispatch_runner.cjs +1 -1
  232. package/dispatch_runner.mjs +1 -1
  233. package/{ecmascript-CWLZ7bCX.mjs → ecmascript-B9Z2C24U.mjs} +5 -5
  234. package/{ecmascript-CWLZ7bCX.mjs.map → ecmascript-B9Z2C24U.mjs.map} +1 -1
  235. package/{ecmascript-BGr_0Dwn.cjs → ecmascript-BYfmjg7y.cjs} +5 -5
  236. package/{ecmascript-BGr_0Dwn.cjs.map → ecmascript-BYfmjg7y.cjs.map} +1 -1
  237. package/eslint/rules.cjs +1 -1
  238. package/eslint/rules.mjs +1 -1
  239. package/eslint.cjs +3 -3
  240. package/eslint.mjs +3 -3
  241. package/exceptions.cjs +1 -1
  242. package/exceptions.mjs +1 -1
  243. package/forge.cjs +2 -2
  244. package/forge.mjs +2 -2
  245. package/guards.cjs +7 -7
  246. package/guards.mjs +7 -7
  247. package/{helpers-BPi_iwxv.cjs → helpers-DPlh_7Bn.cjs} +3 -3
  248. package/{helpers-BPi_iwxv.cjs.map → helpers-DPlh_7Bn.cjs.map} +1 -1
  249. package/{helpers-D47G8WQb.mjs → helpers-mbn_EsDV.mjs} +3 -3
  250. package/{helpers-D47G8WQb.mjs.map → helpers-mbn_EsDV.mjs.map} +1 -1
  251. package/index.cjs +11 -11
  252. package/index.mjs +11 -11
  253. package/{isolation-B2FgKbap.cjs → isolation-B01xCIoV.cjs} +2 -2
  254. package/{isolation-B2FgKbap.cjs.map → isolation-B01xCIoV.cjs.map} +1 -1
  255. package/{isolation-BRGpiU-K.mjs → isolation-CO0NiK8R.mjs} +2 -2
  256. package/{isolation-BRGpiU-K.mjs.map → isolation-CO0NiK8R.mjs.map} +1 -1
  257. package/{manifest-B5bWMHgj.mjs → manifest-D8UTRohY.mjs} +2 -2
  258. package/{manifest-B5bWMHgj.mjs.map → manifest-D8UTRohY.mjs.map} +1 -1
  259. package/{manifest-Chjh-3s1.cjs → manifest-IP1IOJcg.cjs} +2 -2
  260. package/{manifest-Chjh-3s1.cjs.map → manifest-IP1IOJcg.cjs.map} +1 -1
  261. package/mcp/adk-docs-corpus.json +2 -2
  262. package/package.json +538 -538
  263. package/{predicates-C9jl2QPZ.cjs → predicates-Bzaa7gNI.cjs} +2 -2
  264. package/{predicates-C9jl2QPZ.cjs.map → predicates-Bzaa7gNI.cjs.map} +1 -1
  265. package/{predicates-2dZQ82LY.mjs → predicates-CM27Z3TF.mjs} +2 -2
  266. package/{predicates-2dZQ82LY.mjs.map → predicates-CM27Z3TF.mjs.map} +1 -1
  267. package/{retrievable-ReauMJxJ.cjs → retrievable-Bq-O3k6r.cjs} +3 -3
  268. package/{retrievable-ReauMJxJ.cjs.map → retrievable-Bq-O3k6r.cjs.map} +1 -1
  269. package/{retrievable-mFgC1aty.mjs → retrievable-CXTAUuuv.mjs} +3 -3
  270. package/{retrievable-mFgC1aty.mjs.map → retrievable-CXTAUuuv.mjs.map} +1 -1
  271. package/{scrapper-BsEY0Wo6.cjs → scrapper-B8xG9lTD.cjs} +5 -5
  272. package/{scrapper-BsEY0Wo6.cjs.map → scrapper-B8xG9lTD.cjs.map} +1 -1
  273. package/{scrapper-bShwZxKP.mjs → scrapper-DiQ5FfDL.mjs} +5 -5
  274. package/{scrapper-bShwZxKP.mjs.map → scrapper-DiQ5FfDL.mjs.map} +1 -1
  275. package/{searxng-CAY-bOMl.mjs → searxng-BFTJ6rTE.mjs} +5 -5
  276. package/{searxng-CAY-bOMl.mjs.map → searxng-BFTJ6rTE.mjs.map} +1 -1
  277. package/{searxng-CLF0vBMT.cjs → searxng-EJhWRnIE.cjs} +5 -5
  278. package/{searxng-CLF0vBMT.cjs.map → searxng-EJhWRnIE.cjs.map} +1 -1
  279. package/server.json +2 -2
  280. package/skills/adk-assembly/SKILL.md +2 -2
  281. package/{spooled_artifact-CFjf6ULg.cjs → spooled_artifact---DmicFW.cjs} +384 -384
  282. package/spooled_artifact---DmicFW.cjs.map +1 -0
  283. package/{spooled_artifact-B710Rb0d.mjs → spooled_artifact-Bw_7swIp.mjs} +385 -385
  284. package/spooled_artifact-Bw_7swIp.mjs.map +1 -0
  285. package/spooled_artifact.cjs +2 -2
  286. package/spooled_artifact.mjs +2 -2
  287. package/{spooled_markdown_artifact-PWppwnPQ.cjs → spooled_markdown_artifact-Rjzj-kyh.cjs} +3 -3
  288. package/{spooled_markdown_artifact-PWppwnPQ.cjs.map → spooled_markdown_artifact-Rjzj-kyh.cjs.map} +1 -1
  289. package/{spooled_markdown_artifact-1C4mmi73.mjs → spooled_markdown_artifact-vd6eNtIP.mjs} +3 -3
  290. package/{spooled_markdown_artifact-1C4mmi73.mjs.map → spooled_markdown_artifact-vd6eNtIP.mjs.map} +1 -1
  291. package/{thought-BKXwUZoq.mjs → thought-CxSaF6Xf.mjs} +3 -3
  292. package/{thought-BKXwUZoq.mjs.map → thought-CxSaF6Xf.mjs.map} +1 -1
  293. package/{thought-D5fJsxBW.cjs → thought-Dp3sMWW6.cjs} +3 -3
  294. package/{thought-D5fJsxBW.cjs.map → thought-Dp3sMWW6.cjs.map} +1 -1
  295. package/{tokenizable-DDIdXbJN.cjs → tokenizable-BcodRtoW.cjs} +29 -29
  296. package/{tokenizable-DDIdXbJN.cjs.map → tokenizable-BcodRtoW.cjs.map} +1 -1
  297. package/{tokenizable-xPXj1AQX.mjs → tokenizable-VB4Av8GF.mjs} +30 -30
  298. package/{tokenizable-xPXj1AQX.mjs.map → tokenizable-VB4Av8GF.mjs.map} +1 -1
  299. package/{tool_call-CDV5pW13.cjs → tool_call-B9px4W9k.cjs} +3 -3
  300. package/{tool_call-CDV5pW13.cjs.map → tool_call-B9px4W9k.cjs.map} +1 -1
  301. package/{tool_call-D-LqMvpU.mjs → tool_call-Cfaj-6zK.mjs} +3 -3
  302. package/{tool_call-D-LqMvpU.mjs.map → tool_call-Cfaj-6zK.mjs.map} +1 -1
  303. package/{tools-CvCMdAd7.mjs → tools-D0MBDh2R.mjs} +6 -6
  304. package/{tools-CvCMdAd7.mjs.map → tools-D0MBDh2R.mjs.map} +1 -1
  305. package/{tools-CACuuMV4.cjs → tools-aNbi6JyA.cjs} +6 -6
  306. package/{tools-CACuuMV4.cjs.map → tools-aNbi6JyA.cjs.map} +1 -1
  307. package/{toon-CCjuuzd_.mjs → toon-BSTQnHed.mjs} +6 -6
  308. package/{toon-CCjuuzd_.mjs.map → toon-BSTQnHed.mjs.map} +1 -1
  309. package/{toon-B7Q9RWJF.cjs → toon-DmLwZ6H1.cjs} +6 -6
  310. package/{toon-B7Q9RWJF.cjs.map → toon-DmLwZ6H1.cjs.map} +1 -1
  311. package/{transformers_js-DM01eAzh.cjs → transformers_js-7OzeS_Tp.cjs} +2 -2
  312. package/{transformers_js-DM01eAzh.cjs.map → transformers_js-7OzeS_Tp.cjs.map} +1 -1
  313. package/{transformers_js-BR2Ov0Su.mjs → transformers_js-p3lAkHFH.mjs} +2 -2
  314. package/{transformers_js-BR2Ov0Su.mjs.map → transformers_js-p3lAkHFH.mjs.map} +1 -1
  315. package/{turn_runner-BgPw9uqb.mjs → turn_runner-BHHD6h77.mjs} +4 -4
  316. package/{turn_runner-BgPw9uqb.mjs.map → turn_runner-BHHD6h77.mjs.map} +1 -1
  317. package/{turn_runner-CP2zxSlu.cjs → turn_runner-Dj7JsUTQ.cjs} +4 -4
  318. package/{turn_runner-CP2zxSlu.cjs.map → turn_runner-Dj7JsUTQ.cjs.map} +1 -1
  319. package/turn_runner.cjs +1 -1
  320. package/turn_runner.mjs +1 -1
  321. package/{xml-BqTTIFhv.mjs → xml-CYseDztH.mjs} +6 -6
  322. package/{xml-BqTTIFhv.mjs.map → xml-CYseDztH.mjs.map} +1 -1
  323. package/{xml-viE54OTe.cjs → xml-zJul8jMQ.cjs} +6 -6
  324. package/{xml-viE54OTe.cjs.map → xml-zJul8jMQ.cjs.map} +1 -1
  325. package/{yaml-B1So-pUR.mjs → yaml-BPBoiOjx.mjs} +6 -6
  326. package/{yaml-B1So-pUR.mjs.map → yaml-BPBoiOjx.mjs.map} +1 -1
  327. package/{yaml-cGhhPyZq.cjs → yaml-D0PzoRAr.cjs} +6 -6
  328. package/{yaml-cGhhPyZq.cjs.map → yaml-D0PzoRAr.cjs.map} +1 -1
  329. package/artifact_methods-9BemAvd4.mjs +0 -1
  330. package/artifact_methods-FKgk4q_1.cjs +0 -1
  331. package/spooled_artifact-B710Rb0d.mjs.map +0 -1
  332. package/spooled_artifact-CFjf6ULg.cjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"tool_call-CDV5pW13.cjs","names":["#id","#kind","#mimeType","#filename","#source","#trustTier","#modalityHazard","#reader","#stash","#id","#tool","#args","#checksum","#isComplete","#isError","#results","#payload","#replayCompatibility","#fromArtifactTool","#inline","#createdAt","#updatedAt","#completedAt"],"sources":["../src/lib/helpers/base64.ts","../src/lib/contracts/media_reader.ts","../src/lib/classes/media.ts","../src/lib/classes/tool_call.ts"],"sourcesContent":["/**\n * Cross-environment base64 helpers for `Uint8Array` payloads.\n *\n * @module\n *\n * @remarks\n * Used by {@link @nhtio/adk!Media}'s `asBase64()` and by the in-memory reader handle path\n * (`describe()`/resolver), which inlines its buffer as base64 because it owns no external locator. Both\n * directions prefer Node's `Buffer` when present and fall back to `btoa`/`atob` with a chunked window so\n * large buffers do not overflow the call stack.\n */\n\ninterface MinimalBuffer {\n from(input: Uint8Array): { toString(enc: string): string }\n from(input: string, enc: string): Uint8Array\n}\n\nconst getBuffer = (): MinimalBuffer | undefined => {\n return (globalThis as { Buffer?: MinimalBuffer }).Buffer\n}\n\n/**\n * Encode a `Uint8Array` as a base64 string.\n *\n * @remarks\n * Prefers `Buffer.from(bytes).toString('base64')` when `globalThis.Buffer` exists; otherwise\n * chunk-encodes through `btoa` with a `0x8000`-byte window to avoid `Maximum call stack size exceeded`\n * on large buffers.\n *\n * @param bytes - The buffer to encode.\n * @returns The base64 representation.\n */\nexport const encodeBase64 = (bytes: Uint8Array): string => {\n const buffer = getBuffer()\n if (buffer && typeof buffer.from === 'function') {\n return buffer.from(bytes).toString('base64')\n }\n const chunkSize = 0x8000\n let binary = ''\n for (let i = 0; i < bytes.length; i += chunkSize) {\n const chunk = bytes.subarray(i, i + chunkSize)\n binary += String.fromCharCode.apply(null, Array.from(chunk) as number[])\n }\n return btoa(binary)\n}\n\n/**\n * Decode a base64 string back into a `Uint8Array`.\n *\n * @remarks\n * Inverse of {@link encodeBase64}. Prefers `Buffer.from(b64, 'base64')` when `globalThis.Buffer` exists;\n * otherwise decodes through `atob` byte-by-byte.\n *\n * @param b64 - The base64 string to decode.\n * @returns The decoded bytes.\n */\nexport const decodeBase64 = (b64: string): Uint8Array => {\n const buffer = getBuffer()\n if (buffer && typeof buffer.from === 'function') {\n const decoded = buffer.from(b64, 'base64')\n // `Buffer` is a `Uint8Array` subclass; return a plain view over the same bytes.\n return new Uint8Array(decoded)\n }\n const binary = atob(b64)\n const out = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) {\n out[i] = binary.charCodeAt(i)\n }\n return out\n}\n","import { validator } from '@nhtio/validation'\nimport { passesSchema } from '../utils/validation'\nimport type { ReaderDescriptor } from './reader_descriptor'\n\n/**\n * Re-openable byte source contract for a Media instance.\n *\n * @remarks\n * Peer to {@link @nhtio/adk!SpoolReader} but tuned for binary streaming rather than line-indexed text.\n * Each `stream()` call must return a fresh, drainable `ReadableStream` over the same underlying\n * bytes — implementations model replay: in-memory readers reconstitute the stream from the\n * buffer, file-backed readers reopen the file handle, HTTP-backed readers re-issue the fetch,\n * cloud blob readers re-issue the GET. The implementor owns the storage and the cost of keeping\n * the underlying source addressable. Implementors whose underlying source is genuinely\n * non-replayable (a raw HTTP body they were handed once) are responsible for caching locally\n * before constructing the Media.\n *\n * Both methods may be synchronous or asynchronous to accommodate both in-memory and I/O-backed\n * implementations without forcing unnecessary promise overhead on simple cases.\n */\nexport interface MediaReader {\n /**\n * Re-opens the underlying byte source and returns a fresh ReadableStream.\n *\n * @remarks\n * Each call yields a new, drainable stream over the same bytes. Render code that needs the\n * full buffer (e.g. base64-encoding an inline image_url) drains the stream; render code that\n * can forward the stream (e.g. multipart upload) passes the stream through without buffering.\n *\n * @returns A drainable ReadableStream of Uint8Array chunks over the underlying bytes.\n */\n stream(): ReadableStream<Uint8Array> | Promise<ReadableStream<Uint8Array>>\n\n /**\n * Returns the total number of bytes in the underlying data, or `undefined` if unknown.\n *\n * @remarks\n * Used for telemetry, budget checks, and pre-flight provider size validation without forcing\n * a stream drain. Sources of unknown length may return `undefined` — absence is treated as\n * \"unknown\", not \"zero\".\n *\n * @returns The byte length of the underlying data, or `undefined` when unknown.\n */\n byteLength(): number | undefined | Promise<number | undefined>\n\n /**\n * Optionally emit a serialisable {@link ReaderDescriptor} so a {@link @nhtio/adk!Media} backed by this\n * reader can round-trip through `encode()`/`decode()` as a **handle**.\n *\n * @remarks\n * Synchronous by contract — the encoder's `[ENCODE_METHOD]()` is synchronous and cannot await, so a\n * reader whose handle is only obtainable asynchronously (e.g. draining a `Blob`) must NOT implement\n * this method; encoding such a `Media` throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE}. The\n * descriptor describes *where the bytes live* (a key, a URL, or an inlined buffer) — never the live\n * binding (`Disk`, OPFS root, `fetch`), which the matching resolver re-injects on decode.\n *\n * A reader that omits this method is treated as non-describable: the bytes still stream normally at\n * runtime, the `Media` simply cannot be serialised.\n *\n * @returns A tagged, serialisable handle, or `undefined`/absent when the reader cannot describe itself.\n */\n describe?(): ReaderDescriptor | undefined\n}\n\n/**\n * Validator schema used to validate a MediaReader value.\n *\n * @remarks\n * Because MediaReader is a structural interface with no associated constructor, validation is\n * duck-typed: the value must be an object, class instance, or function with `stream` and\n * `byteLength` present as callable properties. Arity is not enforced.\n */\nexport const mediaReaderSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).stream === 'function' &&\n typeof (value as any).byteLength === 'function'\n ) {\n return value as MediaReader\n }\n return helpers.error('any.invalid')\n })\n\n/**\n * Returns `true` if `value` implements the MediaReader interface.\n *\n * @remarks\n * Duck-typed: checks that `value` is non-null with `stream` and `byteLength` as callable\n * functions. Does not use `instanceof` — there is no MediaReader constructor.\n *\n * @param value - The value to test.\n * @returns `true` when `value` conforms to the MediaReader interface.\n */\nexport const implementsMediaReader = (value: unknown): value is MediaReader => {\n return passesSchema(mediaReaderSchema, value)\n}\n","import { v6 as uuidv6 } from 'uuid'\nimport { Registry } from './registry'\nimport { isError } from '../utils/guards'\nimport { validator } from '@nhtio/validation'\nimport { isInstanceOf } from '../utils/guards'\nimport { encodeBase64 } from '../helpers/base64'\nimport { validateOrThrow } from '../utils/validation'\nimport { resolveMediaReader } from '../contracts/reader_resolvers'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../utils/encoder_symbols'\nimport { implementsMediaReader, mediaReaderSchema } from '../contracts/media_reader'\nimport {\n E_INVALID_INITIAL_MEDIA_VALUE,\n E_NOT_A_MEDIA_READER,\n E_READER_NOT_DESCRIBABLE,\n} from '../exceptions/runtime'\nimport type { AdkEncodableSnapshot } from './encodable'\nimport type { MediaReader } from '../contracts/media_reader'\nimport type { ReaderDescriptor } from '../contracts/reader_descriptor'\n\n/**\n * The set of supported media kinds.\n *\n * @remarks\n * Modality coverage is asymmetric across providers. The framework defines no\n * `supportedModalities` field — how a battery handles a modality it cannot natively render is\n * the battery author's call (see `unsupportedMediaPolicy` on the OpenAI Chat Completions\n * battery).\n */\nexport const MediaKind = ['image', 'audio', 'video', 'document'] as const\n\n/**\n * Union of all recognised media kind identifier strings.\n */\nexport type MediaKind = (typeof MediaKind)[number]\n\n/**\n * Provenance axis. *Who is the framework willing to vouch for as the source of these bytes?*\n *\n * @remarks\n * Mirrors `RetrievableTrustTier` deliberately — same vocabulary, same question:\n * *did this content come from a place the agent should treat as authoritative?*\n *\n * - `'first-party'` — deployer-vetted bytes (tool output the operator authored, signed\n * internal assets).\n * - `'third-party-public'` — open-web fetches, public APIs, public corpora.\n * - `'third-party-private'` — user uploads, partner APIs, private corpora.\n */\nexport const MediaTrustTier = ['first-party', 'third-party-public', 'third-party-private'] as const\nexport type MediaTrustTier = (typeof MediaTrustTier)[number]\n\n/**\n * Modality-hazard axis. *How dangerous is it to let the model decode these bytes?*\n *\n * @remarks\n * Orthogonal to provenance — a first-party trusted PDF can still carry hidden text layers; a\n * third-party-public raw image can still be encoded as opaque pixels with adversarial\n * perturbations.\n *\n * - `'inert'` — bytes the model never decodes as instructions (e.g. a handle that is never\n * inlined into the prompt).\n * - `'extractable-instructions'` — text-bearing media: PDFs, screenshots with UI text, documents.\n * Hazard is OCR / embedded-text-layer reads.\n * - `'opaque-perceptual'` — raw vision/audio/video the model encodes directly. Hazard is\n * steganographic LSB prompts, adversarial perturbations, ultrasonic audio — invisible to any\n * pre-screen.\n *\n * See `/the-loop/trust-tiers/media` and its research sub-page `/the-loop/trust-tiers/media/research`.\n */\nexport const MediaModalityHazard = [\n 'inert',\n 'extractable-instructions',\n 'opaque-perceptual',\n] as const\nexport type MediaModalityHazard = (typeof MediaModalityHazard)[number]\n\n/**\n * Per-entry shape stored in a {@link Media}'s `stash` register.\n *\n * @remarks\n * Each entry carries its own trust tier so render code can route derived text (OCR, captions,\n * transcripts) through its own envelope independent of the parent media. How a battery or\n * middleware assigns those entry-level tiers is the implementor's call — the primitive contract\n * does not enforce a \"downgrade derived interpretation from possibly-adversarial bytes\" policy.\n */\nexport interface MediaStashEntry {\n /** The value of the entry — any serialisable shape the consumer wants to store. */\n value: unknown\n /** Trust tier for this specific entry; routed independently of the parent media. */\n trustTier: MediaTrustTier\n /** Optional pointer to the parent Media id this entry was derived from. */\n derivedFromMedia?: string\n}\n\n/**\n * Plain input object supplied to {@link Media} at construction time.\n *\n * @remarks\n * Validated against `rawMediaSchema` before the `Media` instance is created.\n */\nexport interface RawMedia {\n /**\n * Stable unique identifier for this media instance. Required for strict symmetry with\n * `Message.id` and `ToolCall.id`. When omitted, a fresh UUIDv6 is assigned at construction\n * time.\n */\n id?: string\n /** The media kind. See {@link MediaKind}. */\n kind: MediaKind\n /** The MIME type of the underlying bytes. */\n mimeType: string\n /** Filename used by providers that key on it (e.g. OpenAI `file.filename`). */\n filename: string\n /** Re-openable byte source. See {@link @nhtio/adk!MediaReader}. */\n reader: MediaReader\n /**\n * Trust tier declared at construction time. Required — there is NO default.\n * See {@link MediaTrustTier}.\n */\n trustTier: MediaTrustTier\n /**\n * Modality hazard declared at construction time. Required — there is NO default.\n * See {@link MediaModalityHazard}.\n */\n modalityHazard: MediaModalityHazard\n /** Optional provenance pointer (URL, tool name, etc.) for audit / events. */\n source?: string\n /**\n * Free-form per-instance metadata register. Middleware pipelines append to this — typically\n * with a text description, transcript, caption, or alt-text — so downstream code that cannot\n * consume the media natively has a model-readable fallback. No keys are reserved by the\n * framework. Defaults to `{}`.\n */\n stash?: Record<string, MediaStashEntry>\n}\n\nconst stashEntrySchema = validator\n .object<MediaStashEntry>({\n value: validator.any().required(),\n trustTier: validator\n .string()\n .valid(...MediaTrustTier)\n .required(),\n derivedFromMedia: validator.string().optional(),\n })\n .unknown(false)\n\n/**\n * Validator schema used to validate a {@link RawMedia} before constructing a {@link Media}.\n */\nconst rawMediaSchema = validator.object<RawMedia>({\n id: validator.string().optional(),\n kind: validator\n .string()\n .valid(...MediaKind)\n .required(),\n mimeType: validator.string().required(),\n filename: validator.string().required(),\n reader: mediaReaderSchema.required(),\n trustTier: validator\n .string()\n .valid(...MediaTrustTier)\n .required(),\n modalityHazard: validator\n .string()\n .valid(...MediaModalityHazard)\n .required(),\n source: validator.string().optional(),\n stash: validator.object().pattern(validator.string(), stashEntrySchema).optional(),\n})\n\ninterface ResolvedMedia {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n trustTier: MediaTrustTier\n modalityHazard: MediaModalityHazard\n source?: string\n stash?: Record<string, MediaStashEntry>\n}\n\nconst conservativeHazardForKind = (kind: MediaKind): MediaModalityHazard => {\n return kind === 'document' ? 'extractable-instructions' : 'opaque-perceptual'\n}\n\n/**\n * Shape returned by {@link Media.toJSON}. Metadata-only — bytes and the reader are stripped so\n * naive event/log serialisation never materialises bytes.\n */\n/** The plain-object, JSON-safe form of a {@link Media} produced by {@link Media.toJSON}. */\nexport interface SerializedMedia {\n /** Stable identifier for this media asset. */\n id: string\n /** High-level modality of the asset (e.g. image, audio, document). */\n kind: MediaKind\n /** MIME type of the underlying bytes (e.g. `image/png`). */\n mimeType: string\n /** Original or suggested file name for the asset. */\n filename: string\n /** Optional provenance string (URL, path, or other origin marker). */\n source?: string\n /** Trust tier governing how the asset's content is framed to the model. */\n trustTier: MediaTrustTier\n /** Whether the modality can carry hidden instructions (`extractable-instructions`) or is opaque-perceptual. */\n modalityHazard: MediaModalityHazard\n /** Adapter-scoped side-channel data keyed by name (e.g. provider upload handles). */\n stash: Record<string, MediaStashEntry>\n /** Size of the underlying bytes in bytes, when known. */\n byteLength?: number\n}\n\n/**\n * Lazy, re-openable view over a binary asset (image, audio, video, document).\n *\n * @remarks\n * Dual-peer to {@link @nhtio/adk!Tokenizable} (silo) and {@link @nhtio/adk!SpooledArtifact}\n * (handle). Wraps a {@link @nhtio/adk!MediaReader} contract — the framework owns the contract, the\n * implementor owns the storage backend. Bytes are reached only through the reader; the primitive\n * itself never inlines bytes.\n *\n * Construction requires `trustTier` and `modalityHazard` — the framework refuses to guess\n * provenance or decoding hazard. Ergonomic factories ({@link Media.userAttachment},\n * {@link Media.toolGenerated}, {@link Media.retrievedPublic}, {@link Media.retrievedPrivate})\n * force the labelling decision at the call site without becoming defaults on the bare\n * constructor.\n */\nexport class Media {\n /**\n * Validator schema that accepts a {@link RawMedia} object.\n */\n public static schema = rawMediaSchema\n\n /**\n * The set of recognised media kinds. Exposed for downstream schemas that need to discriminate\n * on `kind`.\n */\n public static MediaKind = MediaKind\n\n /**\n * The set of recognised trust tiers.\n */\n public static MediaTrustTier = MediaTrustTier\n\n /**\n * The set of recognised modality hazards.\n */\n public static MediaModalityHazard = MediaModalityHazard\n\n /**\n * Returns `true` if `value` is a {@link Media} 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 Media} instance.\n */\n public static isMedia(value: unknown): value is Media {\n return isInstanceOf(value, 'Media', Media)\n }\n\n /** Stable unique identifier. */\n declare readonly id: string\n /** Media kind. */\n declare readonly kind: MediaKind\n /** MIME type of the underlying bytes. */\n declare readonly mimeType: string\n /** Filename surfaced to providers that key on it. */\n declare readonly filename: string\n /** Optional provenance pointer. */\n declare readonly source: string | undefined\n /** Trust tier declared at construction time. */\n declare readonly trustTier: MediaTrustTier\n /** Modality hazard declared at construction time. */\n declare readonly modalityHazard: MediaModalityHazard\n /** Mutable per-instance metadata register; middleware pipelines append to this. */\n declare readonly stash: Registry\n\n #id: string\n #kind: MediaKind\n #mimeType: string\n #filename: string\n #source?: string\n #trustTier: MediaTrustTier\n #modalityHazard: MediaModalityHazard\n #reader: MediaReader\n #stash: Registry\n\n /**\n * @param raw - The raw media input validated against `rawMediaSchema`.\n * @throws {@link @nhtio/adk/exceptions!E_INVALID_INITIAL_MEDIA_VALUE} when `raw` does not satisfy the schema.\n * @throws {@link @nhtio/adk/exceptions!E_NOT_A_MEDIA_READER} when `raw.reader` does not implement {@link @nhtio/adk!MediaReader}.\n */\n constructor(raw: RawMedia) {\n let resolved: ResolvedMedia\n try {\n resolved = validateOrThrow<ResolvedMedia>(rawMediaSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_MEDIA_VALUE({ cause: isError(err) ? err : undefined })\n }\n if (!implementsMediaReader(resolved.reader)) {\n throw new E_NOT_A_MEDIA_READER()\n }\n this.#id = resolved.id ?? uuidv6()\n this.#kind = resolved.kind\n this.#mimeType = resolved.mimeType\n this.#filename = resolved.filename\n this.#source = resolved.source\n this.#trustTier = resolved.trustTier\n this.#modalityHazard = resolved.modalityHazard\n this.#reader = resolved.reader\n this.#stash = new Registry(resolved.stash as Record<string, unknown> | undefined)\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n kind: {\n get: () => this.#kind,\n enumerable: true,\n configurable: false,\n },\n mimeType: {\n get: () => this.#mimeType,\n enumerable: true,\n configurable: false,\n },\n filename: {\n get: () => this.#filename,\n enumerable: true,\n configurable: false,\n },\n source: {\n get: () => this.#source,\n enumerable: true,\n configurable: false,\n },\n trustTier: {\n get: () => this.#trustTier,\n enumerable: true,\n configurable: false,\n },\n modalityHazard: {\n get: () => this.#modalityHazard,\n enumerable: true,\n configurable: false,\n },\n stash: {\n get: () => this.#stash,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Re-opens the underlying byte source and returns a fresh ReadableStream.\n *\n * @returns A drainable `ReadableStream` over the underlying bytes.\n */\n async stream(): Promise<ReadableStream<Uint8Array>> {\n return this.#reader.stream()\n }\n\n /**\n * Returns the total number of bytes in the underlying data, or `undefined` if unknown.\n *\n * @returns The byte length, or `undefined` when the underlying source cannot report it.\n */\n async byteLength(): Promise<number | undefined> {\n return this.#reader.byteLength()\n }\n\n /**\n * Drains the reader's stream and returns the underlying bytes as a single `Uint8Array`.\n *\n * @remarks\n * Convenience for callers that need the full buffer (e.g. inline base64 encoding). Forces\n * full materialisation — large assets should be piped through {@link Media.stream} instead.\n */\n async asBytes(): Promise<Uint8Array> {\n const stream = await this.stream()\n const reader = stream.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n if (value) {\n chunks.push(value)\n total += value.byteLength\n }\n }\n const out = new Uint8Array(total)\n let offset = 0\n for (const chunk of chunks) {\n out.set(chunk, offset)\n offset += chunk.byteLength\n }\n return out\n }\n\n /**\n * Drains the reader's stream and returns the underlying bytes as a base64 string.\n *\n * @remarks\n * Cross-environment: prefers Node's `Buffer.from(buf).toString('base64')` when available;\n * otherwise chunk-encodes through `btoa` with a 0x8000-byte window to avoid stack overflow\n * on large buffers.\n */\n async asBase64(): Promise<string> {\n const bytes = await this.asBytes()\n return encodeBase64(bytes)\n }\n\n /**\n * Returns the metadata-only serialisation of this Media. Bytes and the reader are stripped\n * so naive event/log serialisation never materialises bytes.\n *\n * @remarks\n * Implementations that have cheap, already-cached `byteLength` may opt to include it; this\n * default implementation omits it to preserve the \"lazy by default\" invariant. Consumers that\n * need byteLength on the serialised payload should call `await media.byteLength()` and merge\n * the result.\n */\n toJSON(): SerializedMedia {\n return {\n id: this.#id,\n kind: this.#kind,\n mimeType: this.#mimeType,\n filename: this.#filename,\n source: this.#source,\n trustTier: this.#trustTier,\n modalityHazard: this.#modalityHazard,\n stash: this.#stash.all() as Record<string, MediaStashEntry>,\n }\n }\n\n /**\n * Serialise this Media into an `@nhtio/encoder` snapshot — the **handle**, never the bytes.\n *\n * @remarks\n * Emits every metadata field plus the reader's {@link @nhtio/adk!ReaderDescriptor} (via its\n * `describe()` method). The bytes are not inlined: decode re-binds the reader from the descriptor\n * through a registered resolver. Throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} when the backing\n * reader cannot describe itself (e.g. a `fromWebFile` Blob reader) — there is no serialisable handle to\n * write, and silently dropping the reader would decode into a handle pointing at nothing.\n *\n * @returns A snapshot consumed by {@link Media.[DECODE_METHOD]} / the encoder.\n * @throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} when the reader has no `describe()`.\n */\n [ENCODE_METHOD](): AdkEncodableSnapshot {\n const descriptor = this.#reader.describe?.()\n if (!descriptor) {\n throw new E_READER_NOT_DESCRIBABLE(['reader'])\n }\n return {\n id: this.#id,\n kind: this.#kind,\n mimeType: this.#mimeType,\n filename: this.#filename,\n source: this.#source,\n trustTier: this.#trustTier,\n modalityHazard: this.#modalityHazard,\n stash: this.#stash.all(),\n reader: descriptor,\n }\n }\n\n /**\n * Reconstruct a {@link Media} from an {@link Media.[ENCODE_METHOD]} snapshot.\n *\n * @remarks\n * Re-binds the reader from the captured descriptor through the registered resolver\n * ({@link @nhtio/adk!resolveMediaReader}), then re-validates via the normal constructor. Throws\n * {@link @nhtio/adk!E_NO_READER_RESOLVER} when no resolver is registered for the descriptor's tag.\n *\n * @param data - The snapshot produced by {@link Media.[ENCODE_METHOD]}.\n * @returns A fully-validated {@link Media} backed by a freshly-resolved reader.\n */\n static [DECODE_METHOD](data: AdkEncodableSnapshot): Media {\n const snapshot = data as {\n id: string\n kind: MediaKind\n mimeType: string\n filename: string\n source?: string\n trustTier: MediaTrustTier\n modalityHazard: MediaModalityHazard\n stash?: Record<string, MediaStashEntry>\n reader: ReaderDescriptor\n }\n return new Media({\n id: snapshot.id,\n kind: snapshot.kind,\n mimeType: snapshot.mimeType,\n filename: snapshot.filename,\n source: snapshot.source,\n trustTier: snapshot.trustTier,\n modalityHazard: snapshot.modalityHazard,\n stash: snapshot.stash,\n reader: resolveMediaReader(snapshot.reader),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} representing a user-supplied attachment.\n *\n * @remarks\n * Pre-fills `trustTier: 'third-party-private'` and derives `modalityHazard` from `kind`\n * (`document` → `'extractable-instructions'`; everything else → `'opaque-perceptual'`).\n * Use the bare constructor when the conservative kind→hazard mapping is wrong for your case.\n */\n public static userAttachment(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'third-party-private',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} produced by a first-party tool.\n *\n * @remarks\n * Pre-fills `trustTier: 'first-party'` and derives `modalityHazard` from `kind`.\n */\n public static toolGenerated(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'first-party',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} retrieved from a public third-party source.\n *\n * @remarks\n * Pre-fills `trustTier: 'third-party-public'` and derives `modalityHazard` from `kind`.\n */\n public static retrievedPublic(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'third-party-public',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} retrieved from a private third-party source.\n *\n * @remarks\n * Pre-fills `trustTier: 'third-party-private'` and derives `modalityHazard` from `kind`.\n */\n public static retrievedPrivate(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'third-party-private',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n}\n\n/**\n * Returns `true` if `value` is a {@link Media} instance.\n *\n * @remarks\n * Module-level convenience alias for {@link Media.isMedia}. Uses {@link @nhtio/adk!isInstanceOf} for\n * cross-realm safety.\n */\nexport const isMedia = (value: unknown): value is Media => {\n return isInstanceOf(value, 'Media', Media)\n}\n","import { Media } from './media'\nimport { Tokenizable } from './tokenizable'\nimport { validator } from '@nhtio/validation'\nimport { SpooledArtifact } from './spooled_artifact'\nimport { validateOrThrow } from '../utils/validation'\nimport { isObject, isInstanceOf, isError } from '../utils/guards'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../utils/encoder_symbols'\nimport { E_INVALID_INITIAL_TOOL_CALL_VALUE } from '../exceptions/runtime'\nimport type { DateTime } from 'luxon'\nimport type { AdkEncodableSnapshot } from './encodable'\n\n/**\n * Union of every shape a {@link ToolCall.results} field may carry.\n *\n * @remarks\n * Three silos with distinct render-time semantics:\n *\n * - {@link @nhtio/adk!Tokenizable} — always singular. The {@link @nhtio/adk!ArtifactTool}\n * carve-out: a model-visible text answer that explicitly opts out of artifact wrapping to\n * break the recursive grep-on-the-grep-result loop.\n * - {@link @nhtio/adk!SpooledArtifact} or `SpooledArtifact[]` — bounded text output spooled to durable\n * storage. A single tool call may legitimately produce multiple artifacts (e.g. one tool\n * that returns N PR bodies). LLM adapters render either inline (full body in trust envelope)\n * or as a handle reference (forged artifact-query tools).\n * - {@link @nhtio/adk!Media} or `Media[]` — binary modality output (image, audio, video, document).\n * Adapters render as provider-specific content blocks (`image_url`, `input_audio`, `file`,\n * etc.). Bytes are lazy — reached only through {@link @nhtio/adk!Media.stream}.\n */\nexport type ToolCallResults = Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[]\n\nconst isToolCallResults = (value: unknown): value is ToolCallResults => {\n if (Tokenizable.isTokenizable(value)) return true\n if (SpooledArtifact.isSpooledArtifact(value)) return true\n if (Media.isMedia(value)) return true\n if (Array.isArray(value) && value.length > 0) {\n const allMedia = value.every((entry) => Media.isMedia(entry))\n if (allMedia) return true\n const allSpooled = value.every((entry) => SpooledArtifact.isSpooledArtifact(entry))\n if (allSpooled) return true\n }\n return false\n}\n\n/**\n * Plain input object supplied to {@link ToolCall} at construction time.\n *\n * @remarks\n * Validated against `rawToolCallSchema` before the `ToolCall` instance is created.\n * Temporal fields accept any value that Luxon can parse — ISO strings, Unix timestamps,\n * `Date` objects, or existing `DateTime` instances.\n */\nexport interface RawToolCall {\n /** Stable unique identifier for this tool call; correlates the request with its result. */\n id: string\n /** Name of the tool the model has requested. */\n tool: string\n /**\n * Arguments the model supplied for this tool call.\n *\n * @remarks\n * Accepts either a plain object or a JSON-encoded string that deserialises to an object.\n * Always exposed as a plain object on the constructed {@link ToolCall} instance.\n */\n args: string | Record<string, unknown>\n /** Integrity checksum over `tool` and `args`; can be used to detect tampering before execution. */\n checksum: string\n /** `true` once the tool call has finished (successfully or not). */\n isComplete: boolean\n /** `true` when the tool execution produced an error; inspect `results` for detail. */\n isError: boolean\n /**\n * Result returned by the tool, or error detail when `isError` is `true`.\n *\n * @remarks\n * Three silos with distinct render-time semantics — see {@link ToolCallResults}:\n *\n * - For a normal {@link @nhtio/adk!Tool} call whose handler returned `string` or\n * `Uint8Array`, this is a {@link @nhtio/adk!SpooledArtifact} (or one of its subclasses) wrapping the\n * spooled bytes. Tools that legitimately produce multiple bounded artifacts may return\n * a `SpooledArtifact[]`.\n * - For a `Tool` call whose handler returned a {@link @nhtio/adk!Media} or `Media[]`, this is the same\n * media handle(s) — the explicit-modality silo bypasses `SpooledArtifact` wrapping because\n * the bytes are binary and rendered as provider-specific content blocks, not text.\n * - For an {@link @nhtio/adk!ArtifactTool} call (a forged artifact-query tool),\n * this is a {@link @nhtio/adk!Tokenizable} holding the raw model-visible answer — `ArtifactTool`\n * explicitly opts out of wrapping to break the recursive grep-on-the-grep-result loop.\n *\n * The ADK sets {@link RawToolCall.fromArtifactTool} on calls produced by an\n * `ArtifactTool` so subsequent `forgeTools(ctx)` invocations can filter them out of the\n * `callId` enum.\n */\n results: ToolCallResults\n /**\n * Optional vendor-opaque payload that round-trips back to a matching model wire.\n *\n * @remarks\n * Carries provider metadata the ADK cannot interpret, such as Gemini's `thought_signature`\n * on a function call, GPT-OSS's commentary-channel tag, or other vendor-opaque metadata\n * that a provider needs echoed back.\n *\n * A present `payload` requires a present {@link RawToolCall.replayCompatibility} so the\n * matching adapter wire shape is known.\n *\n * @defaultValue `undefined`\n */\n payload?: unknown\n /**\n * Optional free-form identifier describing which adapter wire-shape this tool call can be\n * safely replayed into.\n *\n * @remarks\n * A `replayCompatibility` without a `payload` is allowed — it documents intent without\n * requiring an opaque blob.\n *\n * @defaultValue `undefined`\n */\n replayCompatibility?: string\n /**\n * `true` when this tool call originated from an {@link @nhtio/adk!ArtifactTool}\n * invocation. Defaults to `false`.\n *\n * @remarks\n * Set by the ADK's result-wrapping touch sites when `ArtifactTool.isArtifactTool(tool)`\n * holds. Read by `SpooledArtifact.forgeTools(ctx)` when building each descriptor's `callId`\n * enum — calls with this flag set are excluded so the model can't `artifact_grep` on a\n * previous `artifact_grep` result. Optional in the raw shape (defaults to `false`); always\n * defined on the constructed {@link ToolCall}.\n *\n * @defaultValue `false`\n */\n fromArtifactTool?: boolean\n /**\n * When `false` (the default), the adapter surfaces a {@link @nhtio/adk!SpooledArtifact} result as a\n * \"handle\" — a directions-bearing envelope that tells the model which forged artifact-query tools to\n * call against this `tc.id` to read the content incrementally, keeping the body OUT of the prompt.\n * When `true`, the adapter renders the result inline — the full stringified body wrapped in the\n * adapter's trust envelope and sent to the model as the `tool` role content.\n *\n * @remarks\n * Handle-by-default is the secure, budget-aligned posture: the LLM batteries already spool-wrap every\n * non-{@link @nhtio/adk!Media}, non-{@link @nhtio/adk!ArtifactTool} tool result into a `SpooledArtifact`,\n * so a result that could be arbitrarily large never lands in the next prompt just because nobody\n * touched a flag — the core ADK context-window-diet principle (see the Budgets / Artifacts docs).\n * Inlining is the OPT-IN: a producer that knows its output is small sets `inline: true` so the model\n * sees the body verbatim without a query round-trip.\n *\n * Policy is the producer's or middleware's call (LLM adapters obey the flag — they never size-check\n * the result or silently switch modes). Set per call at construction, or flip mid-turn via\n * `ctx.mutateToolCall(tc.id, { inline: true })`.\n *\n * Handles only make sense for `SpooledArtifact` (the only result kind the forged artifact-query tools\n * can read). For a {@link @nhtio/adk!Tokenizable} result (e.g. an `ArtifactTool` answer or an error\n * string) the flag is moot — the adapter renders it inline regardless, since there is no queryable\n * artifact to hand back.\n *\n * @defaultValue `false`\n */\n inline?: boolean\n /** When this tool call was first created. */\n createdAt: string | number | Date | DateTime\n /** When this tool call was last modified. */\n updatedAt: string | number | Date | DateTime\n /** When the tool call completed. */\n completedAt: string | number | Date | DateTime\n}\n\n/**\n * A fully-resolved {@link RawToolCall} where temporal fields have been normalised to Luxon\n * `DateTime` instances.\n *\n * @remarks\n * Used internally by the {@link ToolCall} constructor to assign private fields with\n * guaranteed types.\n */\ninterface ResolvedToolCall {\n id: string\n tool: string\n args: Record<string, unknown>\n checksum: string\n isComplete: boolean\n isError: boolean\n results: ToolCallResults\n payload?: unknown\n replayCompatibility?: string\n fromArtifactTool: boolean\n inline: boolean\n createdAt: DateTime\n updatedAt: DateTime\n completedAt: DateTime\n}\n\n/**\n * Validator schema used to validate a {@link RawToolCall} before constructing a {@link ToolCall}.\n *\n * @remarks\n * Validates all fields of {@link RawToolCall}:\n * - `id` — required non-empty string.\n * - `tool` — required non-empty string.\n * - `args` — required; either a plain object or a JSON string that deserialises to an object.\n * Strings are parsed and the resulting object is stored.\n * - `checksum` — required string.\n * - `isComplete` — required boolean.\n * - `isError` — required boolean.\n * - `results` — required; one of {@link @nhtio/adk!Tokenizable}, {@link @nhtio/adk!SpooledArtifact}, a non-empty\n * `SpooledArtifact[]`, {@link @nhtio/adk!Media}, or a non-empty `Media[]`. Arrays must be homogeneous.\n * - `createdAt` / `updatedAt` / `completedAt` — required datetime-parseable values, normalised to `DateTime`.\n *\n * Throws {@link @nhtio/adk!E_INVALID_INITIAL_TOOL_CALL_VALUE} (via the {@link ToolCall} constructor) when\n * validation fails.\n */\nconst rawToolCallSchema = validator\n .object<RawToolCall>({\n id: validator.string().required(),\n tool: validator.string().required(),\n args: validator\n .alternatives(\n validator.object().unknown(true),\n validator.string().custom((value, helpers) => {\n try {\n const parsed = JSON.parse(value)\n if (!isObject(parsed)) {\n return helpers.error('any.invalid')\n }\n return parsed\n } catch {\n return helpers.error('any.invalid')\n }\n })\n )\n .required(),\n checksum: validator.string().required(),\n isComplete: validator.boolean().required(),\n isError: validator.boolean().required(),\n results: validator\n .any()\n .custom((value, helpers) => {\n if (isToolCallResults(value)) {\n return value\n }\n return helpers.error('any.invalid')\n })\n .required(),\n payload: validator.any().optional(),\n replayCompatibility: validator.string().min(1).optional(),\n fromArtifactTool: validator.boolean().default(false),\n inline: validator.boolean().default(false),\n createdAt: validator.datetime().required(),\n updatedAt: validator.datetime().required(),\n completedAt: validator.datetime().required(),\n })\n .custom((value, helpers) => {\n const v = value as RawToolCall\n const hasPayload = v.payload !== undefined && v.payload !== null\n if (hasPayload && (v.replayCompatibility === undefined || v.replayCompatibility === null)) {\n return helpers.error('any.invalid')\n }\n return value\n })\n\n/**\n * An immutable, validated tool call record associated with a turn.\n *\n * @remarks\n * Represents a completed tool invocation from the conversation history — `results`,\n * `completedAt`, `isComplete`, and `isError` are all present and required.\n * Temporal fields are normalised to Luxon `DateTime` instances at construction time.\n */\nexport class ToolCall {\n /**\n * Validator schema that accepts a {@link RawToolCall} object.\n *\n * @remarks\n * Reusable fragment for any schema that needs to validate or nest a tool call entry.\n */\n public static schema = rawToolCallSchema\n\n /**\n * Returns `true` if `value` is a {@link ToolCall} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety — `instanceof` would fail for instances\n * created in a different module copy or VM context.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link ToolCall} instance.\n */\n public static isToolCall(value: unknown): value is ToolCall {\n return isInstanceOf(value, 'ToolCall', ToolCall)\n }\n\n /** Stable unique identifier for this tool call; correlates the request with its result. */\n declare readonly id: string\n /** Name of the tool the model has requested. */\n declare readonly tool: string\n /** Arguments the model supplied for this tool call, always as a plain object. */\n declare readonly args: Record<string, unknown>\n /** Integrity checksum over `tool` and `args`. */\n declare readonly checksum: string\n /** `true` once the tool call has finished (successfully or not). */\n declare readonly isComplete: boolean\n /** `true` when the tool execution produced an error; inspect `results` for detail. */\n declare readonly isError: boolean\n /**\n * Result returned by the tool, or error detail when `isError` is `true`.\n *\n * @remarks\n * One of three silos — see {@link ToolCallResults}. {@link @nhtio/adk!SpooledArtifact} or\n * `SpooledArtifact[]` for normal text-output {@link @nhtio/adk!Tool} calls;\n * {@link @nhtio/adk!Media} or `Media[]` for tool calls whose handler returned binary modality output;\n * {@link @nhtio/adk!Tokenizable} for {@link @nhtio/adk!ArtifactTool} calls\n * (see {@link ToolCall.fromArtifactTool}).\n */\n declare readonly results: ToolCallResults\n /**\n * Optional vendor-opaque payload that round-trips back to a matching model wire.\n * See {@link RawToolCall.payload}.\n */\n declare readonly payload: unknown\n /**\n * Optional wire-shape identifier describing which adapter can safely replay this tool call.\n * See {@link RawToolCall.replayCompatibility}.\n */\n declare readonly replayCompatibility: string | undefined\n /**\n * `true` when this tool call originated from an {@link @nhtio/adk!ArtifactTool}\n * invocation. Used by `SpooledArtifact.forgeTools(ctx)` to filter out forged-tool results from\n * the `callId` enum it builds.\n */\n declare readonly fromArtifactTool: boolean\n /**\n * `false` (default) instructs LLM adapters to surface a `SpooledArtifact` result as a handle\n * reference (body kept out of the prompt); `true` renders the result inline. See\n * {@link RawToolCall.inline}.\n */\n declare readonly inline: boolean\n /** When this tool call was first created. */\n declare readonly createdAt: DateTime\n /** When this tool call was last modified. */\n declare readonly updatedAt: DateTime\n /** When the tool call completed. */\n declare readonly completedAt: DateTime\n\n #id: string\n #tool: string\n #args: Record<string, unknown>\n #checksum: string\n #isComplete: boolean\n #isError: boolean\n #results: ToolCallResults\n #payload: unknown\n #replayCompatibility: string | undefined\n #fromArtifactTool: boolean\n #inline: boolean\n #createdAt: DateTime\n #updatedAt: DateTime\n #completedAt: DateTime\n\n /**\n * @param raw - The raw tool call input validated against `rawToolCallSchema`.\n * @throws {@link @nhtio/adk!E_INVALID_INITIAL_TOOL_CALL_VALUE} when `raw` does not satisfy the schema.\n */\n constructor(raw: RawToolCall) {\n let resolved: ResolvedToolCall\n try {\n resolved = validateOrThrow<ResolvedToolCall>(rawToolCallSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_TOOL_CALL_VALUE({ cause: isError(err) ? err : undefined })\n }\n this.#id = resolved.id\n this.#tool = resolved.tool\n this.#args = resolved.args\n this.#checksum = resolved.checksum\n this.#isComplete = resolved.isComplete\n this.#isError = resolved.isError\n this.#results = resolved.results\n this.#payload = resolved.payload\n this.#replayCompatibility = resolved.replayCompatibility\n this.#fromArtifactTool = resolved.fromArtifactTool\n this.#inline = resolved.inline\n this.#createdAt = resolved.createdAt\n this.#updatedAt = resolved.updatedAt\n this.#completedAt = resolved.completedAt\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n tool: {\n get: () => this.#tool,\n enumerable: true,\n configurable: false,\n },\n args: {\n get: () => this.#args,\n enumerable: true,\n configurable: false,\n },\n checksum: {\n get: () => this.#checksum,\n enumerable: true,\n configurable: false,\n },\n isComplete: {\n get: () => this.#isComplete,\n enumerable: true,\n configurable: false,\n },\n isError: {\n get: () => this.#isError,\n enumerable: true,\n configurable: false,\n },\n results: {\n get: () => this.#results,\n enumerable: true,\n configurable: false,\n },\n payload: {\n get: () => this.#payload,\n enumerable: true,\n configurable: false,\n },\n replayCompatibility: {\n get: () => this.#replayCompatibility,\n enumerable: true,\n configurable: false,\n },\n fromArtifactTool: {\n get: () => this.#fromArtifactTool,\n enumerable: true,\n configurable: false,\n },\n inline: {\n get: () => this.#inline,\n enumerable: true,\n configurable: false,\n },\n createdAt: {\n get: () => this.#createdAt,\n enumerable: true,\n configurable: false,\n },\n updatedAt: {\n get: () => this.#updatedAt,\n enumerable: true,\n configurable: false,\n },\n completedAt: {\n get: () => this.#completedAt,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Serialise this ToolCall into an `@nhtio/encoder` snapshot.\n *\n * @remarks\n * Emits a {@link RawToolCall}-shaped object. `results` is the live {@link ToolCallResults} union —\n * a {@link @nhtio/adk!Tokenizable}, {@link @nhtio/adk!SpooledArtifact}(s), or {@link @nhtio/adk!Media}(s) —\n * which the encoder recurses into; reader-backed results round-trip as handles (and throw\n * {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} if a backing reader cannot describe itself). The `args`\n * object and the producer-supplied `checksum` are emitted verbatim, so the constructor's\n * checksum re-validation passes on decode. Round-trips via {@link ToolCall.[DECODE_METHOD]}.\n *\n * @returns A {@link RawToolCall}-shaped snapshot.\n */\n [ENCODE_METHOD](): AdkEncodableSnapshot {\n return {\n id: this.#id,\n tool: this.#tool,\n args: this.#args,\n checksum: this.#checksum,\n isComplete: this.#isComplete,\n isError: this.#isError,\n results: this.#results,\n payload: this.#payload,\n replayCompatibility: this.#replayCompatibility,\n fromArtifactTool: this.#fromArtifactTool,\n inline: this.#inline,\n createdAt: this.#createdAt,\n updatedAt: this.#updatedAt,\n completedAt: this.#completedAt,\n }\n }\n\n /**\n * Reconstruct a {@link ToolCall} from a {@link ToolCall.[ENCODE_METHOD]} snapshot.\n *\n * @param data - The snapshot produced by {@link ToolCall.[ENCODE_METHOD]}.\n * @returns A fully-validated {@link ToolCall}.\n */\n static [DECODE_METHOD](data: AdkEncodableSnapshot): ToolCall {\n return new ToolCall(data as RawToolCall)\n }\n}\n"],"mappings":";;;;;;;AAiBA,IAAM,kBAA6C;CACjD,OAAQ,WAA0C;AACpD;;;;;;;;;;;;AAaA,IAAa,gBAAgB,UAA8B;CACzD,MAAM,SAAS,UAAU;CACzB,IAAI,UAAU,OAAO,OAAO,SAAS,YACnC,OAAO,OAAO,KAAK,KAAK,EAAE,SAAS,QAAQ;CAE7C,MAAM,YAAY;CAClB,IAAI,SAA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C;IAChB,YAAY;IACZ,cAAc;GAChB;GACA,WAAW;IACT,WAAW,KAAKC;IAChB,YAAY;IACZ,cAAc;GAChB;GACA,aAAa;IACX,WAAW,KAAKC;IAChB,YAAY;IACZ,cAAc;GAChB;EACF,CAAC;CACH;;;;;;;;;;;;;;CAeA,CAAC,oBAAA,iBAAuC;EACtC,OAAO;GACL,IAAI,KAAKb;GACT,MAAM,KAAKC;GACX,MAAM,KAAKC;GACX,UAAU,KAAKC;GACf,YAAY,KAAKC;GACjB,SAAS,KAAKC;GACd,SAAS,KAAKC;GACd,SAAS,KAAKC;GACd,qBAAqB,KAAKC;GAC1B,kBAAkB,KAAKC;GACvB,QAAQ,KAAKC;GACb,WAAW,KAAKC;GAChB,WAAW,KAAKC;GAChB,aAAa,KAAKC;EACpB;CACF;;;;;;;CAQA,QAAQ,oBAAA,eAAe,MAAsC;EAC3D,OAAO,IAAI,SAAS,IAAmB;CACzC;AACF"}
1
+ {"version":3,"file":"tool_call-B9px4W9k.cjs","names":["#id","#kind","#mimeType","#filename","#source","#trustTier","#modalityHazard","#reader","#stash","#id","#tool","#args","#checksum","#isComplete","#isError","#results","#payload","#replayCompatibility","#fromArtifactTool","#inline","#createdAt","#updatedAt","#completedAt"],"sources":["../src/lib/helpers/base64.ts","../src/lib/contracts/media_reader.ts","../src/lib/classes/media.ts","../src/lib/classes/tool_call.ts"],"sourcesContent":["/**\n * Cross-environment base64 helpers for `Uint8Array` payloads.\n *\n * @module\n *\n * @remarks\n * Used by {@link @nhtio/adk!Media}'s `asBase64()` and by the in-memory reader handle path\n * (`describe()`/resolver), which inlines its buffer as base64 because it owns no external locator. Both\n * directions prefer Node's `Buffer` when present and fall back to `btoa`/`atob` with a chunked window so\n * large buffers do not overflow the call stack.\n */\n\ninterface MinimalBuffer {\n from(input: Uint8Array): { toString(enc: string): string }\n from(input: string, enc: string): Uint8Array\n}\n\nconst getBuffer = (): MinimalBuffer | undefined => {\n return (globalThis as { Buffer?: MinimalBuffer }).Buffer\n}\n\n/**\n * Encode a `Uint8Array` as a base64 string.\n *\n * @remarks\n * Prefers `Buffer.from(bytes).toString('base64')` when `globalThis.Buffer` exists; otherwise\n * chunk-encodes through `btoa` with a `0x8000`-byte window to avoid `Maximum call stack size exceeded`\n * on large buffers.\n *\n * @param bytes - The buffer to encode.\n * @returns The base64 representation.\n */\nexport const encodeBase64 = (bytes: Uint8Array): string => {\n const buffer = getBuffer()\n if (buffer && typeof buffer.from === 'function') {\n return buffer.from(bytes).toString('base64')\n }\n const chunkSize = 0x8000\n let binary = ''\n for (let i = 0; i < bytes.length; i += chunkSize) {\n const chunk = bytes.subarray(i, i + chunkSize)\n binary += String.fromCharCode.apply(null, Array.from(chunk) as number[])\n }\n return btoa(binary)\n}\n\n/**\n * Decode a base64 string back into a `Uint8Array`.\n *\n * @remarks\n * Inverse of {@link encodeBase64}. Prefers `Buffer.from(b64, 'base64')` when `globalThis.Buffer` exists;\n * otherwise decodes through `atob` byte-by-byte.\n *\n * @param b64 - The base64 string to decode.\n * @returns The decoded bytes.\n */\nexport const decodeBase64 = (b64: string): Uint8Array => {\n const buffer = getBuffer()\n if (buffer && typeof buffer.from === 'function') {\n const decoded = buffer.from(b64, 'base64')\n // `Buffer` is a `Uint8Array` subclass; return a plain view over the same bytes.\n return new Uint8Array(decoded)\n }\n const binary = atob(b64)\n const out = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) {\n out[i] = binary.charCodeAt(i)\n }\n return out\n}\n","import { validator } from '@nhtio/validation'\nimport { passesSchema } from '../utils/validation'\nimport type { ReaderDescriptor } from './reader_descriptor'\n\n/**\n * Re-openable byte source contract for a Media instance.\n *\n * @remarks\n * Peer to {@link @nhtio/adk!SpoolReader} but tuned for binary streaming rather than line-indexed text.\n * Each `stream()` call must return a fresh, drainable `ReadableStream` over the same underlying\n * bytes — implementations model replay: in-memory readers reconstitute the stream from the\n * buffer, file-backed readers reopen the file handle, HTTP-backed readers re-issue the fetch,\n * cloud blob readers re-issue the GET. The implementor owns the storage and the cost of keeping\n * the underlying source addressable. Implementors whose underlying source is genuinely\n * non-replayable (a raw HTTP body they were handed once) are responsible for caching locally\n * before constructing the Media.\n *\n * Both methods may be synchronous or asynchronous to accommodate both in-memory and I/O-backed\n * implementations without forcing unnecessary promise overhead on simple cases.\n */\nexport interface MediaReader {\n /**\n * Re-opens the underlying byte source and returns a fresh ReadableStream.\n *\n * @remarks\n * Each call yields a new, drainable stream over the same bytes. Render code that needs the\n * full buffer (e.g. base64-encoding an inline image_url) drains the stream; render code that\n * can forward the stream (e.g. multipart upload) passes the stream through without buffering.\n *\n * @returns A drainable ReadableStream of Uint8Array chunks over the underlying bytes.\n */\n stream(): ReadableStream<Uint8Array> | Promise<ReadableStream<Uint8Array>>\n\n /**\n * Returns the total number of bytes in the underlying data, or `undefined` if unknown.\n *\n * @remarks\n * Used for telemetry, budget checks, and pre-flight provider size validation without forcing\n * a stream drain. Sources of unknown length may return `undefined` — absence is treated as\n * \"unknown\", not \"zero\".\n *\n * @returns The byte length of the underlying data, or `undefined` when unknown.\n */\n byteLength(): number | undefined | Promise<number | undefined>\n\n /**\n * Optionally emit a serialisable {@link ReaderDescriptor} so a {@link @nhtio/adk!Media} backed by this\n * reader can round-trip through `encode()`/`decode()` as a **handle**.\n *\n * @remarks\n * Synchronous by contract — the encoder's `[ENCODE_METHOD]()` is synchronous and cannot await, so a\n * reader whose handle is only obtainable asynchronously (e.g. draining a `Blob`) must NOT implement\n * this method; encoding such a `Media` throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE}. The\n * descriptor describes *where the bytes live* (a key, a URL, or an inlined buffer) — never the live\n * binding (`Disk`, OPFS root, `fetch`), which the matching resolver re-injects on decode.\n *\n * A reader that omits this method is treated as non-describable: the bytes still stream normally at\n * runtime, the `Media` simply cannot be serialised.\n *\n * @returns A tagged, serialisable handle, or `undefined`/absent when the reader cannot describe itself.\n */\n describe?(): ReaderDescriptor | undefined\n}\n\n/**\n * Validator schema used to validate a MediaReader value.\n *\n * @remarks\n * Because MediaReader is a structural interface with no associated constructor, validation is\n * duck-typed: the value must be an object, class instance, or function with `stream` and\n * `byteLength` present as callable properties. Arity is not enforced.\n */\nexport const mediaReaderSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).stream === 'function' &&\n typeof (value as any).byteLength === 'function'\n ) {\n return value as MediaReader\n }\n return helpers.error('any.invalid')\n })\n\n/**\n * Returns `true` if `value` implements the MediaReader interface.\n *\n * @remarks\n * Duck-typed: checks that `value` is non-null with `stream` and `byteLength` as callable\n * functions. Does not use `instanceof` — there is no MediaReader constructor.\n *\n * @param value - The value to test.\n * @returns `true` when `value` conforms to the MediaReader interface.\n */\nexport const implementsMediaReader = (value: unknown): value is MediaReader => {\n return passesSchema(mediaReaderSchema, value)\n}\n","import { v6 as uuidv6 } from 'uuid'\nimport { Registry } from './registry'\nimport { isError } from '../utils/guards'\nimport { validator } from '@nhtio/validation'\nimport { isInstanceOf } from '../utils/guards'\nimport { encodeBase64 } from '../helpers/base64'\nimport { validateOrThrow } from '../utils/validation'\nimport { resolveMediaReader } from '../contracts/reader_resolvers'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../utils/encoder_symbols'\nimport { implementsMediaReader, mediaReaderSchema } from '../contracts/media_reader'\nimport {\n E_INVALID_INITIAL_MEDIA_VALUE,\n E_NOT_A_MEDIA_READER,\n E_READER_NOT_DESCRIBABLE,\n} from '../exceptions/runtime'\nimport type { AdkEncodableSnapshot } from './encodable'\nimport type { MediaReader } from '../contracts/media_reader'\nimport type { ReaderDescriptor } from '../contracts/reader_descriptor'\n\n/**\n * The set of supported media kinds.\n *\n * @remarks\n * Modality coverage is asymmetric across providers. The framework defines no\n * `supportedModalities` field — how a battery handles a modality it cannot natively render is\n * the battery author's call (see `unsupportedMediaPolicy` on the OpenAI Chat Completions\n * battery).\n */\nexport const MediaKind = ['image', 'audio', 'video', 'document'] as const\n\n/**\n * Union of all recognised media kind identifier strings.\n */\nexport type MediaKind = (typeof MediaKind)[number]\n\n/**\n * Provenance axis. *Who is the framework willing to vouch for as the source of these bytes?*\n *\n * @remarks\n * Mirrors `RetrievableTrustTier` deliberately — same vocabulary, same question:\n * *did this content come from a place the agent should treat as authoritative?*\n *\n * - `'first-party'` — deployer-vetted bytes (tool output the operator authored, signed\n * internal assets).\n * - `'third-party-public'` — open-web fetches, public APIs, public corpora.\n * - `'third-party-private'` — user uploads, partner APIs, private corpora.\n */\nexport const MediaTrustTier = ['first-party', 'third-party-public', 'third-party-private'] as const\nexport type MediaTrustTier = (typeof MediaTrustTier)[number]\n\n/**\n * Modality-hazard axis. *How dangerous is it to let the model decode these bytes?*\n *\n * @remarks\n * Orthogonal to provenance — a first-party trusted PDF can still carry hidden text layers; a\n * third-party-public raw image can still be encoded as opaque pixels with adversarial\n * perturbations.\n *\n * - `'inert'` — bytes the model never decodes as instructions (e.g. a handle that is never\n * inlined into the prompt).\n * - `'extractable-instructions'` — text-bearing media: PDFs, screenshots with UI text, documents.\n * Hazard is OCR / embedded-text-layer reads.\n * - `'opaque-perceptual'` — raw vision/audio/video the model encodes directly. Hazard is\n * steganographic LSB prompts, adversarial perturbations, ultrasonic audio — invisible to any\n * pre-screen.\n *\n * See `/the-loop/trust-tiers/media` and its research sub-page `/the-loop/trust-tiers/media/research`.\n */\nexport const MediaModalityHazard = [\n 'inert',\n 'extractable-instructions',\n 'opaque-perceptual',\n] as const\nexport type MediaModalityHazard = (typeof MediaModalityHazard)[number]\n\n/**\n * Per-entry shape stored in a {@link Media}'s `stash` register.\n *\n * @remarks\n * Each entry carries its own trust tier so render code can route derived text (OCR, captions,\n * transcripts) through its own envelope independent of the parent media. How a battery or\n * middleware assigns those entry-level tiers is the implementor's call — the primitive contract\n * does not enforce a \"downgrade derived interpretation from possibly-adversarial bytes\" policy.\n */\nexport interface MediaStashEntry {\n /** The value of the entry — any serialisable shape the consumer wants to store. */\n value: unknown\n /** Trust tier for this specific entry; routed independently of the parent media. */\n trustTier: MediaTrustTier\n /** Optional pointer to the parent Media id this entry was derived from. */\n derivedFromMedia?: string\n}\n\n/**\n * Plain input object supplied to {@link Media} at construction time.\n *\n * @remarks\n * Validated against `rawMediaSchema` before the `Media` instance is created.\n */\nexport interface RawMedia {\n /**\n * Stable unique identifier for this media instance. Required for strict symmetry with\n * `Message.id` and `ToolCall.id`. When omitted, a fresh UUIDv6 is assigned at construction\n * time.\n */\n id?: string\n /** The media kind. See {@link MediaKind}. */\n kind: MediaKind\n /** The MIME type of the underlying bytes. */\n mimeType: string\n /** Filename used by providers that key on it (e.g. OpenAI `file.filename`). */\n filename: string\n /** Re-openable byte source. See {@link @nhtio/adk!MediaReader}. */\n reader: MediaReader\n /**\n * Trust tier declared at construction time. Required — there is NO default.\n * See {@link MediaTrustTier}.\n */\n trustTier: MediaTrustTier\n /**\n * Modality hazard declared at construction time. Required — there is NO default.\n * See {@link MediaModalityHazard}.\n */\n modalityHazard: MediaModalityHazard\n /** Optional provenance pointer (URL, tool name, etc.) for audit / events. */\n source?: string\n /**\n * Free-form per-instance metadata register. Middleware pipelines append to this — typically\n * with a text description, transcript, caption, or alt-text — so downstream code that cannot\n * consume the media natively has a model-readable fallback. No keys are reserved by the\n * framework. Defaults to `{}`.\n */\n stash?: Record<string, MediaStashEntry>\n}\n\nconst stashEntrySchema = validator\n .object<MediaStashEntry>({\n value: validator.any().required(),\n trustTier: validator\n .string()\n .valid(...MediaTrustTier)\n .required(),\n derivedFromMedia: validator.string().optional(),\n })\n .unknown(false)\n\n/**\n * Validator schema used to validate a {@link RawMedia} before constructing a {@link Media}.\n */\nconst rawMediaSchema = validator.object<RawMedia>({\n id: validator.string().optional(),\n kind: validator\n .string()\n .valid(...MediaKind)\n .required(),\n mimeType: validator.string().required(),\n filename: validator.string().required(),\n reader: mediaReaderSchema.required(),\n trustTier: validator\n .string()\n .valid(...MediaTrustTier)\n .required(),\n modalityHazard: validator\n .string()\n .valid(...MediaModalityHazard)\n .required(),\n source: validator.string().optional(),\n stash: validator.object().pattern(validator.string(), stashEntrySchema).optional(),\n})\n\ninterface ResolvedMedia {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n trustTier: MediaTrustTier\n modalityHazard: MediaModalityHazard\n source?: string\n stash?: Record<string, MediaStashEntry>\n}\n\nconst conservativeHazardForKind = (kind: MediaKind): MediaModalityHazard => {\n return kind === 'document' ? 'extractable-instructions' : 'opaque-perceptual'\n}\n\n/**\n * Shape returned by {@link Media.toJSON}. Metadata-only — bytes and the reader are stripped so\n * naive event/log serialisation never materialises bytes.\n */\n/** The plain-object, JSON-safe form of a {@link Media} produced by {@link Media.toJSON}. */\nexport interface SerializedMedia {\n /** Stable identifier for this media asset. */\n id: string\n /** High-level modality of the asset (e.g. image, audio, document). */\n kind: MediaKind\n /** MIME type of the underlying bytes (e.g. `image/png`). */\n mimeType: string\n /** Original or suggested file name for the asset. */\n filename: string\n /** Optional provenance string (URL, path, or other origin marker). */\n source?: string\n /** Trust tier governing how the asset's content is framed to the model. */\n trustTier: MediaTrustTier\n /** Whether the modality can carry hidden instructions (`extractable-instructions`) or is opaque-perceptual. */\n modalityHazard: MediaModalityHazard\n /** Adapter-scoped side-channel data keyed by name (e.g. provider upload handles). */\n stash: Record<string, MediaStashEntry>\n /** Size of the underlying bytes in bytes, when known. */\n byteLength?: number\n}\n\n/**\n * Lazy, re-openable view over a binary asset (image, audio, video, document).\n *\n * @remarks\n * Dual-peer to {@link @nhtio/adk!Tokenizable} (silo) and {@link @nhtio/adk!SpooledArtifact}\n * (handle). Wraps a {@link @nhtio/adk!MediaReader} contract — the framework owns the contract, the\n * implementor owns the storage backend. Bytes are reached only through the reader; the primitive\n * itself never inlines bytes.\n *\n * Construction requires `trustTier` and `modalityHazard` — the framework refuses to guess\n * provenance or decoding hazard. Ergonomic factories ({@link Media.userAttachment},\n * {@link Media.toolGenerated}, {@link Media.retrievedPublic}, {@link Media.retrievedPrivate})\n * force the labelling decision at the call site without becoming defaults on the bare\n * constructor.\n */\nexport class Media {\n /**\n * Validator schema that accepts a {@link RawMedia} object.\n */\n public static schema = rawMediaSchema\n\n /**\n * The set of recognised media kinds. Exposed for downstream schemas that need to discriminate\n * on `kind`.\n */\n public static MediaKind = MediaKind\n\n /**\n * The set of recognised trust tiers.\n */\n public static MediaTrustTier = MediaTrustTier\n\n /**\n * The set of recognised modality hazards.\n */\n public static MediaModalityHazard = MediaModalityHazard\n\n /**\n * Returns `true` if `value` is a {@link Media} 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 Media} instance.\n */\n public static isMedia(value: unknown): value is Media {\n return isInstanceOf(value, 'Media', Media)\n }\n\n /** Stable unique identifier. */\n declare readonly id: string\n /** Media kind. */\n declare readonly kind: MediaKind\n /** MIME type of the underlying bytes. */\n declare readonly mimeType: string\n /** Filename surfaced to providers that key on it. */\n declare readonly filename: string\n /** Optional provenance pointer. */\n declare readonly source: string | undefined\n /** Trust tier declared at construction time. */\n declare readonly trustTier: MediaTrustTier\n /** Modality hazard declared at construction time. */\n declare readonly modalityHazard: MediaModalityHazard\n /** Mutable per-instance metadata register; middleware pipelines append to this. */\n declare readonly stash: Registry\n\n #id: string\n #kind: MediaKind\n #mimeType: string\n #filename: string\n #source?: string\n #trustTier: MediaTrustTier\n #modalityHazard: MediaModalityHazard\n #reader: MediaReader\n #stash: Registry\n\n /**\n * @param raw - The raw media input validated against `rawMediaSchema`.\n * @throws {@link @nhtio/adk/exceptions!E_INVALID_INITIAL_MEDIA_VALUE} when `raw` does not satisfy the schema.\n * @throws {@link @nhtio/adk/exceptions!E_NOT_A_MEDIA_READER} when `raw.reader` does not implement {@link @nhtio/adk!MediaReader}.\n */\n constructor(raw: RawMedia) {\n let resolved: ResolvedMedia\n try {\n resolved = validateOrThrow<ResolvedMedia>(rawMediaSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_MEDIA_VALUE({ cause: isError(err) ? err : undefined })\n }\n if (!implementsMediaReader(resolved.reader)) {\n throw new E_NOT_A_MEDIA_READER()\n }\n this.#id = resolved.id ?? uuidv6()\n this.#kind = resolved.kind\n this.#mimeType = resolved.mimeType\n this.#filename = resolved.filename\n this.#source = resolved.source\n this.#trustTier = resolved.trustTier\n this.#modalityHazard = resolved.modalityHazard\n this.#reader = resolved.reader\n this.#stash = new Registry(resolved.stash as Record<string, unknown> | undefined)\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n kind: {\n get: () => this.#kind,\n enumerable: true,\n configurable: false,\n },\n mimeType: {\n get: () => this.#mimeType,\n enumerable: true,\n configurable: false,\n },\n filename: {\n get: () => this.#filename,\n enumerable: true,\n configurable: false,\n },\n source: {\n get: () => this.#source,\n enumerable: true,\n configurable: false,\n },\n trustTier: {\n get: () => this.#trustTier,\n enumerable: true,\n configurable: false,\n },\n modalityHazard: {\n get: () => this.#modalityHazard,\n enumerable: true,\n configurable: false,\n },\n stash: {\n get: () => this.#stash,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Re-opens the underlying byte source and returns a fresh ReadableStream.\n *\n * @returns A drainable `ReadableStream` over the underlying bytes.\n */\n async stream(): Promise<ReadableStream<Uint8Array>> {\n return this.#reader.stream()\n }\n\n /**\n * Returns the total number of bytes in the underlying data, or `undefined` if unknown.\n *\n * @returns The byte length, or `undefined` when the underlying source cannot report it.\n */\n async byteLength(): Promise<number | undefined> {\n return this.#reader.byteLength()\n }\n\n /**\n * Drains the reader's stream and returns the underlying bytes as a single `Uint8Array`.\n *\n * @remarks\n * Convenience for callers that need the full buffer (e.g. inline base64 encoding). Forces\n * full materialisation — large assets should be piped through {@link Media.stream} instead.\n */\n async asBytes(): Promise<Uint8Array> {\n const stream = await this.stream()\n const reader = stream.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n if (value) {\n chunks.push(value)\n total += value.byteLength\n }\n }\n const out = new Uint8Array(total)\n let offset = 0\n for (const chunk of chunks) {\n out.set(chunk, offset)\n offset += chunk.byteLength\n }\n return out\n }\n\n /**\n * Drains the reader's stream and returns the underlying bytes as a base64 string.\n *\n * @remarks\n * Cross-environment: prefers Node's `Buffer.from(buf).toString('base64')` when available;\n * otherwise chunk-encodes through `btoa` with a 0x8000-byte window to avoid stack overflow\n * on large buffers.\n */\n async asBase64(): Promise<string> {\n const bytes = await this.asBytes()\n return encodeBase64(bytes)\n }\n\n /**\n * Returns the metadata-only serialisation of this Media. Bytes and the reader are stripped\n * so naive event/log serialisation never materialises bytes.\n *\n * @remarks\n * Implementations that have cheap, already-cached `byteLength` may opt to include it; this\n * default implementation omits it to preserve the \"lazy by default\" invariant. Consumers that\n * need byteLength on the serialised payload should call `await media.byteLength()` and merge\n * the result.\n */\n toJSON(): SerializedMedia {\n return {\n id: this.#id,\n kind: this.#kind,\n mimeType: this.#mimeType,\n filename: this.#filename,\n source: this.#source,\n trustTier: this.#trustTier,\n modalityHazard: this.#modalityHazard,\n stash: this.#stash.all() as Record<string, MediaStashEntry>,\n }\n }\n\n /**\n * Serialise this Media into an `@nhtio/encoder` snapshot — the **handle**, never the bytes.\n *\n * @remarks\n * Emits every metadata field plus the reader's {@link @nhtio/adk!ReaderDescriptor} (via its\n * `describe()` method). The bytes are not inlined: decode re-binds the reader from the descriptor\n * through a registered resolver. Throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} when the backing\n * reader cannot describe itself (e.g. a `fromWebFile` Blob reader) — there is no serialisable handle to\n * write, and silently dropping the reader would decode into a handle pointing at nothing.\n *\n * @returns A snapshot consumed by {@link Media.[DECODE_METHOD]} / the encoder.\n * @throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} when the reader has no `describe()`.\n */\n [ENCODE_METHOD](): AdkEncodableSnapshot {\n const descriptor = this.#reader.describe?.()\n if (!descriptor) {\n throw new E_READER_NOT_DESCRIBABLE(['reader'])\n }\n return {\n id: this.#id,\n kind: this.#kind,\n mimeType: this.#mimeType,\n filename: this.#filename,\n source: this.#source,\n trustTier: this.#trustTier,\n modalityHazard: this.#modalityHazard,\n stash: this.#stash.all(),\n reader: descriptor,\n }\n }\n\n /**\n * Reconstruct a {@link Media} from an {@link Media.[ENCODE_METHOD]} snapshot.\n *\n * @remarks\n * Re-binds the reader from the captured descriptor through the registered resolver\n * ({@link @nhtio/adk!resolveMediaReader}), then re-validates via the normal constructor. Throws\n * {@link @nhtio/adk!E_NO_READER_RESOLVER} when no resolver is registered for the descriptor's tag.\n *\n * @param data - The snapshot produced by {@link Media.[ENCODE_METHOD]}.\n * @returns A fully-validated {@link Media} backed by a freshly-resolved reader.\n */\n static [DECODE_METHOD](data: AdkEncodableSnapshot): Media {\n const snapshot = data as {\n id: string\n kind: MediaKind\n mimeType: string\n filename: string\n source?: string\n trustTier: MediaTrustTier\n modalityHazard: MediaModalityHazard\n stash?: Record<string, MediaStashEntry>\n reader: ReaderDescriptor\n }\n return new Media({\n id: snapshot.id,\n kind: snapshot.kind,\n mimeType: snapshot.mimeType,\n filename: snapshot.filename,\n source: snapshot.source,\n trustTier: snapshot.trustTier,\n modalityHazard: snapshot.modalityHazard,\n stash: snapshot.stash,\n reader: resolveMediaReader(snapshot.reader),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} representing a user-supplied attachment.\n *\n * @remarks\n * Pre-fills `trustTier: 'third-party-private'` and derives `modalityHazard` from `kind`\n * (`document` → `'extractable-instructions'`; everything else → `'opaque-perceptual'`).\n * Use the bare constructor when the conservative kind→hazard mapping is wrong for your case.\n */\n public static userAttachment(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'third-party-private',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} produced by a first-party tool.\n *\n * @remarks\n * Pre-fills `trustTier: 'first-party'` and derives `modalityHazard` from `kind`.\n */\n public static toolGenerated(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'first-party',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} retrieved from a public third-party source.\n *\n * @remarks\n * Pre-fills `trustTier: 'third-party-public'` and derives `modalityHazard` from `kind`.\n */\n public static retrievedPublic(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'third-party-public',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} retrieved from a private third-party source.\n *\n * @remarks\n * Pre-fills `trustTier: 'third-party-private'` and derives `modalityHazard` from `kind`.\n */\n public static retrievedPrivate(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'third-party-private',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n}\n\n/**\n * Returns `true` if `value` is a {@link Media} instance.\n *\n * @remarks\n * Module-level convenience alias for {@link Media.isMedia}. Uses {@link @nhtio/adk!isInstanceOf} for\n * cross-realm safety.\n */\nexport const isMedia = (value: unknown): value is Media => {\n return isInstanceOf(value, 'Media', Media)\n}\n","import { Media } from './media'\nimport { Tokenizable } from './tokenizable'\nimport { validator } from '@nhtio/validation'\nimport { SpooledArtifact } from './spooled_artifact'\nimport { validateOrThrow } from '../utils/validation'\nimport { isObject, isInstanceOf, isError } from '../utils/guards'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../utils/encoder_symbols'\nimport { E_INVALID_INITIAL_TOOL_CALL_VALUE } from '../exceptions/runtime'\nimport type { DateTime } from 'luxon'\nimport type { AdkEncodableSnapshot } from './encodable'\n\n/**\n * Union of every shape a {@link ToolCall.results} field may carry.\n *\n * @remarks\n * Three silos with distinct render-time semantics:\n *\n * - {@link @nhtio/adk!Tokenizable} — always singular. The {@link @nhtio/adk!ArtifactTool}\n * carve-out: a model-visible text answer that explicitly opts out of artifact wrapping to\n * break the recursive grep-on-the-grep-result loop.\n * - {@link @nhtio/adk!SpooledArtifact} or `SpooledArtifact[]` — bounded text output spooled to durable\n * storage. A single tool call may legitimately produce multiple artifacts (e.g. one tool\n * that returns N PR bodies). LLM adapters render either inline (full body in trust envelope)\n * or as a handle reference (forged artifact-query tools).\n * - {@link @nhtio/adk!Media} or `Media[]` — binary modality output (image, audio, video, document).\n * Adapters render as provider-specific content blocks (`image_url`, `input_audio`, `file`,\n * etc.). Bytes are lazy — reached only through {@link @nhtio/adk!Media.stream}.\n */\nexport type ToolCallResults = Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[]\n\nconst isToolCallResults = (value: unknown): value is ToolCallResults => {\n if (Tokenizable.isTokenizable(value)) return true\n if (SpooledArtifact.isSpooledArtifact(value)) return true\n if (Media.isMedia(value)) return true\n if (Array.isArray(value) && value.length > 0) {\n const allMedia = value.every((entry) => Media.isMedia(entry))\n if (allMedia) return true\n const allSpooled = value.every((entry) => SpooledArtifact.isSpooledArtifact(entry))\n if (allSpooled) return true\n }\n return false\n}\n\n/**\n * Plain input object supplied to {@link ToolCall} at construction time.\n *\n * @remarks\n * Validated against `rawToolCallSchema` before the `ToolCall` instance is created.\n * Temporal fields accept any value that Luxon can parse — ISO strings, Unix timestamps,\n * `Date` objects, or existing `DateTime` instances.\n */\nexport interface RawToolCall {\n /** Stable unique identifier for this tool call; correlates the request with its result. */\n id: string\n /** Name of the tool the model has requested. */\n tool: string\n /**\n * Arguments the model supplied for this tool call.\n *\n * @remarks\n * Accepts either a plain object or a JSON-encoded string that deserialises to an object.\n * Always exposed as a plain object on the constructed {@link ToolCall} instance.\n */\n args: string | Record<string, unknown>\n /** Integrity checksum over `tool` and `args`; can be used to detect tampering before execution. */\n checksum: string\n /** `true` once the tool call has finished (successfully or not). */\n isComplete: boolean\n /** `true` when the tool execution produced an error; inspect `results` for detail. */\n isError: boolean\n /**\n * Result returned by the tool, or error detail when `isError` is `true`.\n *\n * @remarks\n * Three silos with distinct render-time semantics — see {@link ToolCallResults}:\n *\n * - For a normal {@link @nhtio/adk!Tool} call whose handler returned `string` or\n * `Uint8Array`, this is a {@link @nhtio/adk!SpooledArtifact} (or one of its subclasses) wrapping the\n * spooled bytes. Tools that legitimately produce multiple bounded artifacts may return\n * a `SpooledArtifact[]`.\n * - For a `Tool` call whose handler returned a {@link @nhtio/adk!Media} or `Media[]`, this is the same\n * media handle(s) — the explicit-modality silo bypasses `SpooledArtifact` wrapping because\n * the bytes are binary and rendered as provider-specific content blocks, not text.\n * - For an {@link @nhtio/adk!ArtifactTool} call (a forged artifact-query tool),\n * this is a {@link @nhtio/adk!Tokenizable} holding the raw model-visible answer — `ArtifactTool`\n * explicitly opts out of wrapping to break the recursive grep-on-the-grep-result loop.\n *\n * The ADK sets {@link RawToolCall.fromArtifactTool} on calls produced by an\n * `ArtifactTool` so subsequent `forgeTools(ctx)` invocations can filter them out of the\n * `callId` enum.\n */\n results: ToolCallResults\n /**\n * Optional vendor-opaque payload that round-trips back to a matching model wire.\n *\n * @remarks\n * Carries provider metadata the ADK cannot interpret, such as Gemini's `thought_signature`\n * on a function call, GPT-OSS's commentary-channel tag, or other vendor-opaque metadata\n * that a provider needs echoed back.\n *\n * A present `payload` requires a present {@link RawToolCall.replayCompatibility} so the\n * matching adapter wire shape is known.\n *\n * @defaultValue `undefined`\n */\n payload?: unknown\n /**\n * Optional free-form identifier describing which adapter wire-shape this tool call can be\n * safely replayed into.\n *\n * @remarks\n * A `replayCompatibility` without a `payload` is allowed — it documents intent without\n * requiring an opaque blob.\n *\n * @defaultValue `undefined`\n */\n replayCompatibility?: string\n /**\n * `true` when this tool call originated from an {@link @nhtio/adk!ArtifactTool}\n * invocation. Defaults to `false`.\n *\n * @remarks\n * Set by the ADK's result-wrapping touch sites when `ArtifactTool.isArtifactTool(tool)`\n * holds. Read by `SpooledArtifact.forgeTools(ctx)` when building each descriptor's `callId`\n * enum — calls with this flag set are excluded so the model can't `artifact_grep` on a\n * previous `artifact_grep` result. Optional in the raw shape (defaults to `false`); always\n * defined on the constructed {@link ToolCall}.\n *\n * @defaultValue `false`\n */\n fromArtifactTool?: boolean\n /**\n * When `false` (the default), the adapter surfaces a {@link @nhtio/adk!SpooledArtifact} result as a\n * \"handle\" — a directions-bearing envelope that tells the model which forged artifact-query tools to\n * call against this `tc.id` to read the content incrementally, keeping the body OUT of the prompt.\n * When `true`, the adapter renders the result inline — the full stringified body wrapped in the\n * adapter's trust envelope and sent to the model as the `tool` role content.\n *\n * @remarks\n * Handle-by-default is the secure, budget-aligned posture: the LLM batteries already spool-wrap every\n * non-{@link @nhtio/adk!Media}, non-{@link @nhtio/adk!ArtifactTool} tool result into a `SpooledArtifact`,\n * so a result that could be arbitrarily large never lands in the next prompt just because nobody\n * touched a flag — the core ADK context-window-diet principle (see the Budgets / Artifacts docs).\n * Inlining is the OPT-IN: a producer that knows its output is small sets `inline: true` so the model\n * sees the body verbatim without a query round-trip.\n *\n * Policy is the producer's or middleware's call (LLM adapters obey the flag — they never size-check\n * the result or silently switch modes). Set per call at construction, or flip mid-turn via\n * `ctx.mutateToolCall(tc.id, { inline: true })`.\n *\n * Handles only make sense for `SpooledArtifact` (the only result kind the forged artifact-query tools\n * can read). For a {@link @nhtio/adk!Tokenizable} result (e.g. an `ArtifactTool` answer or an error\n * string) the flag is moot — the adapter renders it inline regardless, since there is no queryable\n * artifact to hand back.\n *\n * @defaultValue `false`\n */\n inline?: boolean\n /** When this tool call was first created. */\n createdAt: string | number | Date | DateTime\n /** When this tool call was last modified. */\n updatedAt: string | number | Date | DateTime\n /** When the tool call completed. */\n completedAt: string | number | Date | DateTime\n}\n\n/**\n * A fully-resolved {@link RawToolCall} where temporal fields have been normalised to Luxon\n * `DateTime` instances.\n *\n * @remarks\n * Used internally by the {@link ToolCall} constructor to assign private fields with\n * guaranteed types.\n */\ninterface ResolvedToolCall {\n id: string\n tool: string\n args: Record<string, unknown>\n checksum: string\n isComplete: boolean\n isError: boolean\n results: ToolCallResults\n payload?: unknown\n replayCompatibility?: string\n fromArtifactTool: boolean\n inline: boolean\n createdAt: DateTime\n updatedAt: DateTime\n completedAt: DateTime\n}\n\n/**\n * Validator schema used to validate a {@link RawToolCall} before constructing a {@link ToolCall}.\n *\n * @remarks\n * Validates all fields of {@link RawToolCall}:\n * - `id` — required non-empty string.\n * - `tool` — required non-empty string.\n * - `args` — required; either a plain object or a JSON string that deserialises to an object.\n * Strings are parsed and the resulting object is stored.\n * - `checksum` — required string.\n * - `isComplete` — required boolean.\n * - `isError` — required boolean.\n * - `results` — required; one of {@link @nhtio/adk!Tokenizable}, {@link @nhtio/adk!SpooledArtifact}, a non-empty\n * `SpooledArtifact[]`, {@link @nhtio/adk!Media}, or a non-empty `Media[]`. Arrays must be homogeneous.\n * - `createdAt` / `updatedAt` / `completedAt` — required datetime-parseable values, normalised to `DateTime`.\n *\n * Throws {@link @nhtio/adk!E_INVALID_INITIAL_TOOL_CALL_VALUE} (via the {@link ToolCall} constructor) when\n * validation fails.\n */\nconst rawToolCallSchema = validator\n .object<RawToolCall>({\n id: validator.string().required(),\n tool: validator.string().required(),\n args: validator\n .alternatives(\n validator.object().unknown(true),\n validator.string().custom((value, helpers) => {\n try {\n const parsed = JSON.parse(value)\n if (!isObject(parsed)) {\n return helpers.error('any.invalid')\n }\n return parsed\n } catch {\n return helpers.error('any.invalid')\n }\n })\n )\n .required(),\n checksum: validator.string().required(),\n isComplete: validator.boolean().required(),\n isError: validator.boolean().required(),\n results: validator\n .any()\n .custom((value, helpers) => {\n if (isToolCallResults(value)) {\n return value\n }\n return helpers.error('any.invalid')\n })\n .required(),\n payload: validator.any().optional(),\n replayCompatibility: validator.string().min(1).optional(),\n fromArtifactTool: validator.boolean().default(false),\n inline: validator.boolean().default(false),\n createdAt: validator.datetime().required(),\n updatedAt: validator.datetime().required(),\n completedAt: validator.datetime().required(),\n })\n .custom((value, helpers) => {\n const v = value as RawToolCall\n const hasPayload = v.payload !== undefined && v.payload !== null\n if (hasPayload && (v.replayCompatibility === undefined || v.replayCompatibility === null)) {\n return helpers.error('any.invalid')\n }\n return value\n })\n\n/**\n * An immutable, validated tool call record associated with a turn.\n *\n * @remarks\n * Represents a completed tool invocation from the conversation history — `results`,\n * `completedAt`, `isComplete`, and `isError` are all present and required.\n * Temporal fields are normalised to Luxon `DateTime` instances at construction time.\n */\nexport class ToolCall {\n /**\n * Validator schema that accepts a {@link RawToolCall} object.\n *\n * @remarks\n * Reusable fragment for any schema that needs to validate or nest a tool call entry.\n */\n public static schema = rawToolCallSchema\n\n /**\n * Returns `true` if `value` is a {@link ToolCall} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety — `instanceof` would fail for instances\n * created in a different module copy or VM context.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link ToolCall} instance.\n */\n public static isToolCall(value: unknown): value is ToolCall {\n return isInstanceOf(value, 'ToolCall', ToolCall)\n }\n\n /** Stable unique identifier for this tool call; correlates the request with its result. */\n declare readonly id: string\n /** Name of the tool the model has requested. */\n declare readonly tool: string\n /** Arguments the model supplied for this tool call, always as a plain object. */\n declare readonly args: Record<string, unknown>\n /** Integrity checksum over `tool` and `args`. */\n declare readonly checksum: string\n /** `true` once the tool call has finished (successfully or not). */\n declare readonly isComplete: boolean\n /** `true` when the tool execution produced an error; inspect `results` for detail. */\n declare readonly isError: boolean\n /**\n * Result returned by the tool, or error detail when `isError` is `true`.\n *\n * @remarks\n * One of three silos — see {@link ToolCallResults}. {@link @nhtio/adk!SpooledArtifact} or\n * `SpooledArtifact[]` for normal text-output {@link @nhtio/adk!Tool} calls;\n * {@link @nhtio/adk!Media} or `Media[]` for tool calls whose handler returned binary modality output;\n * {@link @nhtio/adk!Tokenizable} for {@link @nhtio/adk!ArtifactTool} calls\n * (see {@link ToolCall.fromArtifactTool}).\n */\n declare readonly results: ToolCallResults\n /**\n * Optional vendor-opaque payload that round-trips back to a matching model wire.\n * See {@link RawToolCall.payload}.\n */\n declare readonly payload: unknown\n /**\n * Optional wire-shape identifier describing which adapter can safely replay this tool call.\n * See {@link RawToolCall.replayCompatibility}.\n */\n declare readonly replayCompatibility: string | undefined\n /**\n * `true` when this tool call originated from an {@link @nhtio/adk!ArtifactTool}\n * invocation. Used by `SpooledArtifact.forgeTools(ctx)` to filter out forged-tool results from\n * the `callId` enum it builds.\n */\n declare readonly fromArtifactTool: boolean\n /**\n * `false` (default) instructs LLM adapters to surface a `SpooledArtifact` result as a handle\n * reference (body kept out of the prompt); `true` renders the result inline. See\n * {@link RawToolCall.inline}.\n */\n declare readonly inline: boolean\n /** When this tool call was first created. */\n declare readonly createdAt: DateTime\n /** When this tool call was last modified. */\n declare readonly updatedAt: DateTime\n /** When the tool call completed. */\n declare readonly completedAt: DateTime\n\n #id: string\n #tool: string\n #args: Record<string, unknown>\n #checksum: string\n #isComplete: boolean\n #isError: boolean\n #results: ToolCallResults\n #payload: unknown\n #replayCompatibility: string | undefined\n #fromArtifactTool: boolean\n #inline: boolean\n #createdAt: DateTime\n #updatedAt: DateTime\n #completedAt: DateTime\n\n /**\n * @param raw - The raw tool call input validated against `rawToolCallSchema`.\n * @throws {@link @nhtio/adk!E_INVALID_INITIAL_TOOL_CALL_VALUE} when `raw` does not satisfy the schema.\n */\n constructor(raw: RawToolCall) {\n let resolved: ResolvedToolCall\n try {\n resolved = validateOrThrow<ResolvedToolCall>(rawToolCallSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_TOOL_CALL_VALUE({ cause: isError(err) ? err : undefined })\n }\n this.#id = resolved.id\n this.#tool = resolved.tool\n this.#args = resolved.args\n this.#checksum = resolved.checksum\n this.#isComplete = resolved.isComplete\n this.#isError = resolved.isError\n this.#results = resolved.results\n this.#payload = resolved.payload\n this.#replayCompatibility = resolved.replayCompatibility\n this.#fromArtifactTool = resolved.fromArtifactTool\n this.#inline = resolved.inline\n this.#createdAt = resolved.createdAt\n this.#updatedAt = resolved.updatedAt\n this.#completedAt = resolved.completedAt\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n tool: {\n get: () => this.#tool,\n enumerable: true,\n configurable: false,\n },\n args: {\n get: () => this.#args,\n enumerable: true,\n configurable: false,\n },\n checksum: {\n get: () => this.#checksum,\n enumerable: true,\n configurable: false,\n },\n isComplete: {\n get: () => this.#isComplete,\n enumerable: true,\n configurable: false,\n },\n isError: {\n get: () => this.#isError,\n enumerable: true,\n configurable: false,\n },\n results: {\n get: () => this.#results,\n enumerable: true,\n configurable: false,\n },\n payload: {\n get: () => this.#payload,\n enumerable: true,\n configurable: false,\n },\n replayCompatibility: {\n get: () => this.#replayCompatibility,\n enumerable: true,\n configurable: false,\n },\n fromArtifactTool: {\n get: () => this.#fromArtifactTool,\n enumerable: true,\n configurable: false,\n },\n inline: {\n get: () => this.#inline,\n enumerable: true,\n configurable: false,\n },\n createdAt: {\n get: () => this.#createdAt,\n enumerable: true,\n configurable: false,\n },\n updatedAt: {\n get: () => this.#updatedAt,\n enumerable: true,\n configurable: false,\n },\n completedAt: {\n get: () => this.#completedAt,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Serialise this ToolCall into an `@nhtio/encoder` snapshot.\n *\n * @remarks\n * Emits a {@link RawToolCall}-shaped object. `results` is the live {@link ToolCallResults} union —\n * a {@link @nhtio/adk!Tokenizable}, {@link @nhtio/adk!SpooledArtifact}(s), or {@link @nhtio/adk!Media}(s) —\n * which the encoder recurses into; reader-backed results round-trip as handles (and throw\n * {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} if a backing reader cannot describe itself). The `args`\n * object and the producer-supplied `checksum` are emitted verbatim, so the constructor's\n * checksum re-validation passes on decode. Round-trips via {@link ToolCall.[DECODE_METHOD]}.\n *\n * @returns A {@link RawToolCall}-shaped snapshot.\n */\n [ENCODE_METHOD](): AdkEncodableSnapshot {\n return {\n id: this.#id,\n tool: this.#tool,\n args: this.#args,\n checksum: this.#checksum,\n isComplete: this.#isComplete,\n isError: this.#isError,\n results: this.#results,\n payload: this.#payload,\n replayCompatibility: this.#replayCompatibility,\n fromArtifactTool: this.#fromArtifactTool,\n inline: this.#inline,\n createdAt: this.#createdAt,\n updatedAt: this.#updatedAt,\n completedAt: this.#completedAt,\n }\n }\n\n /**\n * Reconstruct a {@link ToolCall} from a {@link ToolCall.[ENCODE_METHOD]} snapshot.\n *\n * @param data - The snapshot produced by {@link ToolCall.[ENCODE_METHOD]}.\n * @returns A fully-validated {@link ToolCall}.\n */\n static [DECODE_METHOD](data: AdkEncodableSnapshot): ToolCall {\n return new ToolCall(data as RawToolCall)\n }\n}\n"],"mappings":";;;;;;;AAiBA,IAAM,kBAA6C;CACjD,OAAQ,WAA0C;AACpD;;;;;;;;;;;;AAaA,IAAa,gBAAgB,UAA8B;CACzD,MAAM,SAAS,UAAU;CACzB,IAAI,UAAU,OAAO,OAAO,SAAS,YACnC,OAAO,OAAO,KAAK,KAAK,EAAE,SAAS,QAAQ;CAE7C,MAAM,YAAY;CAClB,IAAI,SAAS;CACb,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;EAChD,MAAM,QAAQ,MAAM,SAAS,GAAG,IAAI,SAAS;EAC7C,UAAU,OAAO,aAAa,MAAM,MAAM,MAAM,KAAK,KAAK,CAAa;CACzE;CACA,OAAO,KAAK,MAAM;AACpB;;;;;;;;;;;AAYA,IAAa,gBAAgB,QAA4B;CACvD,MAAM,SAAS,UAAU;CACzB,IAAI,UAAU,OAAO,OAAO,SAAS,YAAY;EAC/C,MAAM,UAAU,OAAO,KAAK,KAAK,QAAQ;EAEzC,OAAO,IAAI,WAAW,OAA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GAC1B,kBAAkB,KAAKC;GACvB,QAAQ,KAAKC;GACb,WAAW,KAAKC;GAChB,WAAW,KAAKC;GAChB,aAAa,KAAKC;EACpB;CACF;;;;;;;CAQA,QAAQ,oBAAA,eAAe,MAAsC;EAC3D,OAAO,IAAI,SAAS,IAAmB;CACzC;AACF"}
@@ -1,7 +1,7 @@
1
1
  import { a as passesSchema, o as validateOrThrow } 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 E_NOT_A_MEDIA_READER, F as E_READER_NOT_DESCRIBABLE, f as E_INVALID_INITIAL_MEDIA_VALUE, o as DECODE_METHOD, r as Tokenizable, s as ENCODE_METHOD, v as E_INVALID_INITIAL_TOOL_CALL_VALUE } from "./tokenizable-xPXj1AQX.mjs";
4
- import { c as resolveMediaReader, m as Registry, t as SpooledArtifact } from "./spooled_artifact-B710Rb0d.mjs";
3
+ import { B as ENCODE_METHOD, N as E_READER_NOT_DESCRIBABLE, O as E_NOT_A_MEDIA_READER, g as E_INVALID_INITIAL_TOOL_CALL_VALUE, r as Tokenizable, u as E_INVALID_INITIAL_MEDIA_VALUE, z as DECODE_METHOD } from "./tokenizable-VB4Av8GF.mjs";
4
+ import { c as resolveMediaReader, g as Registry, t as SpooledArtifact } from "./spooled_artifact-Bw_7swIp.mjs";
5
5
  import { validator } from "@nhtio/validation";
6
6
  import { v6 } from "uuid";
7
7
  //#region src/lib/helpers/base64.ts
@@ -717,4 +717,4 @@ var ToolCall = class ToolCall {
717
717
  //#endregion
718
718
  export { mediaReaderSchema as a, implementsMediaReader as i, Media as n, decodeBase64 as o, isMedia as r, encodeBase64 as s, ToolCall as t };
719
719
 
720
- //# sourceMappingURL=tool_call-D-LqMvpU.mjs.map
720
+ //# sourceMappingURL=tool_call-Cfaj-6zK.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"tool_call-D-LqMvpU.mjs","names":["#id","#kind","#mimeType","#filename","#source","#trustTier","#modalityHazard","#reader","#stash","#id","#tool","#args","#checksum","#isComplete","#isError","#results","#payload","#replayCompatibility","#fromArtifactTool","#inline","#createdAt","#updatedAt","#completedAt"],"sources":["../src/lib/helpers/base64.ts","../src/lib/contracts/media_reader.ts","../src/lib/classes/media.ts","../src/lib/classes/tool_call.ts"],"sourcesContent":["/**\n * Cross-environment base64 helpers for `Uint8Array` payloads.\n *\n * @module\n *\n * @remarks\n * Used by {@link @nhtio/adk!Media}'s `asBase64()` and by the in-memory reader handle path\n * (`describe()`/resolver), which inlines its buffer as base64 because it owns no external locator. Both\n * directions prefer Node's `Buffer` when present and fall back to `btoa`/`atob` with a chunked window so\n * large buffers do not overflow the call stack.\n */\n\ninterface MinimalBuffer {\n from(input: Uint8Array): { toString(enc: string): string }\n from(input: string, enc: string): Uint8Array\n}\n\nconst getBuffer = (): MinimalBuffer | undefined => {\n return (globalThis as { Buffer?: MinimalBuffer }).Buffer\n}\n\n/**\n * Encode a `Uint8Array` as a base64 string.\n *\n * @remarks\n * Prefers `Buffer.from(bytes).toString('base64')` when `globalThis.Buffer` exists; otherwise\n * chunk-encodes through `btoa` with a `0x8000`-byte window to avoid `Maximum call stack size exceeded`\n * on large buffers.\n *\n * @param bytes - The buffer to encode.\n * @returns The base64 representation.\n */\nexport const encodeBase64 = (bytes: Uint8Array): string => {\n const buffer = getBuffer()\n if (buffer && typeof buffer.from === 'function') {\n return buffer.from(bytes).toString('base64')\n }\n const chunkSize = 0x8000\n let binary = ''\n for (let i = 0; i < bytes.length; i += chunkSize) {\n const chunk = bytes.subarray(i, i + chunkSize)\n binary += String.fromCharCode.apply(null, Array.from(chunk) as number[])\n }\n return btoa(binary)\n}\n\n/**\n * Decode a base64 string back into a `Uint8Array`.\n *\n * @remarks\n * Inverse of {@link encodeBase64}. Prefers `Buffer.from(b64, 'base64')` when `globalThis.Buffer` exists;\n * otherwise decodes through `atob` byte-by-byte.\n *\n * @param b64 - The base64 string to decode.\n * @returns The decoded bytes.\n */\nexport const decodeBase64 = (b64: string): Uint8Array => {\n const buffer = getBuffer()\n if (buffer && typeof buffer.from === 'function') {\n const decoded = buffer.from(b64, 'base64')\n // `Buffer` is a `Uint8Array` subclass; return a plain view over the same bytes.\n return new Uint8Array(decoded)\n }\n const binary = atob(b64)\n const out = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) {\n out[i] = binary.charCodeAt(i)\n }\n return out\n}\n","import { validator } from '@nhtio/validation'\nimport { passesSchema } from '../utils/validation'\nimport type { ReaderDescriptor } from './reader_descriptor'\n\n/**\n * Re-openable byte source contract for a Media instance.\n *\n * @remarks\n * Peer to {@link @nhtio/adk!SpoolReader} but tuned for binary streaming rather than line-indexed text.\n * Each `stream()` call must return a fresh, drainable `ReadableStream` over the same underlying\n * bytes — implementations model replay: in-memory readers reconstitute the stream from the\n * buffer, file-backed readers reopen the file handle, HTTP-backed readers re-issue the fetch,\n * cloud blob readers re-issue the GET. The implementor owns the storage and the cost of keeping\n * the underlying source addressable. Implementors whose underlying source is genuinely\n * non-replayable (a raw HTTP body they were handed once) are responsible for caching locally\n * before constructing the Media.\n *\n * Both methods may be synchronous or asynchronous to accommodate both in-memory and I/O-backed\n * implementations without forcing unnecessary promise overhead on simple cases.\n */\nexport interface MediaReader {\n /**\n * Re-opens the underlying byte source and returns a fresh ReadableStream.\n *\n * @remarks\n * Each call yields a new, drainable stream over the same bytes. Render code that needs the\n * full buffer (e.g. base64-encoding an inline image_url) drains the stream; render code that\n * can forward the stream (e.g. multipart upload) passes the stream through without buffering.\n *\n * @returns A drainable ReadableStream of Uint8Array chunks over the underlying bytes.\n */\n stream(): ReadableStream<Uint8Array> | Promise<ReadableStream<Uint8Array>>\n\n /**\n * Returns the total number of bytes in the underlying data, or `undefined` if unknown.\n *\n * @remarks\n * Used for telemetry, budget checks, and pre-flight provider size validation without forcing\n * a stream drain. Sources of unknown length may return `undefined` — absence is treated as\n * \"unknown\", not \"zero\".\n *\n * @returns The byte length of the underlying data, or `undefined` when unknown.\n */\n byteLength(): number | undefined | Promise<number | undefined>\n\n /**\n * Optionally emit a serialisable {@link ReaderDescriptor} so a {@link @nhtio/adk!Media} backed by this\n * reader can round-trip through `encode()`/`decode()` as a **handle**.\n *\n * @remarks\n * Synchronous by contract — the encoder's `[ENCODE_METHOD]()` is synchronous and cannot await, so a\n * reader whose handle is only obtainable asynchronously (e.g. draining a `Blob`) must NOT implement\n * this method; encoding such a `Media` throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE}. The\n * descriptor describes *where the bytes live* (a key, a URL, or an inlined buffer) — never the live\n * binding (`Disk`, OPFS root, `fetch`), which the matching resolver re-injects on decode.\n *\n * A reader that omits this method is treated as non-describable: the bytes still stream normally at\n * runtime, the `Media` simply cannot be serialised.\n *\n * @returns A tagged, serialisable handle, or `undefined`/absent when the reader cannot describe itself.\n */\n describe?(): ReaderDescriptor | undefined\n}\n\n/**\n * Validator schema used to validate a MediaReader value.\n *\n * @remarks\n * Because MediaReader is a structural interface with no associated constructor, validation is\n * duck-typed: the value must be an object, class instance, or function with `stream` and\n * `byteLength` present as callable properties. Arity is not enforced.\n */\nexport const mediaReaderSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).stream === 'function' &&\n typeof (value as any).byteLength === 'function'\n ) {\n return value as MediaReader\n }\n return helpers.error('any.invalid')\n })\n\n/**\n * Returns `true` if `value` implements the MediaReader interface.\n *\n * @remarks\n * Duck-typed: checks that `value` is non-null with `stream` and `byteLength` as callable\n * functions. Does not use `instanceof` — there is no MediaReader constructor.\n *\n * @param value - The value to test.\n * @returns `true` when `value` conforms to the MediaReader interface.\n */\nexport const implementsMediaReader = (value: unknown): value is MediaReader => {\n return passesSchema(mediaReaderSchema, value)\n}\n","import { v6 as uuidv6 } from 'uuid'\nimport { Registry } from './registry'\nimport { isError } from '../utils/guards'\nimport { validator } from '@nhtio/validation'\nimport { isInstanceOf } from '../utils/guards'\nimport { encodeBase64 } from '../helpers/base64'\nimport { validateOrThrow } from '../utils/validation'\nimport { resolveMediaReader } from '../contracts/reader_resolvers'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../utils/encoder_symbols'\nimport { implementsMediaReader, mediaReaderSchema } from '../contracts/media_reader'\nimport {\n E_INVALID_INITIAL_MEDIA_VALUE,\n E_NOT_A_MEDIA_READER,\n E_READER_NOT_DESCRIBABLE,\n} from '../exceptions/runtime'\nimport type { AdkEncodableSnapshot } from './encodable'\nimport type { MediaReader } from '../contracts/media_reader'\nimport type { ReaderDescriptor } from '../contracts/reader_descriptor'\n\n/**\n * The set of supported media kinds.\n *\n * @remarks\n * Modality coverage is asymmetric across providers. The framework defines no\n * `supportedModalities` field — how a battery handles a modality it cannot natively render is\n * the battery author's call (see `unsupportedMediaPolicy` on the OpenAI Chat Completions\n * battery).\n */\nexport const MediaKind = ['image', 'audio', 'video', 'document'] as const\n\n/**\n * Union of all recognised media kind identifier strings.\n */\nexport type MediaKind = (typeof MediaKind)[number]\n\n/**\n * Provenance axis. *Who is the framework willing to vouch for as the source of these bytes?*\n *\n * @remarks\n * Mirrors `RetrievableTrustTier` deliberately — same vocabulary, same question:\n * *did this content come from a place the agent should treat as authoritative?*\n *\n * - `'first-party'` — deployer-vetted bytes (tool output the operator authored, signed\n * internal assets).\n * - `'third-party-public'` — open-web fetches, public APIs, public corpora.\n * - `'third-party-private'` — user uploads, partner APIs, private corpora.\n */\nexport const MediaTrustTier = ['first-party', 'third-party-public', 'third-party-private'] as const\nexport type MediaTrustTier = (typeof MediaTrustTier)[number]\n\n/**\n * Modality-hazard axis. *How dangerous is it to let the model decode these bytes?*\n *\n * @remarks\n * Orthogonal to provenance — a first-party trusted PDF can still carry hidden text layers; a\n * third-party-public raw image can still be encoded as opaque pixels with adversarial\n * perturbations.\n *\n * - `'inert'` — bytes the model never decodes as instructions (e.g. a handle that is never\n * inlined into the prompt).\n * - `'extractable-instructions'` — text-bearing media: PDFs, screenshots with UI text, documents.\n * Hazard is OCR / embedded-text-layer reads.\n * - `'opaque-perceptual'` — raw vision/audio/video the model encodes directly. Hazard is\n * steganographic LSB prompts, adversarial perturbations, ultrasonic audio — invisible to any\n * pre-screen.\n *\n * See `/the-loop/trust-tiers/media` and its research sub-page `/the-loop/trust-tiers/media/research`.\n */\nexport const MediaModalityHazard = [\n 'inert',\n 'extractable-instructions',\n 'opaque-perceptual',\n] as const\nexport type MediaModalityHazard = (typeof MediaModalityHazard)[number]\n\n/**\n * Per-entry shape stored in a {@link Media}'s `stash` register.\n *\n * @remarks\n * Each entry carries its own trust tier so render code can route derived text (OCR, captions,\n * transcripts) through its own envelope independent of the parent media. How a battery or\n * middleware assigns those entry-level tiers is the implementor's call — the primitive contract\n * does not enforce a \"downgrade derived interpretation from possibly-adversarial bytes\" policy.\n */\nexport interface MediaStashEntry {\n /** The value of the entry — any serialisable shape the consumer wants to store. */\n value: unknown\n /** Trust tier for this specific entry; routed independently of the parent media. */\n trustTier: MediaTrustTier\n /** Optional pointer to the parent Media id this entry was derived from. */\n derivedFromMedia?: string\n}\n\n/**\n * Plain input object supplied to {@link Media} at construction time.\n *\n * @remarks\n * Validated against `rawMediaSchema` before the `Media` instance is created.\n */\nexport interface RawMedia {\n /**\n * Stable unique identifier for this media instance. Required for strict symmetry with\n * `Message.id` and `ToolCall.id`. When omitted, a fresh UUIDv6 is assigned at construction\n * time.\n */\n id?: string\n /** The media kind. See {@link MediaKind}. */\n kind: MediaKind\n /** The MIME type of the underlying bytes. */\n mimeType: string\n /** Filename used by providers that key on it (e.g. OpenAI `file.filename`). */\n filename: string\n /** Re-openable byte source. See {@link @nhtio/adk!MediaReader}. */\n reader: MediaReader\n /**\n * Trust tier declared at construction time. Required — there is NO default.\n * See {@link MediaTrustTier}.\n */\n trustTier: MediaTrustTier\n /**\n * Modality hazard declared at construction time. Required — there is NO default.\n * See {@link MediaModalityHazard}.\n */\n modalityHazard: MediaModalityHazard\n /** Optional provenance pointer (URL, tool name, etc.) for audit / events. */\n source?: string\n /**\n * Free-form per-instance metadata register. Middleware pipelines append to this — typically\n * with a text description, transcript, caption, or alt-text — so downstream code that cannot\n * consume the media natively has a model-readable fallback. No keys are reserved by the\n * framework. Defaults to `{}`.\n */\n stash?: Record<string, MediaStashEntry>\n}\n\nconst stashEntrySchema = validator\n .object<MediaStashEntry>({\n value: validator.any().required(),\n trustTier: validator\n .string()\n .valid(...MediaTrustTier)\n .required(),\n derivedFromMedia: validator.string().optional(),\n })\n .unknown(false)\n\n/**\n * Validator schema used to validate a {@link RawMedia} before constructing a {@link Media}.\n */\nconst rawMediaSchema = validator.object<RawMedia>({\n id: validator.string().optional(),\n kind: validator\n .string()\n .valid(...MediaKind)\n .required(),\n mimeType: validator.string().required(),\n filename: validator.string().required(),\n reader: mediaReaderSchema.required(),\n trustTier: validator\n .string()\n .valid(...MediaTrustTier)\n .required(),\n modalityHazard: validator\n .string()\n .valid(...MediaModalityHazard)\n .required(),\n source: validator.string().optional(),\n stash: validator.object().pattern(validator.string(), stashEntrySchema).optional(),\n})\n\ninterface ResolvedMedia {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n trustTier: MediaTrustTier\n modalityHazard: MediaModalityHazard\n source?: string\n stash?: Record<string, MediaStashEntry>\n}\n\nconst conservativeHazardForKind = (kind: MediaKind): MediaModalityHazard => {\n return kind === 'document' ? 'extractable-instructions' : 'opaque-perceptual'\n}\n\n/**\n * Shape returned by {@link Media.toJSON}. Metadata-only — bytes and the reader are stripped so\n * naive event/log serialisation never materialises bytes.\n */\n/** The plain-object, JSON-safe form of a {@link Media} produced by {@link Media.toJSON}. */\nexport interface SerializedMedia {\n /** Stable identifier for this media asset. */\n id: string\n /** High-level modality of the asset (e.g. image, audio, document). */\n kind: MediaKind\n /** MIME type of the underlying bytes (e.g. `image/png`). */\n mimeType: string\n /** Original or suggested file name for the asset. */\n filename: string\n /** Optional provenance string (URL, path, or other origin marker). */\n source?: string\n /** Trust tier governing how the asset's content is framed to the model. */\n trustTier: MediaTrustTier\n /** Whether the modality can carry hidden instructions (`extractable-instructions`) or is opaque-perceptual. */\n modalityHazard: MediaModalityHazard\n /** Adapter-scoped side-channel data keyed by name (e.g. provider upload handles). */\n stash: Record<string, MediaStashEntry>\n /** Size of the underlying bytes in bytes, when known. */\n byteLength?: number\n}\n\n/**\n * Lazy, re-openable view over a binary asset (image, audio, video, document).\n *\n * @remarks\n * Dual-peer to {@link @nhtio/adk!Tokenizable} (silo) and {@link @nhtio/adk!SpooledArtifact}\n * (handle). Wraps a {@link @nhtio/adk!MediaReader} contract — the framework owns the contract, the\n * implementor owns the storage backend. Bytes are reached only through the reader; the primitive\n * itself never inlines bytes.\n *\n * Construction requires `trustTier` and `modalityHazard` — the framework refuses to guess\n * provenance or decoding hazard. Ergonomic factories ({@link Media.userAttachment},\n * {@link Media.toolGenerated}, {@link Media.retrievedPublic}, {@link Media.retrievedPrivate})\n * force the labelling decision at the call site without becoming defaults on the bare\n * constructor.\n */\nexport class Media {\n /**\n * Validator schema that accepts a {@link RawMedia} object.\n */\n public static schema = rawMediaSchema\n\n /**\n * The set of recognised media kinds. Exposed for downstream schemas that need to discriminate\n * on `kind`.\n */\n public static MediaKind = MediaKind\n\n /**\n * The set of recognised trust tiers.\n */\n public static MediaTrustTier = MediaTrustTier\n\n /**\n * The set of recognised modality hazards.\n */\n public static MediaModalityHazard = MediaModalityHazard\n\n /**\n * Returns `true` if `value` is a {@link Media} 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 Media} instance.\n */\n public static isMedia(value: unknown): value is Media {\n return isInstanceOf(value, 'Media', Media)\n }\n\n /** Stable unique identifier. */\n declare readonly id: string\n /** Media kind. */\n declare readonly kind: MediaKind\n /** MIME type of the underlying bytes. */\n declare readonly mimeType: string\n /** Filename surfaced to providers that key on it. */\n declare readonly filename: string\n /** Optional provenance pointer. */\n declare readonly source: string | undefined\n /** Trust tier declared at construction time. */\n declare readonly trustTier: MediaTrustTier\n /** Modality hazard declared at construction time. */\n declare readonly modalityHazard: MediaModalityHazard\n /** Mutable per-instance metadata register; middleware pipelines append to this. */\n declare readonly stash: Registry\n\n #id: string\n #kind: MediaKind\n #mimeType: string\n #filename: string\n #source?: string\n #trustTier: MediaTrustTier\n #modalityHazard: MediaModalityHazard\n #reader: MediaReader\n #stash: Registry\n\n /**\n * @param raw - The raw media input validated against `rawMediaSchema`.\n * @throws {@link @nhtio/adk/exceptions!E_INVALID_INITIAL_MEDIA_VALUE} when `raw` does not satisfy the schema.\n * @throws {@link @nhtio/adk/exceptions!E_NOT_A_MEDIA_READER} when `raw.reader` does not implement {@link @nhtio/adk!MediaReader}.\n */\n constructor(raw: RawMedia) {\n let resolved: ResolvedMedia\n try {\n resolved = validateOrThrow<ResolvedMedia>(rawMediaSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_MEDIA_VALUE({ cause: isError(err) ? err : undefined })\n }\n if (!implementsMediaReader(resolved.reader)) {\n throw new E_NOT_A_MEDIA_READER()\n }\n this.#id = resolved.id ?? uuidv6()\n this.#kind = resolved.kind\n this.#mimeType = resolved.mimeType\n this.#filename = resolved.filename\n this.#source = resolved.source\n this.#trustTier = resolved.trustTier\n this.#modalityHazard = resolved.modalityHazard\n this.#reader = resolved.reader\n this.#stash = new Registry(resolved.stash as Record<string, unknown> | undefined)\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n kind: {\n get: () => this.#kind,\n enumerable: true,\n configurable: false,\n },\n mimeType: {\n get: () => this.#mimeType,\n enumerable: true,\n configurable: false,\n },\n filename: {\n get: () => this.#filename,\n enumerable: true,\n configurable: false,\n },\n source: {\n get: () => this.#source,\n enumerable: true,\n configurable: false,\n },\n trustTier: {\n get: () => this.#trustTier,\n enumerable: true,\n configurable: false,\n },\n modalityHazard: {\n get: () => this.#modalityHazard,\n enumerable: true,\n configurable: false,\n },\n stash: {\n get: () => this.#stash,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Re-opens the underlying byte source and returns a fresh ReadableStream.\n *\n * @returns A drainable `ReadableStream` over the underlying bytes.\n */\n async stream(): Promise<ReadableStream<Uint8Array>> {\n return this.#reader.stream()\n }\n\n /**\n * Returns the total number of bytes in the underlying data, or `undefined` if unknown.\n *\n * @returns The byte length, or `undefined` when the underlying source cannot report it.\n */\n async byteLength(): Promise<number | undefined> {\n return this.#reader.byteLength()\n }\n\n /**\n * Drains the reader's stream and returns the underlying bytes as a single `Uint8Array`.\n *\n * @remarks\n * Convenience for callers that need the full buffer (e.g. inline base64 encoding). Forces\n * full materialisation — large assets should be piped through {@link Media.stream} instead.\n */\n async asBytes(): Promise<Uint8Array> {\n const stream = await this.stream()\n const reader = stream.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n if (value) {\n chunks.push(value)\n total += value.byteLength\n }\n }\n const out = new Uint8Array(total)\n let offset = 0\n for (const chunk of chunks) {\n out.set(chunk, offset)\n offset += chunk.byteLength\n }\n return out\n }\n\n /**\n * Drains the reader's stream and returns the underlying bytes as a base64 string.\n *\n * @remarks\n * Cross-environment: prefers Node's `Buffer.from(buf).toString('base64')` when available;\n * otherwise chunk-encodes through `btoa` with a 0x8000-byte window to avoid stack overflow\n * on large buffers.\n */\n async asBase64(): Promise<string> {\n const bytes = await this.asBytes()\n return encodeBase64(bytes)\n }\n\n /**\n * Returns the metadata-only serialisation of this Media. Bytes and the reader are stripped\n * so naive event/log serialisation never materialises bytes.\n *\n * @remarks\n * Implementations that have cheap, already-cached `byteLength` may opt to include it; this\n * default implementation omits it to preserve the \"lazy by default\" invariant. Consumers that\n * need byteLength on the serialised payload should call `await media.byteLength()` and merge\n * the result.\n */\n toJSON(): SerializedMedia {\n return {\n id: this.#id,\n kind: this.#kind,\n mimeType: this.#mimeType,\n filename: this.#filename,\n source: this.#source,\n trustTier: this.#trustTier,\n modalityHazard: this.#modalityHazard,\n stash: this.#stash.all() as Record<string, MediaStashEntry>,\n }\n }\n\n /**\n * Serialise this Media into an `@nhtio/encoder` snapshot — the **handle**, never the bytes.\n *\n * @remarks\n * Emits every metadata field plus the reader's {@link @nhtio/adk!ReaderDescriptor} (via its\n * `describe()` method). The bytes are not inlined: decode re-binds the reader from the descriptor\n * through a registered resolver. Throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} when the backing\n * reader cannot describe itself (e.g. a `fromWebFile` Blob reader) — there is no serialisable handle to\n * write, and silently dropping the reader would decode into a handle pointing at nothing.\n *\n * @returns A snapshot consumed by {@link Media.[DECODE_METHOD]} / the encoder.\n * @throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} when the reader has no `describe()`.\n */\n [ENCODE_METHOD](): AdkEncodableSnapshot {\n const descriptor = this.#reader.describe?.()\n if (!descriptor) {\n throw new E_READER_NOT_DESCRIBABLE(['reader'])\n }\n return {\n id: this.#id,\n kind: this.#kind,\n mimeType: this.#mimeType,\n filename: this.#filename,\n source: this.#source,\n trustTier: this.#trustTier,\n modalityHazard: this.#modalityHazard,\n stash: this.#stash.all(),\n reader: descriptor,\n }\n }\n\n /**\n * Reconstruct a {@link Media} from an {@link Media.[ENCODE_METHOD]} snapshot.\n *\n * @remarks\n * Re-binds the reader from the captured descriptor through the registered resolver\n * ({@link @nhtio/adk!resolveMediaReader}), then re-validates via the normal constructor. Throws\n * {@link @nhtio/adk!E_NO_READER_RESOLVER} when no resolver is registered for the descriptor's tag.\n *\n * @param data - The snapshot produced by {@link Media.[ENCODE_METHOD]}.\n * @returns A fully-validated {@link Media} backed by a freshly-resolved reader.\n */\n static [DECODE_METHOD](data: AdkEncodableSnapshot): Media {\n const snapshot = data as {\n id: string\n kind: MediaKind\n mimeType: string\n filename: string\n source?: string\n trustTier: MediaTrustTier\n modalityHazard: MediaModalityHazard\n stash?: Record<string, MediaStashEntry>\n reader: ReaderDescriptor\n }\n return new Media({\n id: snapshot.id,\n kind: snapshot.kind,\n mimeType: snapshot.mimeType,\n filename: snapshot.filename,\n source: snapshot.source,\n trustTier: snapshot.trustTier,\n modalityHazard: snapshot.modalityHazard,\n stash: snapshot.stash,\n reader: resolveMediaReader(snapshot.reader),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} representing a user-supplied attachment.\n *\n * @remarks\n * Pre-fills `trustTier: 'third-party-private'` and derives `modalityHazard` from `kind`\n * (`document` → `'extractable-instructions'`; everything else → `'opaque-perceptual'`).\n * Use the bare constructor when the conservative kind→hazard mapping is wrong for your case.\n */\n public static userAttachment(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'third-party-private',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} produced by a first-party tool.\n *\n * @remarks\n * Pre-fills `trustTier: 'first-party'` and derives `modalityHazard` from `kind`.\n */\n public static toolGenerated(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'first-party',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} retrieved from a public third-party source.\n *\n * @remarks\n * Pre-fills `trustTier: 'third-party-public'` and derives `modalityHazard` from `kind`.\n */\n public static retrievedPublic(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'third-party-public',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} retrieved from a private third-party source.\n *\n * @remarks\n * Pre-fills `trustTier: 'third-party-private'` and derives `modalityHazard` from `kind`.\n */\n public static retrievedPrivate(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'third-party-private',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n}\n\n/**\n * Returns `true` if `value` is a {@link Media} instance.\n *\n * @remarks\n * Module-level convenience alias for {@link Media.isMedia}. Uses {@link @nhtio/adk!isInstanceOf} for\n * cross-realm safety.\n */\nexport const isMedia = (value: unknown): value is Media => {\n return isInstanceOf(value, 'Media', Media)\n}\n","import { Media } from './media'\nimport { Tokenizable } from './tokenizable'\nimport { validator } from '@nhtio/validation'\nimport { SpooledArtifact } from './spooled_artifact'\nimport { validateOrThrow } from '../utils/validation'\nimport { isObject, isInstanceOf, isError } from '../utils/guards'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../utils/encoder_symbols'\nimport { E_INVALID_INITIAL_TOOL_CALL_VALUE } from '../exceptions/runtime'\nimport type { DateTime } from 'luxon'\nimport type { AdkEncodableSnapshot } from './encodable'\n\n/**\n * Union of every shape a {@link ToolCall.results} field may carry.\n *\n * @remarks\n * Three silos with distinct render-time semantics:\n *\n * - {@link @nhtio/adk!Tokenizable} — always singular. The {@link @nhtio/adk!ArtifactTool}\n * carve-out: a model-visible text answer that explicitly opts out of artifact wrapping to\n * break the recursive grep-on-the-grep-result loop.\n * - {@link @nhtio/adk!SpooledArtifact} or `SpooledArtifact[]` — bounded text output spooled to durable\n * storage. A single tool call may legitimately produce multiple artifacts (e.g. one tool\n * that returns N PR bodies). LLM adapters render either inline (full body in trust envelope)\n * or as a handle reference (forged artifact-query tools).\n * - {@link @nhtio/adk!Media} or `Media[]` — binary modality output (image, audio, video, document).\n * Adapters render as provider-specific content blocks (`image_url`, `input_audio`, `file`,\n * etc.). Bytes are lazy — reached only through {@link @nhtio/adk!Media.stream}.\n */\nexport type ToolCallResults = Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[]\n\nconst isToolCallResults = (value: unknown): value is ToolCallResults => {\n if (Tokenizable.isTokenizable(value)) return true\n if (SpooledArtifact.isSpooledArtifact(value)) return true\n if (Media.isMedia(value)) return true\n if (Array.isArray(value) && value.length > 0) {\n const allMedia = value.every((entry) => Media.isMedia(entry))\n if (allMedia) return true\n const allSpooled = value.every((entry) => SpooledArtifact.isSpooledArtifact(entry))\n if (allSpooled) return true\n }\n return false\n}\n\n/**\n * Plain input object supplied to {@link ToolCall} at construction time.\n *\n * @remarks\n * Validated against `rawToolCallSchema` before the `ToolCall` instance is created.\n * Temporal fields accept any value that Luxon can parse — ISO strings, Unix timestamps,\n * `Date` objects, or existing `DateTime` instances.\n */\nexport interface RawToolCall {\n /** Stable unique identifier for this tool call; correlates the request with its result. */\n id: string\n /** Name of the tool the model has requested. */\n tool: string\n /**\n * Arguments the model supplied for this tool call.\n *\n * @remarks\n * Accepts either a plain object or a JSON-encoded string that deserialises to an object.\n * Always exposed as a plain object on the constructed {@link ToolCall} instance.\n */\n args: string | Record<string, unknown>\n /** Integrity checksum over `tool` and `args`; can be used to detect tampering before execution. */\n checksum: string\n /** `true` once the tool call has finished (successfully or not). */\n isComplete: boolean\n /** `true` when the tool execution produced an error; inspect `results` for detail. */\n isError: boolean\n /**\n * Result returned by the tool, or error detail when `isError` is `true`.\n *\n * @remarks\n * Three silos with distinct render-time semantics — see {@link ToolCallResults}:\n *\n * - For a normal {@link @nhtio/adk!Tool} call whose handler returned `string` or\n * `Uint8Array`, this is a {@link @nhtio/adk!SpooledArtifact} (or one of its subclasses) wrapping the\n * spooled bytes. Tools that legitimately produce multiple bounded artifacts may return\n * a `SpooledArtifact[]`.\n * - For a `Tool` call whose handler returned a {@link @nhtio/adk!Media} or `Media[]`, this is the same\n * media handle(s) — the explicit-modality silo bypasses `SpooledArtifact` wrapping because\n * the bytes are binary and rendered as provider-specific content blocks, not text.\n * - For an {@link @nhtio/adk!ArtifactTool} call (a forged artifact-query tool),\n * this is a {@link @nhtio/adk!Tokenizable} holding the raw model-visible answer — `ArtifactTool`\n * explicitly opts out of wrapping to break the recursive grep-on-the-grep-result loop.\n *\n * The ADK sets {@link RawToolCall.fromArtifactTool} on calls produced by an\n * `ArtifactTool` so subsequent `forgeTools(ctx)` invocations can filter them out of the\n * `callId` enum.\n */\n results: ToolCallResults\n /**\n * Optional vendor-opaque payload that round-trips back to a matching model wire.\n *\n * @remarks\n * Carries provider metadata the ADK cannot interpret, such as Gemini's `thought_signature`\n * on a function call, GPT-OSS's commentary-channel tag, or other vendor-opaque metadata\n * that a provider needs echoed back.\n *\n * A present `payload` requires a present {@link RawToolCall.replayCompatibility} so the\n * matching adapter wire shape is known.\n *\n * @defaultValue `undefined`\n */\n payload?: unknown\n /**\n * Optional free-form identifier describing which adapter wire-shape this tool call can be\n * safely replayed into.\n *\n * @remarks\n * A `replayCompatibility` without a `payload` is allowed — it documents intent without\n * requiring an opaque blob.\n *\n * @defaultValue `undefined`\n */\n replayCompatibility?: string\n /**\n * `true` when this tool call originated from an {@link @nhtio/adk!ArtifactTool}\n * invocation. Defaults to `false`.\n *\n * @remarks\n * Set by the ADK's result-wrapping touch sites when `ArtifactTool.isArtifactTool(tool)`\n * holds. Read by `SpooledArtifact.forgeTools(ctx)` when building each descriptor's `callId`\n * enum — calls with this flag set are excluded so the model can't `artifact_grep` on a\n * previous `artifact_grep` result. Optional in the raw shape (defaults to `false`); always\n * defined on the constructed {@link ToolCall}.\n *\n * @defaultValue `false`\n */\n fromArtifactTool?: boolean\n /**\n * When `false` (the default), the adapter surfaces a {@link @nhtio/adk!SpooledArtifact} result as a\n * \"handle\" — a directions-bearing envelope that tells the model which forged artifact-query tools to\n * call against this `tc.id` to read the content incrementally, keeping the body OUT of the prompt.\n * When `true`, the adapter renders the result inline — the full stringified body wrapped in the\n * adapter's trust envelope and sent to the model as the `tool` role content.\n *\n * @remarks\n * Handle-by-default is the secure, budget-aligned posture: the LLM batteries already spool-wrap every\n * non-{@link @nhtio/adk!Media}, non-{@link @nhtio/adk!ArtifactTool} tool result into a `SpooledArtifact`,\n * so a result that could be arbitrarily large never lands in the next prompt just because nobody\n * touched a flag — the core ADK context-window-diet principle (see the Budgets / Artifacts docs).\n * Inlining is the OPT-IN: a producer that knows its output is small sets `inline: true` so the model\n * sees the body verbatim without a query round-trip.\n *\n * Policy is the producer's or middleware's call (LLM adapters obey the flag — they never size-check\n * the result or silently switch modes). Set per call at construction, or flip mid-turn via\n * `ctx.mutateToolCall(tc.id, { inline: true })`.\n *\n * Handles only make sense for `SpooledArtifact` (the only result kind the forged artifact-query tools\n * can read). For a {@link @nhtio/adk!Tokenizable} result (e.g. an `ArtifactTool` answer or an error\n * string) the flag is moot — the adapter renders it inline regardless, since there is no queryable\n * artifact to hand back.\n *\n * @defaultValue `false`\n */\n inline?: boolean\n /** When this tool call was first created. */\n createdAt: string | number | Date | DateTime\n /** When this tool call was last modified. */\n updatedAt: string | number | Date | DateTime\n /** When the tool call completed. */\n completedAt: string | number | Date | DateTime\n}\n\n/**\n * A fully-resolved {@link RawToolCall} where temporal fields have been normalised to Luxon\n * `DateTime` instances.\n *\n * @remarks\n * Used internally by the {@link ToolCall} constructor to assign private fields with\n * guaranteed types.\n */\ninterface ResolvedToolCall {\n id: string\n tool: string\n args: Record<string, unknown>\n checksum: string\n isComplete: boolean\n isError: boolean\n results: ToolCallResults\n payload?: unknown\n replayCompatibility?: string\n fromArtifactTool: boolean\n inline: boolean\n createdAt: DateTime\n updatedAt: DateTime\n completedAt: DateTime\n}\n\n/**\n * Validator schema used to validate a {@link RawToolCall} before constructing a {@link ToolCall}.\n *\n * @remarks\n * Validates all fields of {@link RawToolCall}:\n * - `id` — required non-empty string.\n * - `tool` — required non-empty string.\n * - `args` — required; either a plain object or a JSON string that deserialises to an object.\n * Strings are parsed and the resulting object is stored.\n * - `checksum` — required string.\n * - `isComplete` — required boolean.\n * - `isError` — required boolean.\n * - `results` — required; one of {@link @nhtio/adk!Tokenizable}, {@link @nhtio/adk!SpooledArtifact}, a non-empty\n * `SpooledArtifact[]`, {@link @nhtio/adk!Media}, or a non-empty `Media[]`. Arrays must be homogeneous.\n * - `createdAt` / `updatedAt` / `completedAt` — required datetime-parseable values, normalised to `DateTime`.\n *\n * Throws {@link @nhtio/adk!E_INVALID_INITIAL_TOOL_CALL_VALUE} (via the {@link ToolCall} constructor) when\n * validation fails.\n */\nconst rawToolCallSchema = validator\n .object<RawToolCall>({\n id: validator.string().required(),\n tool: validator.string().required(),\n args: validator\n .alternatives(\n validator.object().unknown(true),\n validator.string().custom((value, helpers) => {\n try {\n const parsed = JSON.parse(value)\n if (!isObject(parsed)) {\n return helpers.error('any.invalid')\n }\n return parsed\n } catch {\n return helpers.error('any.invalid')\n }\n })\n )\n .required(),\n checksum: validator.string().required(),\n isComplete: validator.boolean().required(),\n isError: validator.boolean().required(),\n results: validator\n .any()\n .custom((value, helpers) => {\n if (isToolCallResults(value)) {\n return value\n }\n return helpers.error('any.invalid')\n })\n .required(),\n payload: validator.any().optional(),\n replayCompatibility: validator.string().min(1).optional(),\n fromArtifactTool: validator.boolean().default(false),\n inline: validator.boolean().default(false),\n createdAt: validator.datetime().required(),\n updatedAt: validator.datetime().required(),\n completedAt: validator.datetime().required(),\n })\n .custom((value, helpers) => {\n const v = value as RawToolCall\n const hasPayload = v.payload !== undefined && v.payload !== null\n if (hasPayload && (v.replayCompatibility === undefined || v.replayCompatibility === null)) {\n return helpers.error('any.invalid')\n }\n return value\n })\n\n/**\n * An immutable, validated tool call record associated with a turn.\n *\n * @remarks\n * Represents a completed tool invocation from the conversation history — `results`,\n * `completedAt`, `isComplete`, and `isError` are all present and required.\n * Temporal fields are normalised to Luxon `DateTime` instances at construction time.\n */\nexport class ToolCall {\n /**\n * Validator schema that accepts a {@link RawToolCall} object.\n *\n * @remarks\n * Reusable fragment for any schema that needs to validate or nest a tool call entry.\n */\n public static schema = rawToolCallSchema\n\n /**\n * Returns `true` if `value` is a {@link ToolCall} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety — `instanceof` would fail for instances\n * created in a different module copy or VM context.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link ToolCall} instance.\n */\n public static isToolCall(value: unknown): value is ToolCall {\n return isInstanceOf(value, 'ToolCall', ToolCall)\n }\n\n /** Stable unique identifier for this tool call; correlates the request with its result. */\n declare readonly id: string\n /** Name of the tool the model has requested. */\n declare readonly tool: string\n /** Arguments the model supplied for this tool call, always as a plain object. */\n declare readonly args: Record<string, unknown>\n /** Integrity checksum over `tool` and `args`. */\n declare readonly checksum: string\n /** `true` once the tool call has finished (successfully or not). */\n declare readonly isComplete: boolean\n /** `true` when the tool execution produced an error; inspect `results` for detail. */\n declare readonly isError: boolean\n /**\n * Result returned by the tool, or error detail when `isError` is `true`.\n *\n * @remarks\n * One of three silos — see {@link ToolCallResults}. {@link @nhtio/adk!SpooledArtifact} or\n * `SpooledArtifact[]` for normal text-output {@link @nhtio/adk!Tool} calls;\n * {@link @nhtio/adk!Media} or `Media[]` for tool calls whose handler returned binary modality output;\n * {@link @nhtio/adk!Tokenizable} for {@link @nhtio/adk!ArtifactTool} calls\n * (see {@link ToolCall.fromArtifactTool}).\n */\n declare readonly results: ToolCallResults\n /**\n * Optional vendor-opaque payload that round-trips back to a matching model wire.\n * See {@link RawToolCall.payload}.\n */\n declare readonly payload: unknown\n /**\n * Optional wire-shape identifier describing which adapter can safely replay this tool call.\n * See {@link RawToolCall.replayCompatibility}.\n */\n declare readonly replayCompatibility: string | undefined\n /**\n * `true` when this tool call originated from an {@link @nhtio/adk!ArtifactTool}\n * invocation. Used by `SpooledArtifact.forgeTools(ctx)` to filter out forged-tool results from\n * the `callId` enum it builds.\n */\n declare readonly fromArtifactTool: boolean\n /**\n * `false` (default) instructs LLM adapters to surface a `SpooledArtifact` result as a handle\n * reference (body kept out of the prompt); `true` renders the result inline. See\n * {@link RawToolCall.inline}.\n */\n declare readonly inline: boolean\n /** When this tool call was first created. */\n declare readonly createdAt: DateTime\n /** When this tool call was last modified. */\n declare readonly updatedAt: DateTime\n /** When the tool call completed. */\n declare readonly completedAt: DateTime\n\n #id: string\n #tool: string\n #args: Record<string, unknown>\n #checksum: string\n #isComplete: boolean\n #isError: boolean\n #results: ToolCallResults\n #payload: unknown\n #replayCompatibility: string | undefined\n #fromArtifactTool: boolean\n #inline: boolean\n #createdAt: DateTime\n #updatedAt: DateTime\n #completedAt: DateTime\n\n /**\n * @param raw - The raw tool call input validated against `rawToolCallSchema`.\n * @throws {@link @nhtio/adk!E_INVALID_INITIAL_TOOL_CALL_VALUE} when `raw` does not satisfy the schema.\n */\n constructor(raw: RawToolCall) {\n let resolved: ResolvedToolCall\n try {\n resolved = validateOrThrow<ResolvedToolCall>(rawToolCallSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_TOOL_CALL_VALUE({ cause: isError(err) ? err : undefined })\n }\n this.#id = resolved.id\n this.#tool = resolved.tool\n this.#args = resolved.args\n this.#checksum = resolved.checksum\n this.#isComplete = resolved.isComplete\n this.#isError = resolved.isError\n this.#results = resolved.results\n this.#payload = resolved.payload\n this.#replayCompatibility = resolved.replayCompatibility\n this.#fromArtifactTool = resolved.fromArtifactTool\n this.#inline = resolved.inline\n this.#createdAt = resolved.createdAt\n this.#updatedAt = resolved.updatedAt\n this.#completedAt = resolved.completedAt\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n tool: {\n get: () => this.#tool,\n enumerable: true,\n configurable: false,\n },\n args: {\n get: () => this.#args,\n enumerable: true,\n configurable: false,\n },\n checksum: {\n get: () => this.#checksum,\n enumerable: true,\n configurable: false,\n },\n isComplete: {\n get: () => this.#isComplete,\n enumerable: true,\n configurable: false,\n },\n isError: {\n get: () => this.#isError,\n enumerable: true,\n configurable: false,\n },\n results: {\n get: () => this.#results,\n enumerable: true,\n configurable: false,\n },\n payload: {\n get: () => this.#payload,\n enumerable: true,\n configurable: false,\n },\n replayCompatibility: {\n get: () => this.#replayCompatibility,\n enumerable: true,\n configurable: false,\n },\n fromArtifactTool: {\n get: () => this.#fromArtifactTool,\n enumerable: true,\n configurable: false,\n },\n inline: {\n get: () => this.#inline,\n enumerable: true,\n configurable: false,\n },\n createdAt: {\n get: () => this.#createdAt,\n enumerable: true,\n configurable: false,\n },\n updatedAt: {\n get: () => this.#updatedAt,\n enumerable: true,\n configurable: false,\n },\n completedAt: {\n get: () => this.#completedAt,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Serialise this ToolCall into an `@nhtio/encoder` snapshot.\n *\n * @remarks\n * Emits a {@link RawToolCall}-shaped object. `results` is the live {@link ToolCallResults} union —\n * a {@link @nhtio/adk!Tokenizable}, {@link @nhtio/adk!SpooledArtifact}(s), or {@link @nhtio/adk!Media}(s) —\n * which the encoder recurses into; reader-backed results round-trip as handles (and throw\n * {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} if a backing reader cannot describe itself). The `args`\n * object and the producer-supplied `checksum` are emitted verbatim, so the constructor's\n * checksum re-validation passes on decode. Round-trips via {@link ToolCall.[DECODE_METHOD]}.\n *\n * @returns A {@link RawToolCall}-shaped snapshot.\n */\n [ENCODE_METHOD](): AdkEncodableSnapshot {\n return {\n id: this.#id,\n tool: this.#tool,\n args: this.#args,\n checksum: this.#checksum,\n isComplete: this.#isComplete,\n isError: this.#isError,\n results: this.#results,\n payload: this.#payload,\n replayCompatibility: this.#replayCompatibility,\n fromArtifactTool: this.#fromArtifactTool,\n inline: this.#inline,\n createdAt: this.#createdAt,\n updatedAt: this.#updatedAt,\n completedAt: this.#completedAt,\n }\n }\n\n /**\n * Reconstruct a {@link ToolCall} from a {@link ToolCall.[ENCODE_METHOD]} snapshot.\n *\n * @param data - The snapshot produced by {@link ToolCall.[ENCODE_METHOD]}.\n * @returns A fully-validated {@link ToolCall}.\n */\n static [DECODE_METHOD](data: AdkEncodableSnapshot): ToolCall {\n return new ToolCall(data as RawToolCall)\n }\n}\n"],"mappings":";;;;;;;AAiBA,IAAM,kBAA6C;CACjD,OAAQ,WAA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A,CAAC,iBAAuC;EACtC,OAAO;GACL,IAAI,KAAKb;GACT,MAAM,KAAKC;GACX,MAAM,KAAKC;GACX,UAAU,KAAKC;GACf,YAAY,KAAKC;GACjB,SAAS,KAAKC;GACd,SAAS,KAAKC;GACd,SAAS,KAAKC;GACd,qBAAqB,KAAKC;GAC1B,kBAAkB,KAAKC;GACvB,QAAQ,KAAKC;GACb,WAAW,KAAKC;GAChB,WAAW,KAAKC;GAChB,aAAa,KAAKC;EACpB;CACF;;;;;;;CAQA,QAAQ,eAAe,MAAsC;EAC3D,OAAO,IAAI,SAAS,IAAmB;CACzC;AACF"}
1
+ {"version":3,"file":"tool_call-Cfaj-6zK.mjs","names":["#id","#kind","#mimeType","#filename","#source","#trustTier","#modalityHazard","#reader","#stash","#id","#tool","#args","#checksum","#isComplete","#isError","#results","#payload","#replayCompatibility","#fromArtifactTool","#inline","#createdAt","#updatedAt","#completedAt"],"sources":["../src/lib/helpers/base64.ts","../src/lib/contracts/media_reader.ts","../src/lib/classes/media.ts","../src/lib/classes/tool_call.ts"],"sourcesContent":["/**\n * Cross-environment base64 helpers for `Uint8Array` payloads.\n *\n * @module\n *\n * @remarks\n * Used by {@link @nhtio/adk!Media}'s `asBase64()` and by the in-memory reader handle path\n * (`describe()`/resolver), which inlines its buffer as base64 because it owns no external locator. Both\n * directions prefer Node's `Buffer` when present and fall back to `btoa`/`atob` with a chunked window so\n * large buffers do not overflow the call stack.\n */\n\ninterface MinimalBuffer {\n from(input: Uint8Array): { toString(enc: string): string }\n from(input: string, enc: string): Uint8Array\n}\n\nconst getBuffer = (): MinimalBuffer | undefined => {\n return (globalThis as { Buffer?: MinimalBuffer }).Buffer\n}\n\n/**\n * Encode a `Uint8Array` as a base64 string.\n *\n * @remarks\n * Prefers `Buffer.from(bytes).toString('base64')` when `globalThis.Buffer` exists; otherwise\n * chunk-encodes through `btoa` with a `0x8000`-byte window to avoid `Maximum call stack size exceeded`\n * on large buffers.\n *\n * @param bytes - The buffer to encode.\n * @returns The base64 representation.\n */\nexport const encodeBase64 = (bytes: Uint8Array): string => {\n const buffer = getBuffer()\n if (buffer && typeof buffer.from === 'function') {\n return buffer.from(bytes).toString('base64')\n }\n const chunkSize = 0x8000\n let binary = ''\n for (let i = 0; i < bytes.length; i += chunkSize) {\n const chunk = bytes.subarray(i, i + chunkSize)\n binary += String.fromCharCode.apply(null, Array.from(chunk) as number[])\n }\n return btoa(binary)\n}\n\n/**\n * Decode a base64 string back into a `Uint8Array`.\n *\n * @remarks\n * Inverse of {@link encodeBase64}. Prefers `Buffer.from(b64, 'base64')` when `globalThis.Buffer` exists;\n * otherwise decodes through `atob` byte-by-byte.\n *\n * @param b64 - The base64 string to decode.\n * @returns The decoded bytes.\n */\nexport const decodeBase64 = (b64: string): Uint8Array => {\n const buffer = getBuffer()\n if (buffer && typeof buffer.from === 'function') {\n const decoded = buffer.from(b64, 'base64')\n // `Buffer` is a `Uint8Array` subclass; return a plain view over the same bytes.\n return new Uint8Array(decoded)\n }\n const binary = atob(b64)\n const out = new Uint8Array(binary.length)\n for (let i = 0; i < binary.length; i++) {\n out[i] = binary.charCodeAt(i)\n }\n return out\n}\n","import { validator } from '@nhtio/validation'\nimport { passesSchema } from '../utils/validation'\nimport type { ReaderDescriptor } from './reader_descriptor'\n\n/**\n * Re-openable byte source contract for a Media instance.\n *\n * @remarks\n * Peer to {@link @nhtio/adk!SpoolReader} but tuned for binary streaming rather than line-indexed text.\n * Each `stream()` call must return a fresh, drainable `ReadableStream` over the same underlying\n * bytes — implementations model replay: in-memory readers reconstitute the stream from the\n * buffer, file-backed readers reopen the file handle, HTTP-backed readers re-issue the fetch,\n * cloud blob readers re-issue the GET. The implementor owns the storage and the cost of keeping\n * the underlying source addressable. Implementors whose underlying source is genuinely\n * non-replayable (a raw HTTP body they were handed once) are responsible for caching locally\n * before constructing the Media.\n *\n * Both methods may be synchronous or asynchronous to accommodate both in-memory and I/O-backed\n * implementations without forcing unnecessary promise overhead on simple cases.\n */\nexport interface MediaReader {\n /**\n * Re-opens the underlying byte source and returns a fresh ReadableStream.\n *\n * @remarks\n * Each call yields a new, drainable stream over the same bytes. Render code that needs the\n * full buffer (e.g. base64-encoding an inline image_url) drains the stream; render code that\n * can forward the stream (e.g. multipart upload) passes the stream through without buffering.\n *\n * @returns A drainable ReadableStream of Uint8Array chunks over the underlying bytes.\n */\n stream(): ReadableStream<Uint8Array> | Promise<ReadableStream<Uint8Array>>\n\n /**\n * Returns the total number of bytes in the underlying data, or `undefined` if unknown.\n *\n * @remarks\n * Used for telemetry, budget checks, and pre-flight provider size validation without forcing\n * a stream drain. Sources of unknown length may return `undefined` — absence is treated as\n * \"unknown\", not \"zero\".\n *\n * @returns The byte length of the underlying data, or `undefined` when unknown.\n */\n byteLength(): number | undefined | Promise<number | undefined>\n\n /**\n * Optionally emit a serialisable {@link ReaderDescriptor} so a {@link @nhtio/adk!Media} backed by this\n * reader can round-trip through `encode()`/`decode()` as a **handle**.\n *\n * @remarks\n * Synchronous by contract — the encoder's `[ENCODE_METHOD]()` is synchronous and cannot await, so a\n * reader whose handle is only obtainable asynchronously (e.g. draining a `Blob`) must NOT implement\n * this method; encoding such a `Media` throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE}. The\n * descriptor describes *where the bytes live* (a key, a URL, or an inlined buffer) — never the live\n * binding (`Disk`, OPFS root, `fetch`), which the matching resolver re-injects on decode.\n *\n * A reader that omits this method is treated as non-describable: the bytes still stream normally at\n * runtime, the `Media` simply cannot be serialised.\n *\n * @returns A tagged, serialisable handle, or `undefined`/absent when the reader cannot describe itself.\n */\n describe?(): ReaderDescriptor | undefined\n}\n\n/**\n * Validator schema used to validate a MediaReader value.\n *\n * @remarks\n * Because MediaReader is a structural interface with no associated constructor, validation is\n * duck-typed: the value must be an object, class instance, or function with `stream` and\n * `byteLength` present as callable properties. Arity is not enforced.\n */\nexport const mediaReaderSchema = validator\n .any()\n .required()\n .custom((value, helpers) => {\n if (\n value !== null &&\n value !== undefined &&\n typeof (value as any).stream === 'function' &&\n typeof (value as any).byteLength === 'function'\n ) {\n return value as MediaReader\n }\n return helpers.error('any.invalid')\n })\n\n/**\n * Returns `true` if `value` implements the MediaReader interface.\n *\n * @remarks\n * Duck-typed: checks that `value` is non-null with `stream` and `byteLength` as callable\n * functions. Does not use `instanceof` — there is no MediaReader constructor.\n *\n * @param value - The value to test.\n * @returns `true` when `value` conforms to the MediaReader interface.\n */\nexport const implementsMediaReader = (value: unknown): value is MediaReader => {\n return passesSchema(mediaReaderSchema, value)\n}\n","import { v6 as uuidv6 } from 'uuid'\nimport { Registry } from './registry'\nimport { isError } from '../utils/guards'\nimport { validator } from '@nhtio/validation'\nimport { isInstanceOf } from '../utils/guards'\nimport { encodeBase64 } from '../helpers/base64'\nimport { validateOrThrow } from '../utils/validation'\nimport { resolveMediaReader } from '../contracts/reader_resolvers'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../utils/encoder_symbols'\nimport { implementsMediaReader, mediaReaderSchema } from '../contracts/media_reader'\nimport {\n E_INVALID_INITIAL_MEDIA_VALUE,\n E_NOT_A_MEDIA_READER,\n E_READER_NOT_DESCRIBABLE,\n} from '../exceptions/runtime'\nimport type { AdkEncodableSnapshot } from './encodable'\nimport type { MediaReader } from '../contracts/media_reader'\nimport type { ReaderDescriptor } from '../contracts/reader_descriptor'\n\n/**\n * The set of supported media kinds.\n *\n * @remarks\n * Modality coverage is asymmetric across providers. The framework defines no\n * `supportedModalities` field — how a battery handles a modality it cannot natively render is\n * the battery author's call (see `unsupportedMediaPolicy` on the OpenAI Chat Completions\n * battery).\n */\nexport const MediaKind = ['image', 'audio', 'video', 'document'] as const\n\n/**\n * Union of all recognised media kind identifier strings.\n */\nexport type MediaKind = (typeof MediaKind)[number]\n\n/**\n * Provenance axis. *Who is the framework willing to vouch for as the source of these bytes?*\n *\n * @remarks\n * Mirrors `RetrievableTrustTier` deliberately — same vocabulary, same question:\n * *did this content come from a place the agent should treat as authoritative?*\n *\n * - `'first-party'` — deployer-vetted bytes (tool output the operator authored, signed\n * internal assets).\n * - `'third-party-public'` — open-web fetches, public APIs, public corpora.\n * - `'third-party-private'` — user uploads, partner APIs, private corpora.\n */\nexport const MediaTrustTier = ['first-party', 'third-party-public', 'third-party-private'] as const\nexport type MediaTrustTier = (typeof MediaTrustTier)[number]\n\n/**\n * Modality-hazard axis. *How dangerous is it to let the model decode these bytes?*\n *\n * @remarks\n * Orthogonal to provenance — a first-party trusted PDF can still carry hidden text layers; a\n * third-party-public raw image can still be encoded as opaque pixels with adversarial\n * perturbations.\n *\n * - `'inert'` — bytes the model never decodes as instructions (e.g. a handle that is never\n * inlined into the prompt).\n * - `'extractable-instructions'` — text-bearing media: PDFs, screenshots with UI text, documents.\n * Hazard is OCR / embedded-text-layer reads.\n * - `'opaque-perceptual'` — raw vision/audio/video the model encodes directly. Hazard is\n * steganographic LSB prompts, adversarial perturbations, ultrasonic audio — invisible to any\n * pre-screen.\n *\n * See `/the-loop/trust-tiers/media` and its research sub-page `/the-loop/trust-tiers/media/research`.\n */\nexport const MediaModalityHazard = [\n 'inert',\n 'extractable-instructions',\n 'opaque-perceptual',\n] as const\nexport type MediaModalityHazard = (typeof MediaModalityHazard)[number]\n\n/**\n * Per-entry shape stored in a {@link Media}'s `stash` register.\n *\n * @remarks\n * Each entry carries its own trust tier so render code can route derived text (OCR, captions,\n * transcripts) through its own envelope independent of the parent media. How a battery or\n * middleware assigns those entry-level tiers is the implementor's call — the primitive contract\n * does not enforce a \"downgrade derived interpretation from possibly-adversarial bytes\" policy.\n */\nexport interface MediaStashEntry {\n /** The value of the entry — any serialisable shape the consumer wants to store. */\n value: unknown\n /** Trust tier for this specific entry; routed independently of the parent media. */\n trustTier: MediaTrustTier\n /** Optional pointer to the parent Media id this entry was derived from. */\n derivedFromMedia?: string\n}\n\n/**\n * Plain input object supplied to {@link Media} at construction time.\n *\n * @remarks\n * Validated against `rawMediaSchema` before the `Media` instance is created.\n */\nexport interface RawMedia {\n /**\n * Stable unique identifier for this media instance. Required for strict symmetry with\n * `Message.id` and `ToolCall.id`. When omitted, a fresh UUIDv6 is assigned at construction\n * time.\n */\n id?: string\n /** The media kind. See {@link MediaKind}. */\n kind: MediaKind\n /** The MIME type of the underlying bytes. */\n mimeType: string\n /** Filename used by providers that key on it (e.g. OpenAI `file.filename`). */\n filename: string\n /** Re-openable byte source. See {@link @nhtio/adk!MediaReader}. */\n reader: MediaReader\n /**\n * Trust tier declared at construction time. Required — there is NO default.\n * See {@link MediaTrustTier}.\n */\n trustTier: MediaTrustTier\n /**\n * Modality hazard declared at construction time. Required — there is NO default.\n * See {@link MediaModalityHazard}.\n */\n modalityHazard: MediaModalityHazard\n /** Optional provenance pointer (URL, tool name, etc.) for audit / events. */\n source?: string\n /**\n * Free-form per-instance metadata register. Middleware pipelines append to this — typically\n * with a text description, transcript, caption, or alt-text — so downstream code that cannot\n * consume the media natively has a model-readable fallback. No keys are reserved by the\n * framework. Defaults to `{}`.\n */\n stash?: Record<string, MediaStashEntry>\n}\n\nconst stashEntrySchema = validator\n .object<MediaStashEntry>({\n value: validator.any().required(),\n trustTier: validator\n .string()\n .valid(...MediaTrustTier)\n .required(),\n derivedFromMedia: validator.string().optional(),\n })\n .unknown(false)\n\n/**\n * Validator schema used to validate a {@link RawMedia} before constructing a {@link Media}.\n */\nconst rawMediaSchema = validator.object<RawMedia>({\n id: validator.string().optional(),\n kind: validator\n .string()\n .valid(...MediaKind)\n .required(),\n mimeType: validator.string().required(),\n filename: validator.string().required(),\n reader: mediaReaderSchema.required(),\n trustTier: validator\n .string()\n .valid(...MediaTrustTier)\n .required(),\n modalityHazard: validator\n .string()\n .valid(...MediaModalityHazard)\n .required(),\n source: validator.string().optional(),\n stash: validator.object().pattern(validator.string(), stashEntrySchema).optional(),\n})\n\ninterface ResolvedMedia {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n trustTier: MediaTrustTier\n modalityHazard: MediaModalityHazard\n source?: string\n stash?: Record<string, MediaStashEntry>\n}\n\nconst conservativeHazardForKind = (kind: MediaKind): MediaModalityHazard => {\n return kind === 'document' ? 'extractable-instructions' : 'opaque-perceptual'\n}\n\n/**\n * Shape returned by {@link Media.toJSON}. Metadata-only — bytes and the reader are stripped so\n * naive event/log serialisation never materialises bytes.\n */\n/** The plain-object, JSON-safe form of a {@link Media} produced by {@link Media.toJSON}. */\nexport interface SerializedMedia {\n /** Stable identifier for this media asset. */\n id: string\n /** High-level modality of the asset (e.g. image, audio, document). */\n kind: MediaKind\n /** MIME type of the underlying bytes (e.g. `image/png`). */\n mimeType: string\n /** Original or suggested file name for the asset. */\n filename: string\n /** Optional provenance string (URL, path, or other origin marker). */\n source?: string\n /** Trust tier governing how the asset's content is framed to the model. */\n trustTier: MediaTrustTier\n /** Whether the modality can carry hidden instructions (`extractable-instructions`) or is opaque-perceptual. */\n modalityHazard: MediaModalityHazard\n /** Adapter-scoped side-channel data keyed by name (e.g. provider upload handles). */\n stash: Record<string, MediaStashEntry>\n /** Size of the underlying bytes in bytes, when known. */\n byteLength?: number\n}\n\n/**\n * Lazy, re-openable view over a binary asset (image, audio, video, document).\n *\n * @remarks\n * Dual-peer to {@link @nhtio/adk!Tokenizable} (silo) and {@link @nhtio/adk!SpooledArtifact}\n * (handle). Wraps a {@link @nhtio/adk!MediaReader} contract — the framework owns the contract, the\n * implementor owns the storage backend. Bytes are reached only through the reader; the primitive\n * itself never inlines bytes.\n *\n * Construction requires `trustTier` and `modalityHazard` — the framework refuses to guess\n * provenance or decoding hazard. Ergonomic factories ({@link Media.userAttachment},\n * {@link Media.toolGenerated}, {@link Media.retrievedPublic}, {@link Media.retrievedPrivate})\n * force the labelling decision at the call site without becoming defaults on the bare\n * constructor.\n */\nexport class Media {\n /**\n * Validator schema that accepts a {@link RawMedia} object.\n */\n public static schema = rawMediaSchema\n\n /**\n * The set of recognised media kinds. Exposed for downstream schemas that need to discriminate\n * on `kind`.\n */\n public static MediaKind = MediaKind\n\n /**\n * The set of recognised trust tiers.\n */\n public static MediaTrustTier = MediaTrustTier\n\n /**\n * The set of recognised modality hazards.\n */\n public static MediaModalityHazard = MediaModalityHazard\n\n /**\n * Returns `true` if `value` is a {@link Media} 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 Media} instance.\n */\n public static isMedia(value: unknown): value is Media {\n return isInstanceOf(value, 'Media', Media)\n }\n\n /** Stable unique identifier. */\n declare readonly id: string\n /** Media kind. */\n declare readonly kind: MediaKind\n /** MIME type of the underlying bytes. */\n declare readonly mimeType: string\n /** Filename surfaced to providers that key on it. */\n declare readonly filename: string\n /** Optional provenance pointer. */\n declare readonly source: string | undefined\n /** Trust tier declared at construction time. */\n declare readonly trustTier: MediaTrustTier\n /** Modality hazard declared at construction time. */\n declare readonly modalityHazard: MediaModalityHazard\n /** Mutable per-instance metadata register; middleware pipelines append to this. */\n declare readonly stash: Registry\n\n #id: string\n #kind: MediaKind\n #mimeType: string\n #filename: string\n #source?: string\n #trustTier: MediaTrustTier\n #modalityHazard: MediaModalityHazard\n #reader: MediaReader\n #stash: Registry\n\n /**\n * @param raw - The raw media input validated against `rawMediaSchema`.\n * @throws {@link @nhtio/adk/exceptions!E_INVALID_INITIAL_MEDIA_VALUE} when `raw` does not satisfy the schema.\n * @throws {@link @nhtio/adk/exceptions!E_NOT_A_MEDIA_READER} when `raw.reader` does not implement {@link @nhtio/adk!MediaReader}.\n */\n constructor(raw: RawMedia) {\n let resolved: ResolvedMedia\n try {\n resolved = validateOrThrow<ResolvedMedia>(rawMediaSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_MEDIA_VALUE({ cause: isError(err) ? err : undefined })\n }\n if (!implementsMediaReader(resolved.reader)) {\n throw new E_NOT_A_MEDIA_READER()\n }\n this.#id = resolved.id ?? uuidv6()\n this.#kind = resolved.kind\n this.#mimeType = resolved.mimeType\n this.#filename = resolved.filename\n this.#source = resolved.source\n this.#trustTier = resolved.trustTier\n this.#modalityHazard = resolved.modalityHazard\n this.#reader = resolved.reader\n this.#stash = new Registry(resolved.stash as Record<string, unknown> | undefined)\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n kind: {\n get: () => this.#kind,\n enumerable: true,\n configurable: false,\n },\n mimeType: {\n get: () => this.#mimeType,\n enumerable: true,\n configurable: false,\n },\n filename: {\n get: () => this.#filename,\n enumerable: true,\n configurable: false,\n },\n source: {\n get: () => this.#source,\n enumerable: true,\n configurable: false,\n },\n trustTier: {\n get: () => this.#trustTier,\n enumerable: true,\n configurable: false,\n },\n modalityHazard: {\n get: () => this.#modalityHazard,\n enumerable: true,\n configurable: false,\n },\n stash: {\n get: () => this.#stash,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Re-opens the underlying byte source and returns a fresh ReadableStream.\n *\n * @returns A drainable `ReadableStream` over the underlying bytes.\n */\n async stream(): Promise<ReadableStream<Uint8Array>> {\n return this.#reader.stream()\n }\n\n /**\n * Returns the total number of bytes in the underlying data, or `undefined` if unknown.\n *\n * @returns The byte length, or `undefined` when the underlying source cannot report it.\n */\n async byteLength(): Promise<number | undefined> {\n return this.#reader.byteLength()\n }\n\n /**\n * Drains the reader's stream and returns the underlying bytes as a single `Uint8Array`.\n *\n * @remarks\n * Convenience for callers that need the full buffer (e.g. inline base64 encoding). Forces\n * full materialisation — large assets should be piped through {@link Media.stream} instead.\n */\n async asBytes(): Promise<Uint8Array> {\n const stream = await this.stream()\n const reader = stream.getReader()\n const chunks: Uint8Array[] = []\n let total = 0\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n if (value) {\n chunks.push(value)\n total += value.byteLength\n }\n }\n const out = new Uint8Array(total)\n let offset = 0\n for (const chunk of chunks) {\n out.set(chunk, offset)\n offset += chunk.byteLength\n }\n return out\n }\n\n /**\n * Drains the reader's stream and returns the underlying bytes as a base64 string.\n *\n * @remarks\n * Cross-environment: prefers Node's `Buffer.from(buf).toString('base64')` when available;\n * otherwise chunk-encodes through `btoa` with a 0x8000-byte window to avoid stack overflow\n * on large buffers.\n */\n async asBase64(): Promise<string> {\n const bytes = await this.asBytes()\n return encodeBase64(bytes)\n }\n\n /**\n * Returns the metadata-only serialisation of this Media. Bytes and the reader are stripped\n * so naive event/log serialisation never materialises bytes.\n *\n * @remarks\n * Implementations that have cheap, already-cached `byteLength` may opt to include it; this\n * default implementation omits it to preserve the \"lazy by default\" invariant. Consumers that\n * need byteLength on the serialised payload should call `await media.byteLength()` and merge\n * the result.\n */\n toJSON(): SerializedMedia {\n return {\n id: this.#id,\n kind: this.#kind,\n mimeType: this.#mimeType,\n filename: this.#filename,\n source: this.#source,\n trustTier: this.#trustTier,\n modalityHazard: this.#modalityHazard,\n stash: this.#stash.all() as Record<string, MediaStashEntry>,\n }\n }\n\n /**\n * Serialise this Media into an `@nhtio/encoder` snapshot — the **handle**, never the bytes.\n *\n * @remarks\n * Emits every metadata field plus the reader's {@link @nhtio/adk!ReaderDescriptor} (via its\n * `describe()` method). The bytes are not inlined: decode re-binds the reader from the descriptor\n * through a registered resolver. Throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} when the backing\n * reader cannot describe itself (e.g. a `fromWebFile` Blob reader) — there is no serialisable handle to\n * write, and silently dropping the reader would decode into a handle pointing at nothing.\n *\n * @returns A snapshot consumed by {@link Media.[DECODE_METHOD]} / the encoder.\n * @throws {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} when the reader has no `describe()`.\n */\n [ENCODE_METHOD](): AdkEncodableSnapshot {\n const descriptor = this.#reader.describe?.()\n if (!descriptor) {\n throw new E_READER_NOT_DESCRIBABLE(['reader'])\n }\n return {\n id: this.#id,\n kind: this.#kind,\n mimeType: this.#mimeType,\n filename: this.#filename,\n source: this.#source,\n trustTier: this.#trustTier,\n modalityHazard: this.#modalityHazard,\n stash: this.#stash.all(),\n reader: descriptor,\n }\n }\n\n /**\n * Reconstruct a {@link Media} from an {@link Media.[ENCODE_METHOD]} snapshot.\n *\n * @remarks\n * Re-binds the reader from the captured descriptor through the registered resolver\n * ({@link @nhtio/adk!resolveMediaReader}), then re-validates via the normal constructor. Throws\n * {@link @nhtio/adk!E_NO_READER_RESOLVER} when no resolver is registered for the descriptor's tag.\n *\n * @param data - The snapshot produced by {@link Media.[ENCODE_METHOD]}.\n * @returns A fully-validated {@link Media} backed by a freshly-resolved reader.\n */\n static [DECODE_METHOD](data: AdkEncodableSnapshot): Media {\n const snapshot = data as {\n id: string\n kind: MediaKind\n mimeType: string\n filename: string\n source?: string\n trustTier: MediaTrustTier\n modalityHazard: MediaModalityHazard\n stash?: Record<string, MediaStashEntry>\n reader: ReaderDescriptor\n }\n return new Media({\n id: snapshot.id,\n kind: snapshot.kind,\n mimeType: snapshot.mimeType,\n filename: snapshot.filename,\n source: snapshot.source,\n trustTier: snapshot.trustTier,\n modalityHazard: snapshot.modalityHazard,\n stash: snapshot.stash,\n reader: resolveMediaReader(snapshot.reader),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} representing a user-supplied attachment.\n *\n * @remarks\n * Pre-fills `trustTier: 'third-party-private'` and derives `modalityHazard` from `kind`\n * (`document` → `'extractable-instructions'`; everything else → `'opaque-perceptual'`).\n * Use the bare constructor when the conservative kind→hazard mapping is wrong for your case.\n */\n public static userAttachment(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'third-party-private',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} produced by a first-party tool.\n *\n * @remarks\n * Pre-fills `trustTier: 'first-party'` and derives `modalityHazard` from `kind`.\n */\n public static toolGenerated(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'first-party',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} retrieved from a public third-party source.\n *\n * @remarks\n * Pre-fills `trustTier: 'third-party-public'` and derives `modalityHazard` from `kind`.\n */\n public static retrievedPublic(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'third-party-public',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n\n /**\n * Factory: constructs a {@link Media} retrieved from a private third-party source.\n *\n * @remarks\n * Pre-fills `trustTier: 'third-party-private'` and derives `modalityHazard` from `kind`.\n */\n public static retrievedPrivate(args: {\n id?: string\n kind: MediaKind\n mimeType: string\n filename: string\n reader: MediaReader\n source?: string\n stash?: Record<string, MediaStashEntry>\n }): Media {\n return new Media({\n ...args,\n trustTier: 'third-party-private',\n modalityHazard: conservativeHazardForKind(args.kind),\n })\n }\n}\n\n/**\n * Returns `true` if `value` is a {@link Media} instance.\n *\n * @remarks\n * Module-level convenience alias for {@link Media.isMedia}. Uses {@link @nhtio/adk!isInstanceOf} for\n * cross-realm safety.\n */\nexport const isMedia = (value: unknown): value is Media => {\n return isInstanceOf(value, 'Media', Media)\n}\n","import { Media } from './media'\nimport { Tokenizable } from './tokenizable'\nimport { validator } from '@nhtio/validation'\nimport { SpooledArtifact } from './spooled_artifact'\nimport { validateOrThrow } from '../utils/validation'\nimport { isObject, isInstanceOf, isError } from '../utils/guards'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../utils/encoder_symbols'\nimport { E_INVALID_INITIAL_TOOL_CALL_VALUE } from '../exceptions/runtime'\nimport type { DateTime } from 'luxon'\nimport type { AdkEncodableSnapshot } from './encodable'\n\n/**\n * Union of every shape a {@link ToolCall.results} field may carry.\n *\n * @remarks\n * Three silos with distinct render-time semantics:\n *\n * - {@link @nhtio/adk!Tokenizable} — always singular. The {@link @nhtio/adk!ArtifactTool}\n * carve-out: a model-visible text answer that explicitly opts out of artifact wrapping to\n * break the recursive grep-on-the-grep-result loop.\n * - {@link @nhtio/adk!SpooledArtifact} or `SpooledArtifact[]` — bounded text output spooled to durable\n * storage. A single tool call may legitimately produce multiple artifacts (e.g. one tool\n * that returns N PR bodies). LLM adapters render either inline (full body in trust envelope)\n * or as a handle reference (forged artifact-query tools).\n * - {@link @nhtio/adk!Media} or `Media[]` — binary modality output (image, audio, video, document).\n * Adapters render as provider-specific content blocks (`image_url`, `input_audio`, `file`,\n * etc.). Bytes are lazy — reached only through {@link @nhtio/adk!Media.stream}.\n */\nexport type ToolCallResults = Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[]\n\nconst isToolCallResults = (value: unknown): value is ToolCallResults => {\n if (Tokenizable.isTokenizable(value)) return true\n if (SpooledArtifact.isSpooledArtifact(value)) return true\n if (Media.isMedia(value)) return true\n if (Array.isArray(value) && value.length > 0) {\n const allMedia = value.every((entry) => Media.isMedia(entry))\n if (allMedia) return true\n const allSpooled = value.every((entry) => SpooledArtifact.isSpooledArtifact(entry))\n if (allSpooled) return true\n }\n return false\n}\n\n/**\n * Plain input object supplied to {@link ToolCall} at construction time.\n *\n * @remarks\n * Validated against `rawToolCallSchema` before the `ToolCall` instance is created.\n * Temporal fields accept any value that Luxon can parse — ISO strings, Unix timestamps,\n * `Date` objects, or existing `DateTime` instances.\n */\nexport interface RawToolCall {\n /** Stable unique identifier for this tool call; correlates the request with its result. */\n id: string\n /** Name of the tool the model has requested. */\n tool: string\n /**\n * Arguments the model supplied for this tool call.\n *\n * @remarks\n * Accepts either a plain object or a JSON-encoded string that deserialises to an object.\n * Always exposed as a plain object on the constructed {@link ToolCall} instance.\n */\n args: string | Record<string, unknown>\n /** Integrity checksum over `tool` and `args`; can be used to detect tampering before execution. */\n checksum: string\n /** `true` once the tool call has finished (successfully or not). */\n isComplete: boolean\n /** `true` when the tool execution produced an error; inspect `results` for detail. */\n isError: boolean\n /**\n * Result returned by the tool, or error detail when `isError` is `true`.\n *\n * @remarks\n * Three silos with distinct render-time semantics — see {@link ToolCallResults}:\n *\n * - For a normal {@link @nhtio/adk!Tool} call whose handler returned `string` or\n * `Uint8Array`, this is a {@link @nhtio/adk!SpooledArtifact} (or one of its subclasses) wrapping the\n * spooled bytes. Tools that legitimately produce multiple bounded artifacts may return\n * a `SpooledArtifact[]`.\n * - For a `Tool` call whose handler returned a {@link @nhtio/adk!Media} or `Media[]`, this is the same\n * media handle(s) — the explicit-modality silo bypasses `SpooledArtifact` wrapping because\n * the bytes are binary and rendered as provider-specific content blocks, not text.\n * - For an {@link @nhtio/adk!ArtifactTool} call (a forged artifact-query tool),\n * this is a {@link @nhtio/adk!Tokenizable} holding the raw model-visible answer — `ArtifactTool`\n * explicitly opts out of wrapping to break the recursive grep-on-the-grep-result loop.\n *\n * The ADK sets {@link RawToolCall.fromArtifactTool} on calls produced by an\n * `ArtifactTool` so subsequent `forgeTools(ctx)` invocations can filter them out of the\n * `callId` enum.\n */\n results: ToolCallResults\n /**\n * Optional vendor-opaque payload that round-trips back to a matching model wire.\n *\n * @remarks\n * Carries provider metadata the ADK cannot interpret, such as Gemini's `thought_signature`\n * on a function call, GPT-OSS's commentary-channel tag, or other vendor-opaque metadata\n * that a provider needs echoed back.\n *\n * A present `payload` requires a present {@link RawToolCall.replayCompatibility} so the\n * matching adapter wire shape is known.\n *\n * @defaultValue `undefined`\n */\n payload?: unknown\n /**\n * Optional free-form identifier describing which adapter wire-shape this tool call can be\n * safely replayed into.\n *\n * @remarks\n * A `replayCompatibility` without a `payload` is allowed — it documents intent without\n * requiring an opaque blob.\n *\n * @defaultValue `undefined`\n */\n replayCompatibility?: string\n /**\n * `true` when this tool call originated from an {@link @nhtio/adk!ArtifactTool}\n * invocation. Defaults to `false`.\n *\n * @remarks\n * Set by the ADK's result-wrapping touch sites when `ArtifactTool.isArtifactTool(tool)`\n * holds. Read by `SpooledArtifact.forgeTools(ctx)` when building each descriptor's `callId`\n * enum — calls with this flag set are excluded so the model can't `artifact_grep` on a\n * previous `artifact_grep` result. Optional in the raw shape (defaults to `false`); always\n * defined on the constructed {@link ToolCall}.\n *\n * @defaultValue `false`\n */\n fromArtifactTool?: boolean\n /**\n * When `false` (the default), the adapter surfaces a {@link @nhtio/adk!SpooledArtifact} result as a\n * \"handle\" — a directions-bearing envelope that tells the model which forged artifact-query tools to\n * call against this `tc.id` to read the content incrementally, keeping the body OUT of the prompt.\n * When `true`, the adapter renders the result inline — the full stringified body wrapped in the\n * adapter's trust envelope and sent to the model as the `tool` role content.\n *\n * @remarks\n * Handle-by-default is the secure, budget-aligned posture: the LLM batteries already spool-wrap every\n * non-{@link @nhtio/adk!Media}, non-{@link @nhtio/adk!ArtifactTool} tool result into a `SpooledArtifact`,\n * so a result that could be arbitrarily large never lands in the next prompt just because nobody\n * touched a flag — the core ADK context-window-diet principle (see the Budgets / Artifacts docs).\n * Inlining is the OPT-IN: a producer that knows its output is small sets `inline: true` so the model\n * sees the body verbatim without a query round-trip.\n *\n * Policy is the producer's or middleware's call (LLM adapters obey the flag — they never size-check\n * the result or silently switch modes). Set per call at construction, or flip mid-turn via\n * `ctx.mutateToolCall(tc.id, { inline: true })`.\n *\n * Handles only make sense for `SpooledArtifact` (the only result kind the forged artifact-query tools\n * can read). For a {@link @nhtio/adk!Tokenizable} result (e.g. an `ArtifactTool` answer or an error\n * string) the flag is moot — the adapter renders it inline regardless, since there is no queryable\n * artifact to hand back.\n *\n * @defaultValue `false`\n */\n inline?: boolean\n /** When this tool call was first created. */\n createdAt: string | number | Date | DateTime\n /** When this tool call was last modified. */\n updatedAt: string | number | Date | DateTime\n /** When the tool call completed. */\n completedAt: string | number | Date | DateTime\n}\n\n/**\n * A fully-resolved {@link RawToolCall} where temporal fields have been normalised to Luxon\n * `DateTime` instances.\n *\n * @remarks\n * Used internally by the {@link ToolCall} constructor to assign private fields with\n * guaranteed types.\n */\ninterface ResolvedToolCall {\n id: string\n tool: string\n args: Record<string, unknown>\n checksum: string\n isComplete: boolean\n isError: boolean\n results: ToolCallResults\n payload?: unknown\n replayCompatibility?: string\n fromArtifactTool: boolean\n inline: boolean\n createdAt: DateTime\n updatedAt: DateTime\n completedAt: DateTime\n}\n\n/**\n * Validator schema used to validate a {@link RawToolCall} before constructing a {@link ToolCall}.\n *\n * @remarks\n * Validates all fields of {@link RawToolCall}:\n * - `id` — required non-empty string.\n * - `tool` — required non-empty string.\n * - `args` — required; either a plain object or a JSON string that deserialises to an object.\n * Strings are parsed and the resulting object is stored.\n * - `checksum` — required string.\n * - `isComplete` — required boolean.\n * - `isError` — required boolean.\n * - `results` — required; one of {@link @nhtio/adk!Tokenizable}, {@link @nhtio/adk!SpooledArtifact}, a non-empty\n * `SpooledArtifact[]`, {@link @nhtio/adk!Media}, or a non-empty `Media[]`. Arrays must be homogeneous.\n * - `createdAt` / `updatedAt` / `completedAt` — required datetime-parseable values, normalised to `DateTime`.\n *\n * Throws {@link @nhtio/adk!E_INVALID_INITIAL_TOOL_CALL_VALUE} (via the {@link ToolCall} constructor) when\n * validation fails.\n */\nconst rawToolCallSchema = validator\n .object<RawToolCall>({\n id: validator.string().required(),\n tool: validator.string().required(),\n args: validator\n .alternatives(\n validator.object().unknown(true),\n validator.string().custom((value, helpers) => {\n try {\n const parsed = JSON.parse(value)\n if (!isObject(parsed)) {\n return helpers.error('any.invalid')\n }\n return parsed\n } catch {\n return helpers.error('any.invalid')\n }\n })\n )\n .required(),\n checksum: validator.string().required(),\n isComplete: validator.boolean().required(),\n isError: validator.boolean().required(),\n results: validator\n .any()\n .custom((value, helpers) => {\n if (isToolCallResults(value)) {\n return value\n }\n return helpers.error('any.invalid')\n })\n .required(),\n payload: validator.any().optional(),\n replayCompatibility: validator.string().min(1).optional(),\n fromArtifactTool: validator.boolean().default(false),\n inline: validator.boolean().default(false),\n createdAt: validator.datetime().required(),\n updatedAt: validator.datetime().required(),\n completedAt: validator.datetime().required(),\n })\n .custom((value, helpers) => {\n const v = value as RawToolCall\n const hasPayload = v.payload !== undefined && v.payload !== null\n if (hasPayload && (v.replayCompatibility === undefined || v.replayCompatibility === null)) {\n return helpers.error('any.invalid')\n }\n return value\n })\n\n/**\n * An immutable, validated tool call record associated with a turn.\n *\n * @remarks\n * Represents a completed tool invocation from the conversation history — `results`,\n * `completedAt`, `isComplete`, and `isError` are all present and required.\n * Temporal fields are normalised to Luxon `DateTime` instances at construction time.\n */\nexport class ToolCall {\n /**\n * Validator schema that accepts a {@link RawToolCall} object.\n *\n * @remarks\n * Reusable fragment for any schema that needs to validate or nest a tool call entry.\n */\n public static schema = rawToolCallSchema\n\n /**\n * Returns `true` if `value` is a {@link ToolCall} instance.\n *\n * @remarks\n * Uses {@link @nhtio/adk!isInstanceOf} for cross-realm safety — `instanceof` would fail for instances\n * created in a different module copy or VM context.\n *\n * @param value - The value to test.\n * @returns `true` when `value` is a {@link ToolCall} instance.\n */\n public static isToolCall(value: unknown): value is ToolCall {\n return isInstanceOf(value, 'ToolCall', ToolCall)\n }\n\n /** Stable unique identifier for this tool call; correlates the request with its result. */\n declare readonly id: string\n /** Name of the tool the model has requested. */\n declare readonly tool: string\n /** Arguments the model supplied for this tool call, always as a plain object. */\n declare readonly args: Record<string, unknown>\n /** Integrity checksum over `tool` and `args`. */\n declare readonly checksum: string\n /** `true` once the tool call has finished (successfully or not). */\n declare readonly isComplete: boolean\n /** `true` when the tool execution produced an error; inspect `results` for detail. */\n declare readonly isError: boolean\n /**\n * Result returned by the tool, or error detail when `isError` is `true`.\n *\n * @remarks\n * One of three silos — see {@link ToolCallResults}. {@link @nhtio/adk!SpooledArtifact} or\n * `SpooledArtifact[]` for normal text-output {@link @nhtio/adk!Tool} calls;\n * {@link @nhtio/adk!Media} or `Media[]` for tool calls whose handler returned binary modality output;\n * {@link @nhtio/adk!Tokenizable} for {@link @nhtio/adk!ArtifactTool} calls\n * (see {@link ToolCall.fromArtifactTool}).\n */\n declare readonly results: ToolCallResults\n /**\n * Optional vendor-opaque payload that round-trips back to a matching model wire.\n * See {@link RawToolCall.payload}.\n */\n declare readonly payload: unknown\n /**\n * Optional wire-shape identifier describing which adapter can safely replay this tool call.\n * See {@link RawToolCall.replayCompatibility}.\n */\n declare readonly replayCompatibility: string | undefined\n /**\n * `true` when this tool call originated from an {@link @nhtio/adk!ArtifactTool}\n * invocation. Used by `SpooledArtifact.forgeTools(ctx)` to filter out forged-tool results from\n * the `callId` enum it builds.\n */\n declare readonly fromArtifactTool: boolean\n /**\n * `false` (default) instructs LLM adapters to surface a `SpooledArtifact` result as a handle\n * reference (body kept out of the prompt); `true` renders the result inline. See\n * {@link RawToolCall.inline}.\n */\n declare readonly inline: boolean\n /** When this tool call was first created. */\n declare readonly createdAt: DateTime\n /** When this tool call was last modified. */\n declare readonly updatedAt: DateTime\n /** When the tool call completed. */\n declare readonly completedAt: DateTime\n\n #id: string\n #tool: string\n #args: Record<string, unknown>\n #checksum: string\n #isComplete: boolean\n #isError: boolean\n #results: ToolCallResults\n #payload: unknown\n #replayCompatibility: string | undefined\n #fromArtifactTool: boolean\n #inline: boolean\n #createdAt: DateTime\n #updatedAt: DateTime\n #completedAt: DateTime\n\n /**\n * @param raw - The raw tool call input validated against `rawToolCallSchema`.\n * @throws {@link @nhtio/adk!E_INVALID_INITIAL_TOOL_CALL_VALUE} when `raw` does not satisfy the schema.\n */\n constructor(raw: RawToolCall) {\n let resolved: ResolvedToolCall\n try {\n resolved = validateOrThrow<ResolvedToolCall>(rawToolCallSchema, raw, true)\n } catch (err) {\n throw new E_INVALID_INITIAL_TOOL_CALL_VALUE({ cause: isError(err) ? err : undefined })\n }\n this.#id = resolved.id\n this.#tool = resolved.tool\n this.#args = resolved.args\n this.#checksum = resolved.checksum\n this.#isComplete = resolved.isComplete\n this.#isError = resolved.isError\n this.#results = resolved.results\n this.#payload = resolved.payload\n this.#replayCompatibility = resolved.replayCompatibility\n this.#fromArtifactTool = resolved.fromArtifactTool\n this.#inline = resolved.inline\n this.#createdAt = resolved.createdAt\n this.#updatedAt = resolved.updatedAt\n this.#completedAt = resolved.completedAt\n\n Object.defineProperties(this, {\n id: {\n get: () => this.#id,\n enumerable: true,\n configurable: false,\n },\n tool: {\n get: () => this.#tool,\n enumerable: true,\n configurable: false,\n },\n args: {\n get: () => this.#args,\n enumerable: true,\n configurable: false,\n },\n checksum: {\n get: () => this.#checksum,\n enumerable: true,\n configurable: false,\n },\n isComplete: {\n get: () => this.#isComplete,\n enumerable: true,\n configurable: false,\n },\n isError: {\n get: () => this.#isError,\n enumerable: true,\n configurable: false,\n },\n results: {\n get: () => this.#results,\n enumerable: true,\n configurable: false,\n },\n payload: {\n get: () => this.#payload,\n enumerable: true,\n configurable: false,\n },\n replayCompatibility: {\n get: () => this.#replayCompatibility,\n enumerable: true,\n configurable: false,\n },\n fromArtifactTool: {\n get: () => this.#fromArtifactTool,\n enumerable: true,\n configurable: false,\n },\n inline: {\n get: () => this.#inline,\n enumerable: true,\n configurable: false,\n },\n createdAt: {\n get: () => this.#createdAt,\n enumerable: true,\n configurable: false,\n },\n updatedAt: {\n get: () => this.#updatedAt,\n enumerable: true,\n configurable: false,\n },\n completedAt: {\n get: () => this.#completedAt,\n enumerable: true,\n configurable: false,\n },\n })\n }\n\n /**\n * Serialise this ToolCall into an `@nhtio/encoder` snapshot.\n *\n * @remarks\n * Emits a {@link RawToolCall}-shaped object. `results` is the live {@link ToolCallResults} union —\n * a {@link @nhtio/adk!Tokenizable}, {@link @nhtio/adk!SpooledArtifact}(s), or {@link @nhtio/adk!Media}(s) —\n * which the encoder recurses into; reader-backed results round-trip as handles (and throw\n * {@link @nhtio/adk!E_READER_NOT_DESCRIBABLE} if a backing reader cannot describe itself). The `args`\n * object and the producer-supplied `checksum` are emitted verbatim, so the constructor's\n * checksum re-validation passes on decode. Round-trips via {@link ToolCall.[DECODE_METHOD]}.\n *\n * @returns A {@link RawToolCall}-shaped snapshot.\n */\n [ENCODE_METHOD](): AdkEncodableSnapshot {\n return {\n id: this.#id,\n tool: this.#tool,\n args: this.#args,\n checksum: this.#checksum,\n isComplete: this.#isComplete,\n isError: this.#isError,\n results: this.#results,\n payload: this.#payload,\n replayCompatibility: this.#replayCompatibility,\n fromArtifactTool: this.#fromArtifactTool,\n inline: this.#inline,\n createdAt: this.#createdAt,\n updatedAt: this.#updatedAt,\n completedAt: this.#completedAt,\n }\n }\n\n /**\n * Reconstruct a {@link ToolCall} from a {@link ToolCall.[ENCODE_METHOD]} snapshot.\n *\n * @param data - The snapshot produced by {@link ToolCall.[ENCODE_METHOD]}.\n * @returns A fully-validated {@link ToolCall}.\n */\n static [DECODE_METHOD](data: AdkEncodableSnapshot): ToolCall {\n return new ToolCall(data as RawToolCall)\n }\n}\n"],"mappings":";;;;;;;AAiBA,IAAM,kBAA6C;CACjD,OAAQ,WAA0C;AACpD;;;;;;;;;;;;AAaA,IAAa,gBAAgB,UAA8B;CACzD,MAAM,SAAS,UAAU;CACzB,IAAI,UAAU,OAAO,OAAO,SAAS,YACnC,OAAO,OAAO,KAAK,KAAK,EAAE,SAAS,QAAQ;CAE7C,MAAM,YAAY;CAClB,IAAI,SAAS;CACb,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,WAAW;EAChD,MAAM,QAAQ,MAAM,SAAS,GAAG,IAAI,SAAS;EAC7C,UAAU,OAAO,aAAa,MAAM,MAAM,MAAM,KAAK,KAAK,CAAa;CACzE;CACA,OAAO,KAAK,MAAM;AACpB;;;;;;;;;;;AAYA,IAAa,gBAAgB,QAA4B;CACvD,MAAM,SAAS,UAAU;CACzB,IAAI,UAAU,OAAO,OAAO,SAAS,YAAY;EAC/C,MAAM,UAAU,OAAO,KAAK,KAAK,QAAQ;EAEzC,OAAO,IAAI,WAAW,OAAO;CAC/B;CACA,MAAM,SAAS,KAAK,GAAG;CACvB,MAAM,MAAM,IAAI,WAAW,OAAO,MAAM;CACxC,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KACjC,IAAI,KAAK,OAAO,WAAW,CAAC;CAE9B,OAAO;AACT;;;;;;;;;;;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