@nhtio/adk 1.20260924.0 → 1.20260928.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (317) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/artifact_methods-Cg0go7Q4.mjs +1 -0
  3. package/artifact_methods-CxeKTocm.cjs +1 -0
  4. package/batteries/artifacts/ecmascript.cjs +1 -1
  5. package/batteries/artifacts/ecmascript.mjs +1 -1
  6. package/batteries/artifacts/toon.cjs +1 -1
  7. package/batteries/artifacts/toon.mjs +1 -1
  8. package/batteries/artifacts/xml.cjs +1 -1
  9. package/batteries/artifacts/xml.mjs +1 -1
  10. package/batteries/artifacts/yaml.cjs +1 -1
  11. package/batteries/artifacts/yaml.mjs +1 -1
  12. package/batteries/artifacts.cjs +4 -4
  13. package/batteries/artifacts.mjs +4 -4
  14. package/batteries/dev-tools/forge.cjs +3 -3
  15. package/batteries/dev-tools/forge.mjs +3 -3
  16. package/batteries/dev-tools.cjs +3 -3
  17. package/batteries/dev-tools.mjs +3 -3
  18. package/batteries/encoding.cjs +7 -7
  19. package/batteries/encoding.mjs +7 -7
  20. package/batteries/generation/gemini/adapter.cjs +1 -1
  21. package/batteries/generation/gemini/adapter.mjs +1 -1
  22. package/batteries/generation/local_diffusion/adapter.cjs +1 -1
  23. package/batteries/generation/local_diffusion/adapter.mjs +1 -1
  24. package/batteries/generation/openai/adapter.cjs +1 -1
  25. package/batteries/generation/openai/adapter.mjs +1 -1
  26. package/batteries/llm/anthropic_messages/adapter.cjs +6 -6
  27. package/batteries/llm/anthropic_messages/adapter.mjs +6 -6
  28. package/batteries/llm/anthropic_messages/count_tokens.cjs +1 -1
  29. package/batteries/llm/anthropic_messages/count_tokens.mjs +1 -1
  30. package/batteries/llm/anthropic_messages/helpers.cjs +3 -3
  31. package/batteries/llm/anthropic_messages/helpers.mjs +3 -3
  32. package/batteries/llm/anthropic_messages/validation.cjs +2 -2
  33. package/batteries/llm/anthropic_messages/validation.mjs +2 -2
  34. package/batteries/llm/anthropic_messages.cjs +2 -2
  35. package/batteries/llm/anthropic_messages.mjs +2 -2
  36. package/batteries/llm/bedrock_converse/adapter.cjs +162 -21
  37. package/batteries/llm/bedrock_converse/adapter.cjs.map +1 -1
  38. package/batteries/llm/bedrock_converse/adapter.mjs +162 -21
  39. package/batteries/llm/bedrock_converse/adapter.mjs.map +1 -1
  40. package/batteries/llm/bedrock_converse/helpers.cjs +1 -1
  41. package/batteries/llm/bedrock_converse/helpers.mjs +1 -1
  42. package/batteries/llm/bedrock_converse/validation.cjs +2 -2
  43. package/batteries/llm/bedrock_converse/validation.mjs +2 -2
  44. package/batteries/llm/bedrock_converse.cjs +2 -2
  45. package/batteries/llm/bedrock_converse.mjs +2 -2
  46. package/batteries/llm/claude_code_cli/adapter.cjs +66 -25
  47. package/batteries/llm/claude_code_cli/adapter.cjs.map +1 -1
  48. package/batteries/llm/claude_code_cli/adapter.mjs +66 -25
  49. package/batteries/llm/claude_code_cli/adapter.mjs.map +1 -1
  50. package/batteries/llm/claude_code_cli/helpers.cjs +3 -3
  51. package/batteries/llm/claude_code_cli/helpers.mjs +3 -3
  52. package/batteries/llm/claude_code_cli/line_queue.d.ts +39 -0
  53. package/batteries/llm/claude_code_cli/message_id_state.d.ts +48 -0
  54. package/batteries/llm/claude_code_cli/types.d.ts +76 -0
  55. package/batteries/llm/claude_code_cli/validation.cjs +5 -2
  56. package/batteries/llm/claude_code_cli/validation.cjs.map +1 -1
  57. package/batteries/llm/claude_code_cli/validation.mjs +5 -2
  58. package/batteries/llm/claude_code_cli/validation.mjs.map +1 -1
  59. package/batteries/llm/claude_code_cli/wire.cjs.map +1 -1
  60. package/batteries/llm/claude_code_cli/wire.d.ts +45 -1
  61. package/batteries/llm/claude_code_cli/wire.mjs.map +1 -1
  62. package/batteries/llm/claude_code_cli/wrapper.d.ts +5 -4
  63. package/batteries/llm/claude_code_cli.cjs +2 -2
  64. package/batteries/llm/claude_code_cli.mjs +2 -2
  65. package/batteries/llm/gemini_generate_content/adapter.cjs +160 -19
  66. package/batteries/llm/gemini_generate_content/adapter.cjs.map +1 -1
  67. package/batteries/llm/gemini_generate_content/adapter.mjs +160 -19
  68. package/batteries/llm/gemini_generate_content/adapter.mjs.map +1 -1
  69. package/batteries/llm/gemini_generate_content/helpers.cjs +1 -1
  70. package/batteries/llm/gemini_generate_content/helpers.mjs +1 -1
  71. package/batteries/llm/gemini_generate_content/validation.cjs +2 -2
  72. package/batteries/llm/gemini_generate_content/validation.mjs +2 -2
  73. package/batteries/llm/gemini_generate_content.cjs +1 -1
  74. package/batteries/llm/gemini_generate_content.mjs +1 -1
  75. package/batteries/llm/litert_lm/adapter.cjs +6 -6
  76. package/batteries/llm/litert_lm/adapter.mjs +6 -6
  77. package/batteries/llm/litert_lm/helpers.cjs +3 -3
  78. package/batteries/llm/litert_lm/helpers.mjs +3 -3
  79. package/batteries/llm/litert_lm/validation.cjs +2 -2
  80. package/batteries/llm/litert_lm/validation.mjs +2 -2
  81. package/batteries/llm/litert_lm.cjs +1 -1
  82. package/batteries/llm/litert_lm.mjs +1 -1
  83. package/batteries/llm/ollama/adapter.cjs +6 -6
  84. package/batteries/llm/ollama/adapter.mjs +6 -6
  85. package/batteries/llm/ollama/helpers.cjs +4 -4
  86. package/batteries/llm/ollama/helpers.mjs +4 -4
  87. package/batteries/llm/ollama/validation.cjs +2 -2
  88. package/batteries/llm/ollama/validation.mjs +2 -2
  89. package/batteries/llm/ollama.cjs +2 -2
  90. package/batteries/llm/ollama.mjs +2 -2
  91. package/batteries/llm/openai_chat_completions/adapter.cjs +6 -6
  92. package/batteries/llm/openai_chat_completions/adapter.mjs +6 -6
  93. package/batteries/llm/openai_chat_completions/helpers.cjs +4 -4
  94. package/batteries/llm/openai_chat_completions/helpers.mjs +4 -4
  95. package/batteries/llm/openai_chat_completions/validation.cjs +2 -2
  96. package/batteries/llm/openai_chat_completions/validation.mjs +2 -2
  97. package/batteries/llm/openai_chat_completions.cjs +2 -2
  98. package/batteries/llm/openai_chat_completions.mjs +2 -2
  99. package/batteries/llm/openai_responses/adapter.cjs +6 -6
  100. package/batteries/llm/openai_responses/adapter.mjs +6 -6
  101. package/batteries/llm/openai_responses/helpers.cjs +3 -3
  102. package/batteries/llm/openai_responses/helpers.mjs +3 -3
  103. package/batteries/llm/openai_responses/validation.cjs +2 -2
  104. package/batteries/llm/openai_responses/validation.mjs +2 -2
  105. package/batteries/llm/openai_responses.cjs +2 -2
  106. package/batteries/llm/openai_responses.mjs +2 -2
  107. package/batteries/llm/transformers_js/adapter.cjs +6 -6
  108. package/batteries/llm/transformers_js/adapter.mjs +6 -6
  109. package/batteries/llm/transformers_js/helpers.cjs +3 -3
  110. package/batteries/llm/transformers_js/helpers.mjs +3 -3
  111. package/batteries/llm/transformers_js/validation.cjs +2 -2
  112. package/batteries/llm/transformers_js/validation.mjs +2 -2
  113. package/batteries/llm/transformers_js.cjs +1 -1
  114. package/batteries/llm/transformers_js.mjs +1 -1
  115. package/batteries/llm/webllm_chat_completions/adapter.cjs +6 -6
  116. package/batteries/llm/webllm_chat_completions/adapter.mjs +6 -6
  117. package/batteries/llm/webllm_chat_completions/helpers.cjs +1 -1
  118. package/batteries/llm/webllm_chat_completions/helpers.mjs +1 -1
  119. package/batteries/llm/webllm_chat_completions/validation.cjs +2 -2
  120. package/batteries/llm/webllm_chat_completions/validation.mjs +2 -2
  121. package/batteries/llm/webllm_chat_completions.cjs +2 -2
  122. package/batteries/llm/webllm_chat_completions.mjs +2 -2
  123. package/batteries/llm.cjs +2 -2
  124. package/batteries/llm.mjs +2 -2
  125. package/batteries/media/forge.cjs +4 -4
  126. package/batteries/media/forge.mjs +4 -4
  127. package/batteries/media/lint.cjs +1 -1
  128. package/batteries/media/lint.mjs +1 -1
  129. package/batteries/orchestration/dispatch_reasoner.cjs +4 -4
  130. package/batteries/orchestration/dispatch_reasoner.mjs +4 -4
  131. package/batteries/orchestration/executor.cjs +2 -2
  132. package/batteries/orchestration/executor.mjs +2 -2
  133. package/batteries/orchestration/forge.cjs +4 -4
  134. package/batteries/orchestration/forge.mjs +4 -4
  135. package/batteries/orchestration/validation.cjs +2 -2
  136. package/batteries/orchestration/validation.mjs +2 -2
  137. package/batteries/orchestration.cjs +4 -4
  138. package/batteries/orchestration.mjs +4 -4
  139. package/batteries/sandbox/js.cjs +1 -1
  140. package/batteries/sandbox/js.mjs +1 -1
  141. package/batteries/sandbox/tools.cjs +1 -1
  142. package/batteries/sandbox/tools.mjs +1 -1
  143. package/batteries/sandbox.cjs +3 -3
  144. package/batteries/sandbox.mjs +3 -3
  145. package/batteries/skills.cjs +9 -9
  146. package/batteries/skills.mjs +9 -9
  147. package/batteries/tools/_shared.cjs +1 -1
  148. package/batteries/tools/_shared.mjs +1 -1
  149. package/batteries/tools/color.cjs +2 -2
  150. package/batteries/tools/color.mjs +2 -2
  151. package/batteries/tools/comparison.cjs +2 -2
  152. package/batteries/tools/comparison.mjs +2 -2
  153. package/batteries/tools/data_structure.cjs +2 -2
  154. package/batteries/tools/data_structure.mjs +2 -2
  155. package/batteries/tools/datetime_extended.cjs +3 -3
  156. package/batteries/tools/datetime_extended.mjs +3 -3
  157. package/batteries/tools/datetime_math.cjs +3 -3
  158. package/batteries/tools/datetime_math.mjs +3 -3
  159. package/batteries/tools/encoding.cjs +2 -2
  160. package/batteries/tools/encoding.mjs +2 -2
  161. package/batteries/tools/formatting.cjs +2 -2
  162. package/batteries/tools/formatting.mjs +2 -2
  163. package/batteries/tools/geo_basics.cjs +2 -2
  164. package/batteries/tools/geo_basics.mjs +2 -2
  165. package/batteries/tools/math.cjs +2 -2
  166. package/batteries/tools/math.mjs +2 -2
  167. package/batteries/tools/memory.cjs +5 -5
  168. package/batteries/tools/memory.mjs +5 -5
  169. package/batteries/tools/parsing.cjs +3 -3
  170. package/batteries/tools/parsing.mjs +3 -3
  171. package/batteries/tools/retrievables.cjs +5 -5
  172. package/batteries/tools/retrievables.mjs +5 -5
  173. package/batteries/tools/scrapper.cjs +1 -1
  174. package/batteries/tools/scrapper.mjs +1 -1
  175. package/batteries/tools/searxng.cjs +1 -1
  176. package/batteries/tools/searxng.mjs +1 -1
  177. package/batteries/tools/standing_instructions.cjs +3 -3
  178. package/batteries/tools/standing_instructions.mjs +3 -3
  179. package/batteries/tools/statistics.cjs +3 -3
  180. package/batteries/tools/statistics.mjs +3 -3
  181. package/batteries/tools/string_processing.cjs +2 -2
  182. package/batteries/tools/string_processing.mjs +2 -2
  183. package/batteries/tools/structured_data.cjs +2 -2
  184. package/batteries/tools/structured_data.mjs +2 -2
  185. package/batteries/tools/text_analysis.cjs +3 -3
  186. package/batteries/tools/text_analysis.mjs +3 -3
  187. package/batteries/tools/text_comparison.cjs +2 -2
  188. package/batteries/tools/text_comparison.mjs +2 -2
  189. package/batteries/tools/time.cjs +3 -3
  190. package/batteries/tools/time.mjs +3 -3
  191. package/batteries/tools/unit_conversion.cjs +2 -2
  192. package/batteries/tools/unit_conversion.mjs +2 -2
  193. package/batteries/tools.cjs +2 -2
  194. package/batteries/tools.mjs +2 -2
  195. package/batteries/validation.cjs +4 -4
  196. package/batteries/validation.mjs +4 -4
  197. package/batteries/vector/conformance.cjs +59 -0
  198. package/batteries/vector/conformance.cjs.map +1 -1
  199. package/batteries/vector/conformance.mjs +59 -0
  200. package/batteries/vector/conformance.mjs.map +1 -1
  201. package/batteries/vector/lancedb.cjs +1 -1
  202. package/batteries/vector/lancedb.cjs.map +1 -1
  203. package/batteries/vector/lancedb.mjs +1 -1
  204. package/batteries/vector/lancedb.mjs.map +1 -1
  205. package/batteries/vector/retrievable.cjs +1 -1
  206. package/batteries/vector/retrievable.mjs +1 -1
  207. package/batteries/vector/sqlite_vec/index.d.ts +1 -1
  208. package/batteries/vector/sqlite_vec.cjs +19 -30
  209. package/batteries/vector/sqlite_vec.cjs.map +1 -1
  210. package/batteries/vector/sqlite_vec.mjs +20 -31
  211. package/batteries/vector/sqlite_vec.mjs.map +1 -1
  212. package/batteries.cjs +4 -4
  213. package/batteries.mjs +4 -4
  214. package/{chat_common-B7fvGTKv.cjs → chat_common-CNayzS1V.cjs} +2 -2
  215. package/{chat_common-B7fvGTKv.cjs.map → chat_common-CNayzS1V.cjs.map} +1 -1
  216. package/{chat_common-CeoHwSsz.mjs → chat_common-DKw8FDol.mjs} +2 -2
  217. package/{chat_common-CeoHwSsz.mjs.map → chat_common-DKw8FDol.mjs.map} +1 -1
  218. package/claude-code-cli-wrapper.cjs +104 -22
  219. package/claude-code-cli-wrapper.cjs.map +1 -1
  220. package/claude-code-cli-wrapper.mjs +104 -22
  221. package/claude-code-cli-wrapper.mjs.map +1 -1
  222. package/{common-7gCR3zQu.cjs → common-CqetsItm.cjs} +7 -7
  223. package/{common-7gCR3zQu.cjs.map → common-CqetsItm.cjs.map} +1 -1
  224. package/{common-B5maOoF_.mjs → common-oI1niK9Z.mjs} +7 -7
  225. package/{common-B5maOoF_.mjs.map → common-oI1niK9Z.mjs.map} +1 -1
  226. package/common.cjs +7 -7
  227. package/common.mjs +7 -7
  228. package/{dispatch_runner-DO7jo_gl.mjs → dispatch_runner-BZDXUe0G.mjs} +5 -5
  229. package/{dispatch_runner-DO7jo_gl.mjs.map → dispatch_runner-BZDXUe0G.mjs.map} +1 -1
  230. package/{dispatch_runner-FlriTyoq.cjs → dispatch_runner-DDUxXJC3.cjs} +5 -5
  231. package/{dispatch_runner-FlriTyoq.cjs.map → dispatch_runner-DDUxXJC3.cjs.map} +1 -1
  232. package/dispatch_runner.cjs +1 -1
  233. package/dispatch_runner.mjs +1 -1
  234. package/{ecmascript-bgwVyZG1.mjs → ecmascript-B9Z2C24U.mjs} +3 -3
  235. package/{ecmascript-bgwVyZG1.mjs.map → ecmascript-B9Z2C24U.mjs.map} +1 -1
  236. package/{ecmascript-BydSB03Y.cjs → ecmascript-BYfmjg7y.cjs} +3 -3
  237. package/{ecmascript-BydSB03Y.cjs.map → ecmascript-BYfmjg7y.cjs.map} +1 -1
  238. package/eslint/rules.cjs +1 -1
  239. package/eslint/rules.mjs +1 -1
  240. package/eslint.cjs +2 -2
  241. package/eslint.mjs +2 -2
  242. package/exceptions.cjs +1 -1
  243. package/exceptions.mjs +1 -1
  244. package/forge.cjs +2 -2
  245. package/forge.mjs +2 -2
  246. package/guards.cjs +7 -7
  247. package/guards.mjs +7 -7
  248. package/{helpers-Dcp4CrOz.cjs → helpers-DPlh_7Bn.cjs} +3 -3
  249. package/{helpers-Dcp4CrOz.cjs.map → helpers-DPlh_7Bn.cjs.map} +1 -1
  250. package/{helpers-C1T0DV8Q.mjs → helpers-mbn_EsDV.mjs} +3 -3
  251. package/{helpers-C1T0DV8Q.mjs.map → helpers-mbn_EsDV.mjs.map} +1 -1
  252. package/index.cjs +11 -11
  253. package/index.mjs +11 -11
  254. package/mcp/adk-docs-corpus.json +2 -2
  255. package/package.json +425 -425
  256. package/{retrievable-BBwiACtw.cjs → retrievable-Bq-O3k6r.cjs} +3 -3
  257. package/{retrievable-BBwiACtw.cjs.map → retrievable-Bq-O3k6r.cjs.map} +1 -1
  258. package/{retrievable-CrGKx4sc.mjs → retrievable-CXTAUuuv.mjs} +3 -3
  259. package/{retrievable-CrGKx4sc.mjs.map → retrievable-CXTAUuuv.mjs.map} +1 -1
  260. package/{scrapper-BibKj8qE.cjs → scrapper-B8xG9lTD.cjs} +4 -4
  261. package/{scrapper-BibKj8qE.cjs.map → scrapper-B8xG9lTD.cjs.map} +1 -1
  262. package/{scrapper-_JzgbLG5.mjs → scrapper-DiQ5FfDL.mjs} +4 -4
  263. package/{scrapper-_JzgbLG5.mjs.map → scrapper-DiQ5FfDL.mjs.map} +1 -1
  264. package/{searxng-D-nA2gEI.mjs → searxng-BFTJ6rTE.mjs} +4 -4
  265. package/{searxng-D-nA2gEI.mjs.map → searxng-BFTJ6rTE.mjs.map} +1 -1
  266. package/{searxng-C6xrLW-v.cjs → searxng-EJhWRnIE.cjs} +4 -4
  267. package/{searxng-C6xrLW-v.cjs.map → searxng-EJhWRnIE.cjs.map} +1 -1
  268. package/server.json +2 -2
  269. package/skills/adk-assembly/SKILL.md +2 -2
  270. package/{spooled_artifact-BLgbGT8b.cjs → spooled_artifact---DmicFW.cjs} +384 -384
  271. package/spooled_artifact---DmicFW.cjs.map +1 -0
  272. package/{spooled_artifact-BkOe4-j-.mjs → spooled_artifact-Bw_7swIp.mjs} +385 -385
  273. package/spooled_artifact-Bw_7swIp.mjs.map +1 -0
  274. package/spooled_artifact.cjs +2 -2
  275. package/spooled_artifact.mjs +2 -2
  276. package/{spooled_markdown_artifact-8zdejfcJ.cjs → spooled_markdown_artifact-Rjzj-kyh.cjs} +3 -3
  277. package/{spooled_markdown_artifact-8zdejfcJ.cjs.map → spooled_markdown_artifact-Rjzj-kyh.cjs.map} +1 -1
  278. package/{spooled_markdown_artifact-Dnl-lCGv.mjs → spooled_markdown_artifact-vd6eNtIP.mjs} +3 -3
  279. package/{spooled_markdown_artifact-Dnl-lCGv.mjs.map → spooled_markdown_artifact-vd6eNtIP.mjs.map} +1 -1
  280. package/{thought-BrQt6HAb.mjs → thought-CxSaF6Xf.mjs} +3 -3
  281. package/{thought-BrQt6HAb.mjs.map → thought-CxSaF6Xf.mjs.map} +1 -1
  282. package/{thought-COeZTQ-B.cjs → thought-Dp3sMWW6.cjs} +3 -3
  283. package/{thought-COeZTQ-B.cjs.map → thought-Dp3sMWW6.cjs.map} +1 -1
  284. package/{tokenizable-DDIdXbJN.cjs → tokenizable-BcodRtoW.cjs} +29 -29
  285. package/{tokenizable-DDIdXbJN.cjs.map → tokenizable-BcodRtoW.cjs.map} +1 -1
  286. package/{tokenizable-xPXj1AQX.mjs → tokenizable-VB4Av8GF.mjs} +30 -30
  287. package/{tokenizable-xPXj1AQX.mjs.map → tokenizable-VB4Av8GF.mjs.map} +1 -1
  288. package/{tool_call-JbjeUpRK.cjs → tool_call-B9px4W9k.cjs} +4 -4
  289. package/{tool_call-JbjeUpRK.cjs.map → tool_call-B9px4W9k.cjs.map} +1 -1
  290. package/{tool_call-8crmZsO8.mjs → tool_call-Cfaj-6zK.mjs} +4 -4
  291. package/{tool_call-8crmZsO8.mjs.map → tool_call-Cfaj-6zK.mjs.map} +1 -1
  292. package/{tools-BC4NJqZD.mjs → tools-D0MBDh2R.mjs} +6 -6
  293. package/{tools-BC4NJqZD.mjs.map → tools-D0MBDh2R.mjs.map} +1 -1
  294. package/{tools-D4mdzi0a.cjs → tools-aNbi6JyA.cjs} +6 -6
  295. package/{tools-D4mdzi0a.cjs.map → tools-aNbi6JyA.cjs.map} +1 -1
  296. package/{toon-BA9Q7NHG.mjs → toon-BSTQnHed.mjs} +5 -5
  297. package/{toon-BA9Q7NHG.mjs.map → toon-BSTQnHed.mjs.map} +1 -1
  298. package/{toon-b-0pFKZ8.cjs → toon-DmLwZ6H1.cjs} +5 -5
  299. package/{toon-b-0pFKZ8.cjs.map → toon-DmLwZ6H1.cjs.map} +1 -1
  300. package/{turn_runner-BmVXcBZ2.mjs → turn_runner-BHHD6h77.mjs} +5 -5
  301. package/{turn_runner-BmVXcBZ2.mjs.map → turn_runner-BHHD6h77.mjs.map} +1 -1
  302. package/{turn_runner-DX-3s3ih.cjs → turn_runner-Dj7JsUTQ.cjs} +5 -5
  303. package/{turn_runner-DX-3s3ih.cjs.map → turn_runner-Dj7JsUTQ.cjs.map} +1 -1
  304. package/turn_runner.cjs +1 -1
  305. package/turn_runner.mjs +1 -1
  306. package/{xml-B1JIGLpU.mjs → xml-CYseDztH.mjs} +5 -5
  307. package/{xml-B1JIGLpU.mjs.map → xml-CYseDztH.mjs.map} +1 -1
  308. package/{xml-fvwTsoRv.cjs → xml-zJul8jMQ.cjs} +5 -5
  309. package/{xml-fvwTsoRv.cjs.map → xml-zJul8jMQ.cjs.map} +1 -1
  310. package/{yaml-1mP4uxdf.mjs → yaml-BPBoiOjx.mjs} +5 -5
  311. package/{yaml-1mP4uxdf.mjs.map → yaml-BPBoiOjx.mjs.map} +1 -1
  312. package/{yaml-DPUTumla.cjs → yaml-D0PzoRAr.cjs} +5 -5
  313. package/{yaml-DPUTumla.cjs.map → yaml-D0PzoRAr.cjs.map} +1 -1
  314. package/artifact_methods-7KatxCSd.cjs +0 -1
  315. package/artifact_methods-q52ETLwI.mjs +0 -1
  316. package/spooled_artifact-BLgbGT8b.cjs.map +0 -1
  317. package/spooled_artifact-BkOe4-j-.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"tokenizable-xPXj1AQX.mjs","names":["#evaluator","#value","#cache","#ctxCache"],"sources":["../src/lib/exceptions/runtime.ts","../src/lib/utils/encoder_symbols.ts","../src/lib/utils/estimation_context.ts","../src/lib/classes/tokenizable.ts"],"sourcesContent":["import { createException } from '../utils/exceptions'\n\n/**\n * Thrown by {@link @nhtio/adk!TurnRunner} when the supplied config object fails schema validation at\n * construction time.\n *\n * @remarks\n * Marked fatal — a misconfigured runner must not be allowed to execute turns.\n *\n * The single printf argument carries the validator's field-level detail (e.g.\n * `\"storeMediaBytesCallback is required\"`) so a misconfiguration names the offending field\n * instead of failing opaquely. The underlying `ValidationError` is also attached on `cause`.\n *\n * @group Turn Runner Construction\n */\nexport const E_INVALID_TURN_RUNNER_CONFIG = createException<[string]>(\n 'E_INVALID_TURN_RUNNER_CONFIG',\n 'The turn runner cannot be instantiated with the provided configuration: %s',\n 'E_INVALID_TURN_RUNNER_CONFIG',\n 529,\n true\n)\n\n/**\n * Thrown by {@link @nhtio/adk!TurnRunner} when the {@link @nhtio/adk!TurnContext} supplied to `run` fails schema\n * validation.\n *\n * @remarks\n * Marked fatal — an invalid context indicates a programming error in the caller, not a\n * recoverable runtime condition. Thrown synchronously out of `run()` before `turnStart` is\n * emitted.\n *\n * @group Turn Input Validation\n */\nexport const E_INVALID_TURN_CONTEXT = createException(\n 'E_INVALID_TURN_CONTEXT',\n 'The turn runner received an invalid context object.',\n 'E_INVALID_TURN_CONTEXT',\n 529,\n true\n)\n\n/**\n * Emitted (via the `error` event) when a non-abort error propagates out of the input\n * middleware pipeline during {@link @nhtio/adk!TurnRunner.run}.\n *\n * @remarks\n * Not fatal — the turn runner emits this on the `error` event rather than throwing, so\n * registered listeners can handle or log the failure without crashing the pipeline. Dispatch\n * and output middleware are skipped; `turnEnd` still fires.\n *\n * @group Pipelines\n */\nexport const E_INPUT_PIPELINE_ERROR = createException(\n 'E_INPUT_PIPELINE_ERROR',\n 'An error occurred in the input pipeline.',\n 'E_INPUT_PIPELINE_ERROR',\n 500,\n false\n)\n\n/**\n * Emitted (via the `error` event) when a non-abort error propagates out of the output\n * middleware pipeline during {@link @nhtio/adk!TurnRunner.run}.\n *\n * @remarks\n * Not fatal — the turn runner emits this on the `error` event rather than throwing, so\n * registered listeners can handle or log the failure without crashing the pipeline. `turnEnd`\n * still fires.\n *\n * @group Pipelines\n */\nexport const E_OUTPUT_PIPELINE_ERROR = createException(\n 'E_OUTPUT_PIPELINE_ERROR',\n 'An error occurred in the output pipeline.',\n 'E_OUTPUT_PIPELINE_ERROR',\n 500,\n false\n)\n\n/**\n * Emitted (via the `error` event) when a middleware pipeline resolves without reaching its\n * terminal handler and without the turn being aborted. Indicates that some middleware\n * returned without calling `next` and without signalling a deliberate refusal via the turn's\n * abort controller.\n *\n * @remarks\n * Not fatal — the runner emits this on the `error` event so the failure is observable, then\n * proceeds to short-circuit the remainder of the turn the same way any other pipeline error\n * would. The constructor takes a single positional argument identifying the pipeline that\n * short-circuited: one of `'turn-input'`, `'turn-output'`, `'dispatch-input'`, or `'dispatch-output'`.\n *\n * Deliberate refusals should call `ctx.abort(reason)`, which sets the `'aborted'` outcome\n * instead of emitting this error.\n *\n * @warning\n * This is a **detection condition**, not a thrown exception. The runner constructs and emits\n * the code itself when it detects a missing `next()` on the unwind — nothing in user code\n * throws it. Upstream post-steps still run normally.\n *\n * @example\n * ```ts\n * throw new E_PIPELINE_SHORT_CIRCUITED(['turn-input'])\n * ```\n *\n * @group Pipelines\n */\nexport const E_PIPELINE_SHORT_CIRCUITED = createException<[string]>(\n 'E_PIPELINE_SHORT_CIRCUITED',\n \"The '%s' middleware pipeline short-circuited without calling next or aborting the turn.\",\n 'E_PIPELINE_SHORT_CIRCUITED',\n 500,\n false\n)\n\n/**\n * Thrown when a registry is initialised with a value that is defined but not a plain object.\n *\n * @remarks\n * Registries expect either `undefined` (empty start) or a plain object as their initial value.\n * Passing a primitive, array, class instance, or other non-object signals a programming error\n * in the caller.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_REGISTRY_VALUE = createException(\n 'E_INVALID_INITIAL_REGISTRY_VALUE',\n 'Attempted to initialize a registry with a defined non-object value.',\n 'E_INVALID_INITIAL_REGISTRY_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Memory} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Memory` requires all fields — `id`, `content`, `confidence`, `importance`, `createdAt`,\n * `updatedAt` — to be present and of the correct type. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_MEMORY_VALUE = createException(\n 'E_INVALID_INITIAL_MEMORY_VALUE',\n 'Attempted to initialize a memory with an invalid value.',\n 'E_INVALID_INITIAL_MEMORY_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a tool call and retrievable eligible for artifact forging share an id.\n */\nexport const E_ARTIFACT_ID_COLLISION = createException<[string]>(\n 'E_ARTIFACT_ID_COLLISION',\n 'Artifact id collision: the tool call and retrievable with id \"%s\" both identify eligible artifacts.',\n 'E_ARTIFACT_ID_COLLISION',\n 409,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Retrievable} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Retrievable` requires `id`, `content`, `trustTier`, `createdAt`, and `updatedAt` to be present\n * and of the correct type, and `trustTier` must be one of `'first-party'`, `'third-party-public'`,\n * or `'third-party-private'`. The `trustTier` decision must be made consciously by the retrieval\n * middleware at construction time — there is no default. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_RETRIEVABLE_VALUE = createException(\n 'E_INVALID_INITIAL_RETRIEVABLE_VALUE',\n 'Invalid initial value supplied to Retrievable constructor.',\n 'E_INVALID_INITIAL_RETRIEVABLE_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Message} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Message` requires `id`, `role` (`user` or `assistant`), `content`, `createdAt`, and\n * `updatedAt` to be present and of the correct type. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_MESSAGE_VALUE = createException(\n 'E_INVALID_INITIAL_MESSAGE_VALUE',\n 'Attempted to initialize a message with an invalid value.',\n 'E_INVALID_INITIAL_MESSAGE_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when an {@link @nhtio/adk!Identity} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Identity` requires both `identifier` (string or number) and `representation` (string or\n * {@link @nhtio/adk!Tokenizable}) to be present and of the correct type. Passing an incomplete or\n * incorrectly typed object signals a programming error in the caller.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_IDENTITY_VALUE = createException(\n 'E_INVALID_INITIAL_IDENTITY_VALUE',\n 'Attempted to initialize an identity with an invalid value.',\n 'E_INVALID_INITIAL_IDENTITY_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Thought} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Thought` requires `id`, `content`, `createdAt`, and `updatedAt` to be present and of the\n * correct type. Passing an incomplete or incorrectly typed object signals a programming error\n * in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_THOUGHT_VALUE = createException(\n 'E_INVALID_INITIAL_THOUGHT_VALUE',\n 'Attempted to initialize a thought with an invalid value.',\n 'E_INVALID_INITIAL_THOUGHT_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!TurnGate} is constructed with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Gates\n */\nexport const E_INVALID_INITIAL_TURN_GATE_VALUE = createException(\n 'E_INVALID_INITIAL_TURN_GATE_VALUE',\n 'Attempted to initialize a turn gate with an invalid value.',\n 'E_INVALID_INITIAL_TURN_GATE_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown synchronously in the caller's context when {@link @nhtio/adk!TurnGate.resolve} is called with a\n * value that fails the gate's schema.\n *\n * @remarks\n * Fatal — passing the wrong type to `resolve()` is a programming error. The internal promise is\n * NOT settled when this is thrown; the gate remains open.\n *\n * @group Gates\n */\nexport const E_INVALID_TURN_GATE_RESOLUTION = createException(\n 'E_INVALID_TURN_GATE_RESOLUTION',\n 'The value supplied to TurnGate.resolve() failed schema validation.',\n 'E_INVALID_TURN_GATE_RESOLUTION',\n 500,\n true\n)\n\n/**\n * Thrown (as a rejection reason) when a {@link @nhtio/adk!TurnGate} times out before being resolved.\n *\n * @remarks\n * Not fatal — a timeout is a recoverable runtime condition; the caller may retry or surface it\n * to the user.\n *\n * @warning\n * A timeout does **not** cancel the external event or clear any remote queue. The gate closes\n * locally, but whatever external system was expected to call `gate.resolve()` may still fire\n * later. Orphaned external state must be handled by the caller.\n *\n * @group Gates\n */\nexport const E_TURN_GATE_TIMEOUT = createException(\n 'E_TURN_GATE_TIMEOUT',\n 'The turn gate timed out before being resolved.',\n 'E_TURN_GATE_TIMEOUT',\n 408,\n false\n)\n\n/**\n * Thrown (as a rejection reason) when a {@link @nhtio/adk!TurnGate} is aborted — either because the turn's\n * `AbortSignal` fired or because {@link @nhtio/adk!TurnGate.abort} was called directly.\n *\n * @remarks\n * Not fatal — abort is an intentional cancellation, not an error in the caller.\n *\n * @group Gates\n */\nexport const E_TURN_GATE_ABORTED = createException(\n 'E_TURN_GATE_ABORTED',\n 'The turn gate was aborted before being resolved.',\n 'E_TURN_GATE_ABORTED',\n 499,\n false\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!SpooledArtifact} is constructed with a value that does not implement the\n * {@link @nhtio/adk!SpoolReader} interface.\n *\n * @remarks\n * Validated at construction time via {@link @nhtio/adk!implementsSpoolReader}. Passing anything that lacks\n * `line`, `byteLength`, or `lineCount` as callable functions signals a programming error in the\n * caller.\n *\n * @group Artifacts\n */\nexport const E_NOT_A_SPOOL_READER = createException(\n 'E_NOT_A_SPOOL_READER',\n 'The provided value does not implement the SpoolReader interface.',\n 'E_NOT_A_SPOOL_READER',\n 500,\n true\n)\n\n/**\n * Thrown when a Media is constructed with a value that does not implement the MediaReader\n * interface.\n *\n * @remarks\n * Validated at construction time. Passing anything that lacks `stream` or `byteLength` as\n * callable functions signals a programming error in the caller.\n *\n * @group Artifacts\n */\nexport const E_NOT_A_MEDIA_READER = createException(\n 'E_NOT_A_MEDIA_READER',\n 'The provided value does not implement the MediaReader interface.',\n 'E_NOT_A_MEDIA_READER',\n 500,\n true\n)\n\n/**\n * Thrown when a Media is initialised with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Artifacts\n */\nexport const E_INVALID_INITIAL_MEDIA_VALUE = createException(\n 'E_INVALID_INITIAL_MEDIA_VALUE',\n 'Attempted to initialize a media with an invalid value.',\n 'E_INVALID_INITIAL_MEDIA_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!ToolCall} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `ToolCall` requires `id`, `tool`, `args`, `checksum`, `isComplete`, `isError`, `createdAt`,\n * and `updatedAt` to be present and of the correct type. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_TOOL_CALL_VALUE = createException(\n 'E_INVALID_INITIAL_TOOL_CALL_VALUE',\n 'Attempted to initialize a tool call with an invalid value.',\n 'E_INVALID_INITIAL_TOOL_CALL_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Tool} is constructed with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Tools\n */\nexport const E_INVALID_INITIAL_TOOL_VALUE = createException(\n 'E_INVALID_INITIAL_TOOL_VALUE',\n 'Attempted to initialize a tool with an invalid value.',\n 'E_INVALID_INITIAL_TOOL_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown synchronously when {@link @nhtio/adk!Tool.validate} is called with arguments that fail the tool's\n * input schema.\n *\n * @remarks\n * Not fatal — an arg validation failure in the tool call loop is a caller mistake that can be\n * surfaced as an error response. The tool handler is NOT called when this is thrown.\n *\n * @group Tools\n */\nexport const E_INVALID_TOOL_ARGS = createException(\n 'E_INVALID_TOOL_ARGS',\n 'The arguments supplied to the tool failed input schema validation.',\n 'E_INVALID_TOOL_ARGS',\n 422,\n false\n)\n\n/**\n * Thrown (as a rejection reason) when a {@link @nhtio/adk!Tool}'s handler throws during execution.\n *\n * @remarks\n * Not fatal — a downstream tool failure is a recoverable runtime condition. The tool call loop\n * catches this error specifically to report the failure back to the model rather than crashing\n * the pipeline.\n *\n * @group Tools\n */\nexport const E_TOOL_DOWNSTREAM_ERROR = createException(\n 'E_TOOL_DOWNSTREAM_ERROR',\n 'The tool handler threw an error during execution.',\n 'E_TOOL_DOWNSTREAM_ERROR',\n 500,\n false\n)\n\n/**\n * Thrown when {@link @nhtio/adk!ToolRegistry.register} is called for a tool name that is already registered\n * and `overwrite` is not `true`.\n *\n * @remarks\n * Fatal — accidentally overwriting a registered tool indicates a programming error. Pass\n * `overwrite: true` to replace an existing tool intentionally.\n *\n * @group Tools\n */\nexport const E_TOOL_ALREADY_REGISTERED = createException(\n 'E_TOOL_ALREADY_REGISTERED',\n 'A tool with this name is already registered. Pass overwrite: true to replace it.',\n 'E_TOOL_ALREADY_REGISTERED',\n 409,\n true\n)\n\n/**\n * Thrown when {@link @nhtio/adk!DispatchContext} is constructed with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Dispatch\n */\nexport const E_INVALID_LLM_EXECUTION_CONTEXT = createException(\n 'E_INVALID_LLM_EXECUTION_CONTEXT',\n 'The LLM execution context cannot be instantiated with the provided value.',\n 'E_INVALID_LLM_EXECUTION_CONTEXT',\n 529,\n true\n)\n\n/**\n * Thrown (as a rejection reason) when {@link @nhtio/adk!DispatchContext.waitFor} is called on a\n * standalone context that was constructed without a `waitFor` function.\n *\n * @remarks\n * Not fatal — the caller can catch this and handle the case where gate suspension is not\n * supported for this execution context.\n *\n * @group Dispatch\n */\nexport const E_LLM_EXECUTION_GATE_NOT_SUPPORTED = createException(\n 'E_LLM_EXECUTION_GATE_NOT_SUPPORTED',\n 'waitFor was called on a standalone DispatchContext with no gate function provided.',\n 'E_LLM_EXECUTION_GATE_NOT_SUPPORTED',\n 501,\n false\n)\n\n/**\n * Thrown when {@link @nhtio/adk!DispatchContext.ack} or {@link @nhtio/adk!DispatchContext.nack} is called on a\n * context that has already been signalled.\n *\n * @remarks\n * Fatal — signalling twice is a programming error in the caller. The first signal wins; the\n * second call is rejected loudly so callers cannot accidentally race between ack and nack.\n *\n * @danger\n * Signalling is **not** silently idempotent. The first `ack()` or `nack()` wins; the second\n * throws immediately. Guard with `if (!ctx.isSignalled)` when more than one seam may signal.\n *\n * @group Dispatch\n */\nexport const E_LLM_EXECUTION_ALREADY_SIGNALLED = createException(\n 'E_LLM_EXECUTION_ALREADY_SIGNALLED',\n 'ack() or nack() was called on an DispatchContext that has already been signalled.',\n 'E_LLM_EXECUTION_ALREADY_SIGNALLED',\n 500,\n true\n)\n\n/**\n * Thrown when {@link @nhtio/adk!DispatchRunner.dispatch} receives an input that fails schema validation.\n *\n * @remarks\n * Fatal — invalid dispatch input indicates a programming error in the caller.\n *\n * @group Dispatch\n */\nexport const E_INVALID_LLM_DISPATCH_INPUT = createException(\n 'E_INVALID_LLM_DISPATCH_INPUT',\n 'The LLM execution runner received an invalid dispatch input.',\n 'E_INVALID_LLM_DISPATCH_INPUT',\n 529,\n true\n)\n\n/**\n * Emitted (via the observability `error` hook) and re-thrown when a non-abort error propagates\n * out of the input or output middleware pipeline during {@link @nhtio/adk!DispatchRunner.dispatch}.\n *\n * @remarks\n * Not fatal — pipeline errors are recoverable runtime conditions. `dispatch()` rejects with this\n * exception so callers can handle the failure via try/catch. Both `dispatchInputPipeline` and\n * `dispatchOutputPipeline` share this one code — the runner does not split input vs. output at\n * this layer.\n *\n * @group Pipelines\n */\nexport const E_DISPATCH_PIPELINE_ERROR = createException(\n 'E_DISPATCH_PIPELINE_ERROR',\n 'An error occurred in an LLM execution pipeline.',\n 'E_DISPATCH_PIPELINE_ERROR',\n 500,\n false\n)\n\n/**\n * Emitted (via the observability `error` hook) and re-thrown when the user-supplied executor\n * callback throws during {@link @nhtio/adk!DispatchRunner.dispatch}.\n *\n * @remarks\n * Not fatal — executor errors are recoverable runtime conditions. `dispatch()` rejects with this\n * exception so callers can handle the failure via try/catch.\n *\n * @group Dispatch\n */\nexport const E_LLM_EXECUTION_EXECUTOR_ERROR = createException(\n 'E_LLM_EXECUTION_EXECUTOR_ERROR',\n 'The LLM execution executor callback threw an error.',\n 'E_LLM_EXECUTION_EXECUTOR_ERROR',\n 500,\n false\n)\n\n/**\n * Thrown when `encode()`-ing a reader-backed primitive ({@link @nhtio/adk!Media},\n * {@link @nhtio/adk!SpooledArtifact}) whose underlying reader cannot describe itself.\n *\n * @remarks\n * The encoder serialises reader-backed primitives as **handles**, not bytes: the reader emits a\n * `{ tag, locator }` descriptor (via its optional `describe()` method) and decode re-binds it through a\n * registered resolver. A reader with no `describe()` has no serialisable handle — there is nothing to\n * write down. The single printf argument names the offending field (e.g. `\"reader\"`).\n *\n * This is deliberately not silent: dropping the reader would yield a `Media`/`SpooledArtifact` that\n * decodes into a handle pointing at nothing. The framework refuses to fabricate that. The canonical\n * trigger is a `fromWebFile`-backed `Media` — a browser `Blob` is not re-openable across a\n * serialisation boundary, and the encoder is synchronous so it cannot drain the bytes inline. Re-wrap\n * the bytes in a describable reader (e.g. persist to a spool/media store) before encoding.\n *\n * Not fatal — an un-encodable value is a caller condition, not a runner failure.\n *\n * @group Primitive Validation\n */\nexport const E_READER_NOT_DESCRIBABLE = createException<[string]>(\n 'E_READER_NOT_DESCRIBABLE',\n 'Cannot encode this value: its %s reader does not implement describe(), so it has no serialisable handle. Back it with a describable reader (a spool/media store) before encoding.',\n 'E_READER_NOT_DESCRIBABLE',\n 422,\n false\n)\n\n/**\n * Thrown when `decode()`-ing a reader handle whose `tag` has no registered resolver.\n *\n * @remarks\n * A reader descriptor's `tag` (e.g. `\"spool:flydrive\"`, `\"media:in-memory\"`) names the resolver that\n * re-binds the handle to a live reader. In-memory and fetch resolvers auto-register when the\n * `@nhtio/adk/batteries/encoding` battery loads; durable-store resolvers (flydrive, OPFS) must be\n * registered by the consumer **with the live `Disk`/OPFS root** before decoding, because the locator\n * carries only the key — not the binding. The single printf argument is the unresolved `tag`.\n *\n * The fix is always the same: call `registerSpoolReaderResolver(tag, …)` /\n * `registerMediaReaderResolver(tag, …)` (re-exported from the encoding battery) at application startup,\n * supplying the same ambient store the bytes were written to.\n *\n * Not fatal — a missing resolver is a wiring condition the caller can correct and retry.\n *\n * @group Primitive Validation\n */\nexport const E_NO_READER_RESOLVER = createException<[string]>(\n 'E_NO_READER_RESOLVER',\n 'No reader resolver registered for tag \"%s\". Register one (with its live store binding) before decoding — see the @nhtio/adk/batteries/encoding battery.',\n 'E_NO_READER_RESOLVER',\n 422,\n false\n)\n\n/**\n * Thrown by {@link @nhtio/adk!Tokenizable} when a DYNAMIC (evaluatable) value's evaluator function fails to\n * produce a usable string at resolve time — either it THREW, or it RETURNED A NON-STRING.\n *\n * @remarks\n * An evaluatable Tokenizable wraps a `(ctx?) => string` that is invoked at prompt-assembly time (and, with\n * no context, at measurement/serialization time). Both failure modes are PROGRAMMER errors, not recoverable\n * runtime conditions: an evaluator that throws is buggy, and a non-string return would otherwise coerce\n * silent garbage into the prompt (`undefined` → \"undefined\", an object → \"[object Object]\"). So we surface\n * loudly rather than degrade — the only sanctioned fallback is the evaluator's OWN `ctx === undefined`\n * branch, which must itself return a string. Inside a runner the throw rides the nack → error seam (a\n * dispatch error / banner); outside a runner it propagates as the real bug it is.\n *\n * The single printf argument describes the failure (\"threw\" or \"returned a non-string (`type`)\"); the\n * original error, when the evaluator threw, is attached on `cause`.\n *\n * @group Primitive Validation\n */\nexport const E_TOKENIZABLE_EVALUATOR_INVALID = createException<[string]>(\n 'E_TOKENIZABLE_EVALUATOR_INVALID',\n 'A dynamic Tokenizable evaluator did not produce a string: %s. The evaluator must return a string for every input (including when the context is undefined), and must not throw.',\n 'E_TOKENIZABLE_EVALUATOR_INVALID',\n 500,\n true\n)\n","/**\n * Well-known `Symbol.for()` keys for the `@nhtio/encoder` custom-class contract.\n *\n * @remarks\n * A primitive opts in to `encode()`/`decode()` by implementing two symbol-keyed methods:\n *\n * - `[ENCODE_METHOD](): Encodable` — an **instance** method returning a serialisable snapshot of self.\n * - `static [DECODE_METHOD](data): T` — a **static** factory reconstructing the instance from that snapshot.\n *\n * These are the docs' \"Option B\" (zero-dependency) opt-in: because `Symbol.for()` resolves against the\n * global symbol registry by string key, a class implements the contract **without importing\n * `@nhtio/encoder`**. The encoder only enters the picture for *decoding* — `registerClass()` (shipped by\n * the `@nhtio/adk/batteries/encoding` battery) maps the wire tag back to a constructor.\n *\n * The string keys are written here exactly once. Every encodable primitive imports these constants\n * rather than re-typing the literals — a typo in one class would otherwise silently make it\n * un-encodable (the encoder would flatten the instance to a plain object instead of throwing).\n *\n * The `: unique symbol` annotation is required: TypeScript only permits a `unique symbol`-typed value\n * as a computed class-member name.\n */\n\n/** Instance method key: serialise the instance into an `Encodable` snapshot. */\nexport const ENCODE_METHOD: unique symbol = Symbol.for('@nhtio/encoder:toEncoded')\n\n/** Static method key: reconstruct an instance from an `Encodable` snapshot. */\nexport const DECODE_METHOD: unique symbol = Symbol.for('@nhtio/encoder:fromEncoded')\n","import { isInstanceOf } from './guards'\nimport type { TokenEncoding } from '../classes/tokenizable'\n\n/**\n * Ambient channel that lets a leaf token estimator ({@link @nhtio/adk!Tokenizable.estimateTokens} and the\n * primitives that delegate to it) discover whether it is running inside a runner execution — and, if so,\n * surface a non-fatal warning instead of throwing.\n *\n * @remarks\n * **Why this exists.** `estimateTokens(encoding)` takes only an encoding — it is never handed the\n * {@link @nhtio/adk!DispatchContext}. JavaScript closures are lexical, so the runner's context (a\n * different module) is NOT in scope inside the estimator; the estimator cannot check it directly. The\n * behavioural contract we need is:\n *\n * - **inside a TurnRunner run or DispatchRunner dispatch** — a token-estimation failure must DEGRADE to a\n * cheap char-based guesstimate AND emit a `warning` (never kill the turn/dispatch);\n * - **outside those executions** — FAIL LOUD (throw), because a genuine encoder failure in non-runner code\n * is a real bug that must surface.\n *\n * A runner publishes its warn-emit capability here for the duration of its run; the estimator reads\n * {@link currentEstimationWarnEmitter} in its catch — present ⇒ degrade + warn, absent ⇒ throw. The\n * ambient scope IS the definition of \"am I in a runner execution?\".\n *\n * **Stack, not a single slot.** `DispatchRunner.dispatch()` is a public entry point called both standalone\n * AND nested inside `TurnRunner.run()`. A LIFO stack means the innermost active runner wins: a dispatch\n * running inside a turn pushes on top of the turn's emitter, so estimations during the dispatch route to\n * the (richer, dispatch-scoped) emitter, and the turn's is restored when the dispatch returns. \"Prefer the\n * dispatch channel when both are active\" is the stack order, not a special case.\n *\n * **Synchronous by design.** Token estimation is synchronous, so the emitter on top of the stack is always\n * the one for the currently-executing estimation. {@link runWithEstimationWarnings} still restores the\n * stack in a `finally`, so an async runner body that awaits (with no synchronous estimation crossing the\n * await) remains correct: the push/pop bracket the whole body. No `async_hooks` — this runs in the browser\n * bundle too.\n */\nexport interface EstimationWarning {\n /** The encoding whose real tokenizer failed, triggering the degrade. */\n encoding: TokenEncoding\n /** The underlying error thrown by the encoder (surfaced for diagnostics). */\n error: unknown\n /** A short, bounded preview of the text being estimated — never the full value. */\n textPreview: string\n}\n\n/** Sink invoked by the estimator when it degrades inside a runner. */\nexport type EstimationWarnEmitter = (warning: EstimationWarning) => void\n\n// Module-level LIFO of active warn-emit sinks. Empty ⇒ no runner execution is active ⇒ estimators throw.\nconst stack: EstimationWarnEmitter[] = []\n\n/**\n * Run `body` with `emit` published as the active estimation warn-sink, restoring the previous state\n * afterwards. Runners bracket their whole run/dispatch in this so any token estimation performed within\n * (in an executor, a pipeline, a gate) can degrade-and-warn instead of throwing.\n *\n * @param emit - Sink the leaf estimator calls when it degrades; the runner forwards it to its `warning` bus.\n * @param body - The runner's work. May be sync or return a Promise; the sink stays active until it settles.\n * @returns Whatever `body` returns (including a Promise, which is awaited so the `finally` pops after it).\n */\nexport function runWithEstimationWarnings<T>(emit: EstimationWarnEmitter, body: () => T): T {\n stack.push(emit)\n let popped = false\n const pop = (): void => {\n if (popped) return\n popped = true\n // Pop OUR entry specifically (by identity) rather than blindly truncating, so a misuse elsewhere\n // cannot desynchronise the stack.\n const idx = stack.lastIndexOf(emit)\n if (idx !== -1) stack.splice(idx, 1)\n }\n try {\n const result = body()\n // Cross-realm-safe Promise check (bare `instanceof Promise` is fragile across realms — see\n // CONTRIBUTING §Class identity guards). Runner bodies are async, so this is the live path.\n if (isInstanceOf<Promise<unknown>>(result, 'Promise', Promise)) {\n // Keep the sink active until the async body settles, then pop regardless of outcome.\n return result.finally(pop) as unknown as T\n }\n pop()\n return result\n } catch (err) {\n pop()\n throw err\n }\n}\n\n/**\n * The warn-sink for the innermost active runner execution, or `undefined` when none is active. A leaf\n * estimator reads this in its catch: `undefined` is the signal to THROW (outside any runner); a defined\n * sink is the signal to emit a warning and return the char-based guesstimate.\n */\nexport function currentEstimationWarnEmitter(): EstimationWarnEmitter | undefined {\n return stack.length > 0 ? stack[stack.length - 1] : undefined\n}\n","import { getEncoding } from 'js-tiktoken'\nimport { validator } from '@nhtio/validation'\nimport { LlamaTokenizer } from 'llama-tokenizer-js'\nimport { createException } from '../utils/exceptions'\nimport { isInstanceOf, isError } from '../utils/guards'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../utils/encoder_symbols'\nimport { E_TOKENIZABLE_EVALUATOR_INVALID } from '../exceptions/runtime'\nimport { currentEstimationWarnEmitter } from '../utils/estimation_context'\nimport { fromPreTrained as geminiFromPreTrained } from '@lenml/tokenizer-gemini'\nimport type { Tiktoken } from 'js-tiktoken'\nimport type { AdkEncodableSnapshot } from './encodable'\nimport type { DispatchContext } from '../contracts/dispatch_context'\n\n/**\n * A DYNAMIC Tokenizable value: a function evaluated at prompt-ASSEMBLY time with the live dispatch\n * context, so the wrapped content computes itself coherent with the dispatch it ships in (e.g. a\n * citation instruction that adapts to whether the answer tool survived the subtractive-pass shed).\n *\n * @remarks\n * The context is OPTIONAL: the same Tokenizable is also read outside any dispatch (token measurement,\n * serialization, plain string coercion). The evaluator MUST therefore handle `ctx === undefined` and\n * return a string for EVERY input — that no-ctx branch IS its fallback. It must never throw and must\n * never return a non-string; either violation raises {@link @nhtio/adk!E_TOKENIZABLE_EVALUATOR_INVALID}\n * (loud — a mis-authored evaluator must not silently coerce garbage into the prompt). Keep evaluators\n * serializer-friendly (capture only module-level refs or values passed as explicit bindings, NOT live\n * per-turn state) so a dynamic Tokenizable round-trips its evaluator and stays dynamic across encode/decode.\n */\nexport type TokenizableEvaluator = (ctx?: DispatchContext) => string\n\n/**\n * The set of supported token encoding identifiers.\n *\n * @remarks\n * Each value maps to a specific estimation backend:\n * - `gpt2`, `r50k_base`, `p50k_base`, `p50k_edit`, `cl100k_base`, `o200k_base` — exact counts\n * via `js-tiktoken` (OpenAI / tiktoken-compatible models).\n * - `gemini` — exact counts via `@lenml/tokenizer-gemini`, which embeds Gemini's actual\n * SentencePiece vocabulary locally with no API call required.\n * - `gemma` — exact counts for Google's Gemma models (Gemma 2/3/4, incl. the on-device\n * `.litertlm` / ONNX builds). Backed by the SAME `@lenml/tokenizer-gemini` package, whose bundled\n * `tokenizer_config.json` declares `\"tokenizer_class\": \"GemmaTokenizer\"` over the shared 256k-vocab\n * SentencePiece tokenizer — Gemini and Gemma share it, and it encodes Gemma's control tokens\n * (`<start_of_turn>`, `<end_of_turn>`, `<eos>`, …) as single ids. Deliberate reuse, not a proxy: no\n * extra dependency. Distinct identifier so callers can say what model they mean.\n * - `llama2` — exact counts via `llama-tokenizer-js` (Llama 1 and 2). Llama 3+ uses a\n * different vocabulary and should use the `llama3` identifier once a suitable sync backend\n * is available.\n * - `claude` — heuristic approximation using Anthropic's published ~3.5 chars/token ratio.\n * No local tokenizer is available for Claude 3+ models; the Anthropic SDK's\n * `messages.countTokens()` API is the only exact path but requires a network call.\n *\n * This array is the CANONICAL, closed set of backends built into core — adding one of these\n * requires editing core (add a case to {@link Tokenizable.estimateTokens}'s internal switch). For\n * every OTHER encoding a battery or consumer wants to measure (a model-specific tokenizer core has\n * no business knowing about), call {@link registerTokenEstimator} instead — no core edit required.\n * See {@link TokenEncodingId} for the widened identifier type that accepts both.\n */\nexport const TokenEncoding = [\n 'gpt2',\n 'r50k_base',\n 'p50k_base',\n 'p50k_edit',\n 'cl100k_base',\n 'o200k_base',\n 'gemini',\n 'gemma',\n 'llama2',\n 'claude',\n] as const\n\n/**\n * Union of all recognised token encoding identifier strings.\n *\n * @remarks\n * Derived from {@link TokenEncoding} so the type and the runtime array stay in sync\n * automatically when new encodings are added.\n */\nexport type TokenEncoding = (typeof TokenEncoding)[number]\n\n/**\n * A recognised token-encoding identifier: one of the closed {@link TokenEncoding} built-ins, OR any\n * other string registered via {@link registerTokenEstimator}.\n *\n * @remarks\n * The `(string & {})` half of the union is a widening trick, not a real intersection — `string & {}`\n * has no members beyond `string`, so it accepts any string value while `TokenEncoding` still\n * contributes its literal members to editor autocomplete (a bare `string` union member would erase\n * that autocomplete entirely, since TypeScript collapses `TokenEncoding | string` to `string`). Use\n * this type wherever an API accepts \"a built-in encoding, or a custom one\" — including the `tokenEncoding`\n * property on battery adapter options, which treat the built-ins as suggestions but permit any string.\n */\nexport type TokenEncodingId = TokenEncoding | (string & {})\n\n/**\n * A custom token-count function registered for a non-built-in {@link TokenEncodingId} via\n * {@link registerTokenEstimator}.\n *\n * @remarks\n * Synchronous, matching the built-in estimation backends: every backend behind the\n * {@link TokenEncoding} switch (`js-tiktoken`, `@lenml/tokenizer-gemini`, `llama-tokenizer-js`, the\n * Claude heuristic) resolves synchronously, and {@link Tokenizable.estimateTokens} itself returns a\n * plain `number` — not a `Promise<number>`. A custom estimator therefore must not be async either, so\n * a registered encoding stays a drop-in peer of the built-ins (same call shape, no `await` threaded\n * through `estimateTokens` for some encodings and not others). Wrap an inherently-async tokenizer in a\n * synchronous cache (measure ahead of time / memoize a warmed instance) before registering it.\n *\n * @param value - The already-RESOLVED text to count (the same string `countFor` measures for the\n * built-in backends — i.e. `render(ctx)`'s output, never the raw evaluator or ctx).\n * @returns The estimated token count for `value`.\n */\nexport type TokenEstimatorFn = (value: string) => number\n\n/**\n * Thrown by {@link registerTokenEstimator} when the given encoding identifier names a built-in\n * {@link TokenEncoding} rather than a genuinely custom one.\n *\n * @remarks\n * The built-in encodings are canonical: `'gemma'`, `'cl100k_base'`, and friends must always resolve\n * to their core backend (`js-tiktoken`, `@lenml/tokenizer-gemini`, `llama-tokenizer-js`, the Claude\n * heuristic), never to a consumer-supplied override. Allowing a shadow registration would let one\n * battery silently change another's token counts for a shared built-in name — a correctness hazard\n * that is cheap to prevent at registration time. Fatal: this is a programming error in the caller\n * (pick a distinct identifier), not a runtime condition to recover from.\n */\nexport const E_TOKEN_ESTIMATOR_SHADOWS_BUILTIN = createException<[string]>(\n 'E_TOKEN_ESTIMATOR_SHADOWS_BUILTIN',\n 'Cannot register a token estimator for \"%s\": it shadows a built-in TokenEncoding. Built-in encodings always resolve to their core backend and cannot be overridden — register a distinct encoding identifier instead.',\n 'E_TOKEN_ESTIMATOR_SHADOWS_BUILTIN',\n 409,\n true\n)\n\n// Custom encodings registered via registerTokenEstimator, consulted AFTER the built-in switch so the\n// closed set's fast path (and its degrade-vs-throw contract) is never disturbed by registration.\nconst customEstimators = new Map<string, TokenEstimatorFn>()\nconst warnedUnregisteredEncodings = new Set<string>()\n\n// The built-in identifiers as a Set for O(1) shadow-checks and the isBuiltinEncoding guard below.\nconst builtinEncodingSet = new Set<string>(TokenEncoding)\n\n/** Narrows a {@link TokenEncodingId} to the closed {@link TokenEncoding} union when it names a built-in. */\nconst isBuiltinEncoding = (encoding: string): encoding is TokenEncoding =>\n builtinEncodingSet.has(encoding)\n\n/**\n * Register (or replace) a {@link TokenEstimatorFn} for a custom {@link TokenEncodingId}, so\n * {@link Tokenizable.estimateTokens} can measure it without a core code change.\n *\n * @remarks\n * This is the additive escape hatch for the closed {@link TokenEncoding} set. Say a context-management\n * battery needs to measure tokens for a model that core has no built-in backend for — it simply calls\n * this once, at startup, for that model's identifier. From then on the encoding is measurable, with no\n * core code change (a new case in {@link Tokenizable.estimateTokens}'s switch) ever required. Mirrors the\n * {@link @nhtio/adk!registerMediaReaderResolver} / {@link @nhtio/adk!registerSpoolReaderResolver} registry\n * idiom used for reader handles — register a factory once, core (or the primitive) consults it, nobody\n * imports a battery from core.\n *\n * Resolution order inside {@link Tokenizable.estimateTokens}: the built-in switch is tried FIRST (so\n * the closed set's fast path — including its degrade-to-heuristic-on-encoder-failure contract — is\n * completely unaffected by the registry existing), and only an encoding the switch doesn't recognise\n * falls through to this registry.\n *\n * Idempotent-by-overwrite: registering the same `encoding` twice replaces the previous estimator —\n * useful for hot-swapping a warmed tokenizer instance without restarting. Registering a name that\n * shadows a BUILT-IN {@link TokenEncoding} (e.g. `'gemma'`, `'cl100k_base'`) is rejected: the built-ins\n * are canonical and must always resolve to their core backend, never to a consumer override.\n *\n * @param encoding - The custom encoding identifier this estimator handles. Must not be one of the\n * built-in {@link TokenEncoding} values.\n * @param estimator - The synchronous token-count function to call for `encoding`.\n * @throws {@link @nhtio/adk!E_TOKEN_ESTIMATOR_SHADOWS_BUILTIN} when `encoding` names a built-in.\n */\nexport function registerTokenEstimator(encoding: string, estimator: TokenEstimatorFn): void {\n if (isBuiltinEncoding(encoding)) {\n throw new E_TOKEN_ESTIMATOR_SHADOWS_BUILTIN([encoding])\n }\n customEstimators.set(encoding, estimator)\n}\n\n/**\n * Backing schema for {@link Tokenizable.schema}.\n *\n * @remarks\n * Accepts a plain `string` or an existing {@link Tokenizable} instance. Strings pass through\n * unchanged; {@link Tokenizable} instances are accepted via {@link Tokenizable.isTokenizable}\n * to remain cross-realm safe.\n */\nconst stringOrTokenizableSchema = validator.alternatives(\n validator.string(),\n validator.custom((value, helpers) => {\n if (Tokenizable.isTokenizable(value)) {\n return value\n }\n return helpers.error('any.invalid')\n })\n)\n\n/**\n * Backing schema for {@link Tokenizable.emptyableSchema}.\n *\n * @remarks\n * Identical to {@link stringOrTokenizableSchema} except that the EMPTY string is accepted. Joi\n * strings disallow `''` by default, so the strict fragment rejects it while a `new Tokenizable('')`\n * instance sails through the custom branch — an inconsistency that only shows up once a caller\n * legitimately has nothing to put in the field.\n *\n * Deliberately a SEPARATE fragment rather than relaxing the strict one: `Tokenizable.schema` also\n * backs `systemPrompt`, `standingInstructions`, `Identity.representation`, and `Memory.content`,\n * where an empty value is meaningless and should stay a validation error. Opt in per-field.\n */\nconst emptyableStringOrTokenizableSchema = validator.alternatives(\n validator.string().allow(''),\n validator.custom((value, helpers) => {\n if (Tokenizable.isTokenizable(value)) {\n return value\n }\n return helpers.error('any.invalid')\n })\n)\n\n// Lazily-initialised singletons — tokenizers are expensive to load so we defer\n// until first use and reuse across all Tokenizable instances thereafter.\nlet geminiTokenizerInstance: ReturnType<typeof geminiFromPreTrained> | undefined\nlet llamaTokenizerInstance: InstanceType<typeof LlamaTokenizer> | undefined\n\n// js-tiktoken's `getEncoding` has no internal cache — each call does `new Tiktoken(<ranks>)`,\n// parsing the full BPE rank table (~800ms for o200k_base). Building the encoder dwarfs the\n// subsequent `encode()` (~0.6ms) by ~1000×, so a fresh encoder per `estimateTokens` call turns\n// repeated counting (e.g. re-measuring an accumulating dispatch context every iteration) into\n// O(iterations) encoder rebuilds that monopolise a single-threaded host. Cache the encoder per\n// encoding, mirroring the Gemini/Llama singletons above — Tiktoken instances are stateless and\n// safe to reuse across all Tokenizable instances.\nconst tiktokenEncoderInstances = new Map<TokenEncoding, Tiktoken>()\n\nconst getGeminiTokenizer = () => {\n if (!geminiTokenizerInstance) {\n geminiTokenizerInstance = geminiFromPreTrained()\n }\n return geminiTokenizerInstance\n}\n\nconst getLlamaTokenizer = () => {\n if (!llamaTokenizerInstance) {\n llamaTokenizerInstance = new LlamaTokenizer()\n }\n return llamaTokenizerInstance\n}\n\nconst getTiktokenEncoder = (encoding: TokenEncoding): Tiktoken => {\n let enc = tiktokenEncoderInstances.get(encoding)\n if (!enc) {\n enc = getEncoding(encoding as any)\n tiktokenEncoderInstances.set(encoding, enc)\n }\n return enc\n}\n\n/**\n * A mutable string with a built-in token counter.\n *\n * @remarks\n * The wrapped string can be read via the standard coercion protocol and updated at any time via\n * {@link Tokenizable.set}. Token counts are computed lazily on first access per encoding and\n * cached until the value changes, avoiding redundant encoder invocations when the same content\n * is measured multiple times across a pipeline.\n *\n * Estimation is dispatched by encoding identifier — see {@link TokenEncoding} for the full list of\n * built-in backends and their accuracy characteristics, and {@link registerTokenEstimator} for adding\n * more without a core change. An encoding that is neither a built-in nor registered resolves to\n * `undefined` (see {@link Tokenizable.estimateTokens}) — this pre-dates the registry and is unchanged\n * by it. Separately, a built-in encoder that THROWS while measuring (as opposed to an unrecognised\n * name) degrades to a `ceil(length / 3.5)` character heuristic inside a runner execution — see\n * `degradeOrThrow` and `utils/estimation_context`.\n *\n * The class implements the standard JS value-coercion protocol (`toString`, `valueOf`,\n * `toJSON`, `toLocaleString`, `Symbol.for('nodejs.util.inspect.custom')`) so instances behave\n * transparently as strings in most contexts.\n */\nexport class Tokenizable {\n /** The set of supported token-encoding identifiers, re-exposed as a static for convenience. */\n public static TokenEncoding = TokenEncoding\n\n /**\n * Validator schema that accepts a plain `string` or a {@link Tokenizable} instance.\n *\n * @remarks\n * Reusable fragment for any schema that wants to accept either form — for example,\n * `systemPrompt` and each item in `standingInstructions` in `turnContextSchema`.\n */\n public static schema = stringOrTokenizableSchema\n\n /**\n * Variant of {@link Tokenizable.schema} that additionally accepts the EMPTY string.\n *\n * @remarks\n * For fields where \"present but empty\" is a legitimate state rather than a mistake — e.g.\n * {@link @nhtio/adk!Thought.content} in opaque-replay mode, where the meaning lives in the vendor\n * `payload` and the prose is only kept for token-accounting and observer inspection.\n *\n * Do NOT reach for this by default. {@link Tokenizable.schema} stays strict precisely because an\n * empty system prompt or a blank standing instruction is a bug worth failing on.\n */\n public static emptyableSchema = emptyableStringOrTokenizableSchema\n\n declare toJSON: () => string\n declare toString: () => string\n declare valueOf: () => string\n declare toLocaleString: () => string\n /** Replace the wrapped value (string or evaluator) and invalidate the cached token estimates. */\n declare set: (value: string | TokenizableEvaluator) => void\n /**\n * Resolve the wrapped content against an OPTIONAL dispatch context and return the string. For a static\n * value the context is ignored. For a dynamic (evaluatable) value the evaluator is invoked with `ctx`\n * ({@link TokenizableEvaluator}); assembly passes the live context so the content matches the dispatch\n * it ships in, while a no-context call returns the evaluator's `undefined`-branch fallback.\n */\n /** Whether the current wrapped value is evaluator-backed rather than a static string. */\n declare readonly dynamic: boolean\n /** Resolve the value against an optional dispatch context. */\n declare render: (ctx?: DispatchContext) => string\n /**\n * Estimate the token count under the given {@link TokenEncodingId} of the string this Tokenizable\n * resolves to for the OPTIONAL context — i.e. of `render(ctx)`. Passing the same `ctx` assembly uses\n * keeps the budget count honest for dynamic content (it measures exactly what will ship). Accepts\n * both a built-in {@link TokenEncoding} and any encoding registered via {@link registerTokenEstimator}.\n */\n declare estimateTokens: (encoding: TokenEncodingId, ctx?: DispatchContext) => number\n\n // Exactly one of these is set. A static value keeps `#value`; a dynamic value keeps `#evaluator`\n // (and `#value` stays the empty string, never read on the dynamic path).\n #value: string\n #evaluator: TokenizableEvaluator | undefined\n // Per-encoding cache for the STATIC string and the no-ctx (fallback) resolution — both stable.\n #cache: Map<TokenEncodingId, number> = new Map()\n // Per-context cache for DYNAMIC + ctx resolutions: WeakMap<ctxObject, Map<encoding, count>>. A dynamic\n // value resolves differently per ctx, so a single number can't be cached; keying by the ctx object\n // reuses the count across the several measures of one dispatch (subtractive pass + overflow guard) and\n // auto-frees when the ctx is garbage-collected. (Same ctx object ⇒ same resolved string within a\n // dispatch, since the evaluator is a pure read of that ctx's state.)\n #ctxCache: WeakMap<object, Map<TokenEncodingId, number>> = new WeakMap()\n\n /**\n * @param value - The initial value to wrap: a plain `string` (static) or a {@link TokenizableEvaluator}\n * evaluated at assembly time (dynamic).\n */\n constructor(value: string | TokenizableEvaluator) {\n const isFn = typeof value === 'function'\n this.#evaluator = isFn ? (value as TokenizableEvaluator) : undefined\n this.#value = isFn ? '' : (value as string)\n\n // Resolve the wrapped content to a string for an OPTIONAL context. Static → the stored string.\n // Dynamic → invoke the evaluator; a throw OR a non-string return is a programmer bug → raise\n // E_TOKENIZABLE_EVALUATOR_INVALID (loud, no silent coercion, no degrade). The evaluator's own\n // `ctx === undefined` branch is the only sanctioned fallback and must itself return a string.\n const resolve = (ctx?: DispatchContext): string => {\n const fn = this.#evaluator\n if (!fn) return this.#value\n let result: string\n try {\n result = fn(ctx)\n } catch (err) {\n throw new E_TOKENIZABLE_EVALUATOR_INVALID(['the evaluator threw'], {\n cause: isError(err) ? err : new Error(String(err)),\n })\n }\n if (typeof result !== 'string') {\n throw new E_TOKENIZABLE_EVALUATOR_INVALID([`returned a non-string (${typeof result})`])\n }\n return result\n }\n\n // Raw, dependency-free token estimate (~3.5 chars/token) of the RESOLVED text. No encoder, no\n // special-token rules, effectively cannot throw — the guesstimate a real tokenizer degrades TO.\n const estimateTokensRaw = (text: string): number => Math.ceil(text.length / 3.5)\n\n // Shared failure policy for the real tokenizers, enforcing the degrade-vs-throw CONTRACT:\n // - inside a TurnRunner run / DispatchRunner dispatch (an estimation warn-sink is on the ambient\n // stack) → emit a `warning` and DEGRADE to the raw guesstimate, so a token-estimation failure\n // NEVER kills the turn/dispatch;\n // - outside any runner (no sink) → RE-THROW, because a genuine encoder failure in non-runner code is\n // a real bug that must surface (loud), not be silently papered over.\n // This replaces the former `catch → Number.POSITIVE_INFINITY`, which — with the armed overflow guards —\n // made `Infinity > contextWindow` spuriously trip `E_*_CONTEXT_OVERFLOW` on, e.g., text containing a\n // special token. See utils/estimation_context.\n const degradeOrThrow = (encoding: TokenEncoding, text: string, error: unknown): number => {\n const emit = currentEstimationWarnEmitter()\n if (!emit) throw error\n emit({ encoding, error, textPreview: text.slice(0, 80) })\n return estimateTokensRaw(text)\n }\n\n const estimateTokensWithTiktoken = (encoding: TokenEncoding, text: string): number => {\n try {\n const enc: Tiktoken = getTiktokenEncoder(encoding)\n // `encode(text, allowedSpecial, disallowedSpecial)`. js-tiktoken DEFAULTS `disallowedSpecial` to\n // \"all\", so any registered special-token substring in the text (e.g. a doc that mentions\n // `<|endoftext|>`, or model output echoing `<|im_start|>`) makes `encode` THROW\n // (\"The text contains a special token that is not allowed\"). We are ESTIMATING a token count, not\n // round-tripping through the model, so a special-token literal must be counted as ordinary text,\n // never rejected. Pass `disallowedSpecial: []` to disable the guard: specials are BPE-encoded as\n // plain text. Any OTHER encoder failure follows the degrade-vs-throw contract (degradeOrThrow).\n return enc.encode(text, [], []).length\n } catch (err) {\n return degradeOrThrow(encoding, text, err)\n }\n }\n\n const estimateTokensWithGemini = (text: string): number => {\n try {\n return getGeminiTokenizer().encode(text).length\n } catch (err) {\n return degradeOrThrow('gemini', text, err)\n }\n }\n\n // Gemma reuses the very same tokenizer: `@lenml/tokenizer-gemini` bundles the shared 256k-vocab\n // SentencePiece tokenizer whose config is `\"tokenizer_class\": \"GemmaTokenizer\"`. Kept as its own\n // function (rather than folding 'gemma' into the gemini case) so the intent is explicit and a future\n // swap to a dedicated Gemma package is a one-line change here.\n const estimateTokensWithGemma = (text: string): number => {\n try {\n return getGeminiTokenizer().encode(text).length\n } catch (err) {\n return degradeOrThrow('gemma', text, err)\n }\n }\n\n const estimateTokensWithLlama2 = (text: string): number => {\n try {\n return getLlamaTokenizer().encode(text, false).length\n } catch (err) {\n return degradeOrThrow('llama2', text, err)\n }\n }\n\n const estimateTokensWithClaudeHeuristic = (text: string): number => estimateTokensRaw(text)\n\n // Count tokens of an already-RESOLVED string under one of the CLOSED built-in encodings (the\n // switch shared by all built-in callers). Unchanged fast path — `countFor` below only reaches this\n // once it has already narrowed `encoding` to a real {@link TokenEncoding} member.\n const countForBuiltin = (encoding: TokenEncoding, text: string): number => {\n switch (encoding) {\n case 'gpt2':\n case 'r50k_base':\n case 'p50k_base':\n case 'p50k_edit':\n case 'cl100k_base':\n case 'o200k_base':\n return estimateTokensWithTiktoken(encoding, text)\n case 'gemini':\n return estimateTokensWithGemini(text)\n case 'gemma':\n return estimateTokensWithGemma(text)\n case 'llama2':\n return estimateTokensWithLlama2(text)\n case 'claude':\n return estimateTokensWithClaudeHeuristic(text)\n }\n }\n\n // Count tokens of an already-RESOLVED string under any recognised {@link TokenEncodingId}.\n // Resolution order: (1) the built-in switch — completely unchanged, so the closed set's fast path\n // and degrade-vs-throw contract are untouched by the registry existing; (2) the custom-estimator\n // registry, for anything {@link registerTokenEstimator} has registered; (3) the pre-existing\n // fallback path for a truly unrecognised encoding (emits a warning and falls back to the safe\n // 3.5 chars/token heuristic, ensuring overflow math always gets a finite upper-bound estimate).\n const countFor = (encoding: TokenEncodingId, text: string): number => {\n if (isBuiltinEncoding(encoding)) {\n return countForBuiltin(encoding, text)\n }\n const custom = customEstimators.get(encoding)\n if (custom) {\n return custom(text)\n }\n // Unrecognised AND unregistered encodings use the generic character heuristic. Warn once per\n // encoding so callers know the estimate is uncalibrated, while preserving a finite count for\n // context-window arithmetic.\n if (!warnedUnregisteredEncodings.has(encoding)) {\n warnedUnregisteredEncodings.add(encoding)\n console.warn(\n `No token estimator is registered for \"${encoding}\"; using the uncalibrated character heuristic.`\n )\n }\n return text.length\n }\n\n // The standard coercion protocol takes NO argument, so it resolves with no context → the static\n // string, or (dynamic) the evaluator's `undefined`-branch fallback. `render(ctx)` is the explicit,\n // context-aware read that prompt assembly uses.\n const coerce = (): string => resolve(undefined)\n\n Object.defineProperties(this, {\n toJSON: {\n value: coerce,\n enumerable: false,\n configurable: false,\n writable: false,\n },\n toString: {\n value: coerce,\n enumerable: false,\n configurable: false,\n writable: false,\n },\n valueOf: {\n value: coerce,\n enumerable: false,\n configurable: false,\n writable: false,\n },\n toLocaleString: {\n value: coerce,\n enumerable: false,\n configurable: false,\n writable: false,\n },\n [Symbol.for('nodejs.util.inspect.custom')]: {\n value: coerce,\n enumerable: false,\n configurable: false,\n writable: false,\n },\n dynamic: {\n get: () => this.#evaluator !== undefined,\n enumerable: true,\n configurable: false,\n },\n render: {\n value: (ctx?: DispatchContext): string => resolve(ctx),\n enumerable: false,\n configurable: false,\n writable: false,\n },\n set: {\n value: (next: string | TokenizableEvaluator) => {\n const nextIsFn = typeof next === 'function'\n this.#evaluator = nextIsFn ? (next as TokenizableEvaluator) : undefined\n this.#value = nextIsFn ? '' : (next as string)\n this.#cache.clear()\n this.#ctxCache = new WeakMap()\n },\n enumerable: false,\n configurable: false,\n writable: false,\n },\n estimateTokens: {\n value: (encoding: TokenEncodingId, ctx?: DispatchContext): number => {\n // Cache selection: a STATIC value (or a no-ctx resolution — the stable fallback) uses the\n // per-encoding Map; a DYNAMIC value WITH a ctx uses the per-ctx WeakMap (the resolved string\n // varies by ctx, so a single number can't be shared). `ctx === undefined` always hits the\n // stable per-encoding cache regardless of static/dynamic.\n const useCtxCache = this.#evaluator !== undefined && ctx !== undefined\n if (useCtxCache) {\n let m = this.#ctxCache.get(ctx as unknown as object)\n if (m?.has(encoding)) return m.get(encoding)!\n const text = resolve(ctx)\n const est = countFor(encoding, text)\n if (!m) {\n m = new Map()\n this.#ctxCache.set(ctx as unknown as object, m)\n }\n m.set(encoding, est)\n return est\n }\n if (this.#cache.has(encoding)) {\n return this.#cache.get(encoding)!\n }\n const text = resolve(undefined)\n const estimate = countFor(encoding, text)\n this.#cache.set(encoding, estimate)\n return estimate\n },\n enumerable: false,\n configurable: false,\n writable: false,\n },\n })\n }\n\n /**\n * Convenience overload for one-off token counting without managing a {@link Tokenizable} instance.\n *\n * @remarks\n * Creates a temporary instance and immediately discards it — no caching benefit. Use the\n * instance method when you need to count the same value under multiple encodings or when the\n * value may change over time.\n *\n * @param value - The string (or {@link TokenizableEvaluator}) to count tokens for.\n * @param encoding - The encoding identifier to use for counting — a built-in {@link TokenEncoding} or\n * any encoding registered via {@link registerTokenEstimator}.\n * @param ctx - Optional dispatch context; for a dynamic value it selects which resolved string is\n * counted (so the count matches what assembly ships). Ignored for a static string.\n * @returns The estimated number of tokens.\n */\n public static estimateTokens(\n value: string | TokenizableEvaluator,\n encoding: TokenEncodingId,\n ctx?: DispatchContext\n ): number {\n const temp = new Tokenizable(value)\n return temp.estimateTokens(encoding, ctx)\n }\n\n /**\n * Returns `true` if `value` is a {@link Tokenizable} 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 Tokenizable} instance.\n */\n public static isTokenizable(value: unknown): value is Tokenizable {\n return isInstanceOf(value, 'Tokenizable', Tokenizable)\n }\n\n /**\n * Serialise this Tokenizable into an `@nhtio/encoder` snapshot.\n *\n * @remarks\n * The wrapped VALUE is the entire state; the token-count caches are derived and deliberately not encoded\n * (they rebuild lazily after decode). For a STATIC value the snapshot is the string. For a DYNAMIC value\n * the snapshot is the EVALUATOR FUNCTION itself — `@nhtio/encoder` serialises functions (source +\n * explicit bindings), so a dynamic Tokenizable round-trips its evaluator and stays dynamic, re-evaluating\n * live on the next assembly (it does NOT downgrade to a frozen string). Evaluators must therefore stay\n * serializer-friendly: capture only module-level refs / explicit bindings, not live per-turn state.\n * Round-trips via {@link Tokenizable.[DECODE_METHOD]}.\n *\n * @returns The wrapped string, or the evaluator function for a dynamic value.\n */\n [ENCODE_METHOD](): AdkEncodableSnapshot {\n return this.#evaluator ?? this.#value\n }\n\n /**\n * Reconstruct a {@link Tokenizable} from an {@link Tokenizable.[ENCODE_METHOD]} snapshot.\n *\n * @param data - The wrapped string (static) or evaluator function (dynamic) produced by\n * {@link Tokenizable.[ENCODE_METHOD]}.\n * @returns A fresh {@link Tokenizable} over the same value.\n */\n static [DECODE_METHOD](data: AdkEncodableSnapshot): Tokenizable {\n return new Tokenizable(data as string | TokenizableEvaluator)\n }\n}\n\n/**\n * Returns `true` if `value` is a {@link Tokenizable} instance.\n *\n * @remarks\n * Module-level convenience alias for {@link Tokenizable.isTokenizable}. Prefer this form when\n * you need a standalone type guard without importing the full class.\n *\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 Tokenizable} instance.\n */\nexport const isTokenizable = (value: unknown): value is Tokenizable => {\n return isInstanceOf(value, 'Tokenizable', Tokenizable)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAeA,IAAa,+BAA+B,gBAC1C,gCACA,8EACA,gCACA,KACA,IACF;;;;;;;;;;;;AAaA,IAAa,yBAAyB,gBACpC,0BACA,uDACA,0BACA,KACA,IACF;;;;;;;;;;;;AAaA,IAAa,yBAAyB,gBACpC,0BACA,4CACA,0BACA,KACA,KACF;;;;;;;;;;;;AAaA,IAAa,0BAA0B,gBACrC,2BACA,6CACA,2BACA,KACA,KACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,IAAa,6BAA6B,gBACxC,8BACA,2FACA,8BACA,KACA,KACF;;;;;;;;;;;AAYA,IAAa,mCAAmC,gBAC9C,oCACA,uEACA,oCACA,KACA,IACF;;;;;;;;;;;AAYA,IAAa,iCAAiC,gBAC5C,kCACA,2DACA,kCAC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AKA,OAAO,IAAI,UAAU,QAAQ;KAClC,OAAO;IACT;IACA,YAAY;IACZ,cAAc;IACd,UAAU;GACZ;EACF,CAAC;CACH;;;;;;;;;;;;;;;;CAiBA,OAAc,eACZ,OACA,UACA,KACQ;EAER,OAAO,IADU,YAAY,KACtB,EAAK,eAAe,UAAU,GAAG;CAC1C;;;;;;;;;;;CAYA,OAAc,cAAc,OAAsC;EAChE,OAAO,aAAa,OAAO,eAAe,WAAW;CACvD;;;;;;;;;;;;;;;CAgBA,CAAC,iBAAuC;EACtC,OAAO,KAAKF,cAAc,KAAKC;CACjC;;;;;;;;CASA,QAAQ,eAAe,MAAyC;EAC9D,OAAO,IAAI,YAAY,IAAqC;CAC9D;AACF"}
1
+ {"version":3,"file":"tokenizable-VB4Av8GF.mjs","names":["#evaluator","#value","#cache","#ctxCache"],"sources":["../src/lib/utils/encoder_symbols.ts","../src/lib/exceptions/runtime.ts","../src/lib/utils/estimation_context.ts","../src/lib/classes/tokenizable.ts"],"sourcesContent":["/**\n * Well-known `Symbol.for()` keys for the `@nhtio/encoder` custom-class contract.\n *\n * @remarks\n * A primitive opts in to `encode()`/`decode()` by implementing two symbol-keyed methods:\n *\n * - `[ENCODE_METHOD](): Encodable` — an **instance** method returning a serialisable snapshot of self.\n * - `static [DECODE_METHOD](data): T` — a **static** factory reconstructing the instance from that snapshot.\n *\n * These are the docs' \"Option B\" (zero-dependency) opt-in: because `Symbol.for()` resolves against the\n * global symbol registry by string key, a class implements the contract **without importing\n * `@nhtio/encoder`**. The encoder only enters the picture for *decoding* — `registerClass()` (shipped by\n * the `@nhtio/adk/batteries/encoding` battery) maps the wire tag back to a constructor.\n *\n * The string keys are written here exactly once. Every encodable primitive imports these constants\n * rather than re-typing the literals — a typo in one class would otherwise silently make it\n * un-encodable (the encoder would flatten the instance to a plain object instead of throwing).\n *\n * The `: unique symbol` annotation is required: TypeScript only permits a `unique symbol`-typed value\n * as a computed class-member name.\n */\n\n/** Instance method key: serialise the instance into an `Encodable` snapshot. */\nexport const ENCODE_METHOD: unique symbol = Symbol.for('@nhtio/encoder:toEncoded')\n\n/** Static method key: reconstruct an instance from an `Encodable` snapshot. */\nexport const DECODE_METHOD: unique symbol = Symbol.for('@nhtio/encoder:fromEncoded')\n","import { createException } from '../utils/exceptions'\n\n/**\n * Thrown by {@link @nhtio/adk!TurnRunner} when the supplied config object fails schema validation at\n * construction time.\n *\n * @remarks\n * Marked fatal — a misconfigured runner must not be allowed to execute turns.\n *\n * The single printf argument carries the validator's field-level detail (e.g.\n * `\"storeMediaBytesCallback is required\"`) so a misconfiguration names the offending field\n * instead of failing opaquely. The underlying `ValidationError` is also attached on `cause`.\n *\n * @group Turn Runner Construction\n */\nexport const E_INVALID_TURN_RUNNER_CONFIG = createException<[string]>(\n 'E_INVALID_TURN_RUNNER_CONFIG',\n 'The turn runner cannot be instantiated with the provided configuration: %s',\n 'E_INVALID_TURN_RUNNER_CONFIG',\n 529,\n true\n)\n\n/**\n * Thrown by {@link @nhtio/adk!TurnRunner} when the {@link @nhtio/adk!TurnContext} supplied to `run` fails schema\n * validation.\n *\n * @remarks\n * Marked fatal — an invalid context indicates a programming error in the caller, not a\n * recoverable runtime condition. Thrown synchronously out of `run()` before `turnStart` is\n * emitted.\n *\n * @group Turn Input Validation\n */\nexport const E_INVALID_TURN_CONTEXT = createException(\n 'E_INVALID_TURN_CONTEXT',\n 'The turn runner received an invalid context object.',\n 'E_INVALID_TURN_CONTEXT',\n 529,\n true\n)\n\n/**\n * Emitted (via the `error` event) when a non-abort error propagates out of the input\n * middleware pipeline during {@link @nhtio/adk!TurnRunner.run}.\n *\n * @remarks\n * Not fatal — the turn runner emits this on the `error` event rather than throwing, so\n * registered listeners can handle or log the failure without crashing the pipeline. Dispatch\n * and output middleware are skipped; `turnEnd` still fires.\n *\n * @group Pipelines\n */\nexport const E_INPUT_PIPELINE_ERROR = createException(\n 'E_INPUT_PIPELINE_ERROR',\n 'An error occurred in the input pipeline.',\n 'E_INPUT_PIPELINE_ERROR',\n 500,\n false\n)\n\n/**\n * Emitted (via the `error` event) when a non-abort error propagates out of the output\n * middleware pipeline during {@link @nhtio/adk!TurnRunner.run}.\n *\n * @remarks\n * Not fatal — the turn runner emits this on the `error` event rather than throwing, so\n * registered listeners can handle or log the failure without crashing the pipeline. `turnEnd`\n * still fires.\n *\n * @group Pipelines\n */\nexport const E_OUTPUT_PIPELINE_ERROR = createException(\n 'E_OUTPUT_PIPELINE_ERROR',\n 'An error occurred in the output pipeline.',\n 'E_OUTPUT_PIPELINE_ERROR',\n 500,\n false\n)\n\n/**\n * Emitted (via the `error` event) when a middleware pipeline resolves without reaching its\n * terminal handler and without the turn being aborted. Indicates that some middleware\n * returned without calling `next` and without signalling a deliberate refusal via the turn's\n * abort controller.\n *\n * @remarks\n * Not fatal — the runner emits this on the `error` event so the failure is observable, then\n * proceeds to short-circuit the remainder of the turn the same way any other pipeline error\n * would. The constructor takes a single positional argument identifying the pipeline that\n * short-circuited: one of `'turn-input'`, `'turn-output'`, `'dispatch-input'`, or `'dispatch-output'`.\n *\n * Deliberate refusals should call `ctx.abort(reason)`, which sets the `'aborted'` outcome\n * instead of emitting this error.\n *\n * @warning\n * This is a **detection condition**, not a thrown exception. The runner constructs and emits\n * the code itself when it detects a missing `next()` on the unwind — nothing in user code\n * throws it. Upstream post-steps still run normally.\n *\n * @example\n * ```ts\n * throw new E_PIPELINE_SHORT_CIRCUITED(['turn-input'])\n * ```\n *\n * @group Pipelines\n */\nexport const E_PIPELINE_SHORT_CIRCUITED = createException<[string]>(\n 'E_PIPELINE_SHORT_CIRCUITED',\n \"The '%s' middleware pipeline short-circuited without calling next or aborting the turn.\",\n 'E_PIPELINE_SHORT_CIRCUITED',\n 500,\n false\n)\n\n/**\n * Thrown when a registry is initialised with a value that is defined but not a plain object.\n *\n * @remarks\n * Registries expect either `undefined` (empty start) or a plain object as their initial value.\n * Passing a primitive, array, class instance, or other non-object signals a programming error\n * in the caller.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_REGISTRY_VALUE = createException(\n 'E_INVALID_INITIAL_REGISTRY_VALUE',\n 'Attempted to initialize a registry with a defined non-object value.',\n 'E_INVALID_INITIAL_REGISTRY_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Memory} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Memory` requires all fields — `id`, `content`, `confidence`, `importance`, `createdAt`,\n * `updatedAt` — to be present and of the correct type. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_MEMORY_VALUE = createException(\n 'E_INVALID_INITIAL_MEMORY_VALUE',\n 'Attempted to initialize a memory with an invalid value.',\n 'E_INVALID_INITIAL_MEMORY_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a tool call and retrievable eligible for artifact forging share an id.\n */\nexport const E_ARTIFACT_ID_COLLISION = createException<[string]>(\n 'E_ARTIFACT_ID_COLLISION',\n 'Artifact id collision: the tool call and retrievable with id \"%s\" both identify eligible artifacts.',\n 'E_ARTIFACT_ID_COLLISION',\n 409,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Retrievable} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Retrievable` requires `id`, `content`, `trustTier`, `createdAt`, and `updatedAt` to be present\n * and of the correct type, and `trustTier` must be one of `'first-party'`, `'third-party-public'`,\n * or `'third-party-private'`. The `trustTier` decision must be made consciously by the retrieval\n * middleware at construction time — there is no default. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_RETRIEVABLE_VALUE = createException(\n 'E_INVALID_INITIAL_RETRIEVABLE_VALUE',\n 'Invalid initial value supplied to Retrievable constructor.',\n 'E_INVALID_INITIAL_RETRIEVABLE_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Message} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Message` requires `id`, `role` (`user` or `assistant`), `content`, `createdAt`, and\n * `updatedAt` to be present and of the correct type. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_MESSAGE_VALUE = createException(\n 'E_INVALID_INITIAL_MESSAGE_VALUE',\n 'Attempted to initialize a message with an invalid value.',\n 'E_INVALID_INITIAL_MESSAGE_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when an {@link @nhtio/adk!Identity} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Identity` requires both `identifier` (string or number) and `representation` (string or\n * {@link @nhtio/adk!Tokenizable}) to be present and of the correct type. Passing an incomplete or\n * incorrectly typed object signals a programming error in the caller.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_IDENTITY_VALUE = createException(\n 'E_INVALID_INITIAL_IDENTITY_VALUE',\n 'Attempted to initialize an identity with an invalid value.',\n 'E_INVALID_INITIAL_IDENTITY_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Thought} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `Thought` requires `id`, `content`, `createdAt`, and `updatedAt` to be present and of the\n * correct type. Passing an incomplete or incorrectly typed object signals a programming error\n * in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_THOUGHT_VALUE = createException(\n 'E_INVALID_INITIAL_THOUGHT_VALUE',\n 'Attempted to initialize a thought with an invalid value.',\n 'E_INVALID_INITIAL_THOUGHT_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!TurnGate} is constructed with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Gates\n */\nexport const E_INVALID_INITIAL_TURN_GATE_VALUE = createException(\n 'E_INVALID_INITIAL_TURN_GATE_VALUE',\n 'Attempted to initialize a turn gate with an invalid value.',\n 'E_INVALID_INITIAL_TURN_GATE_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown synchronously in the caller's context when {@link @nhtio/adk!TurnGate.resolve} is called with a\n * value that fails the gate's schema.\n *\n * @remarks\n * Fatal — passing the wrong type to `resolve()` is a programming error. The internal promise is\n * NOT settled when this is thrown; the gate remains open.\n *\n * @group Gates\n */\nexport const E_INVALID_TURN_GATE_RESOLUTION = createException(\n 'E_INVALID_TURN_GATE_RESOLUTION',\n 'The value supplied to TurnGate.resolve() failed schema validation.',\n 'E_INVALID_TURN_GATE_RESOLUTION',\n 500,\n true\n)\n\n/**\n * Thrown (as a rejection reason) when a {@link @nhtio/adk!TurnGate} times out before being resolved.\n *\n * @remarks\n * Not fatal — a timeout is a recoverable runtime condition; the caller may retry or surface it\n * to the user.\n *\n * @warning\n * A timeout does **not** cancel the external event or clear any remote queue. The gate closes\n * locally, but whatever external system was expected to call `gate.resolve()` may still fire\n * later. Orphaned external state must be handled by the caller.\n *\n * @group Gates\n */\nexport const E_TURN_GATE_TIMEOUT = createException(\n 'E_TURN_GATE_TIMEOUT',\n 'The turn gate timed out before being resolved.',\n 'E_TURN_GATE_TIMEOUT',\n 408,\n false\n)\n\n/**\n * Thrown (as a rejection reason) when a {@link @nhtio/adk!TurnGate} is aborted — either because the turn's\n * `AbortSignal` fired or because {@link @nhtio/adk!TurnGate.abort} was called directly.\n *\n * @remarks\n * Not fatal — abort is an intentional cancellation, not an error in the caller.\n *\n * @group Gates\n */\nexport const E_TURN_GATE_ABORTED = createException(\n 'E_TURN_GATE_ABORTED',\n 'The turn gate was aborted before being resolved.',\n 'E_TURN_GATE_ABORTED',\n 499,\n false\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!SpooledArtifact} is constructed with a value that does not implement the\n * {@link @nhtio/adk!SpoolReader} interface.\n *\n * @remarks\n * Validated at construction time via {@link @nhtio/adk!implementsSpoolReader}. Passing anything that lacks\n * `line`, `byteLength`, or `lineCount` as callable functions signals a programming error in the\n * caller.\n *\n * @group Artifacts\n */\nexport const E_NOT_A_SPOOL_READER = createException(\n 'E_NOT_A_SPOOL_READER',\n 'The provided value does not implement the SpoolReader interface.',\n 'E_NOT_A_SPOOL_READER',\n 500,\n true\n)\n\n/**\n * Thrown when a Media is constructed with a value that does not implement the MediaReader\n * interface.\n *\n * @remarks\n * Validated at construction time. Passing anything that lacks `stream` or `byteLength` as\n * callable functions signals a programming error in the caller.\n *\n * @group Artifacts\n */\nexport const E_NOT_A_MEDIA_READER = createException(\n 'E_NOT_A_MEDIA_READER',\n 'The provided value does not implement the MediaReader interface.',\n 'E_NOT_A_MEDIA_READER',\n 500,\n true\n)\n\n/**\n * Thrown when a Media is initialised with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Artifacts\n */\nexport const E_INVALID_INITIAL_MEDIA_VALUE = createException(\n 'E_INVALID_INITIAL_MEDIA_VALUE',\n 'Attempted to initialize a media with an invalid value.',\n 'E_INVALID_INITIAL_MEDIA_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!ToolCall} is initialised with a value that fails schema validation.\n *\n * @remarks\n * `ToolCall` requires `id`, `tool`, `args`, `checksum`, `isComplete`, `isError`, `createdAt`,\n * and `updatedAt` to be present and of the correct type. Passing an incomplete or incorrectly\n * typed object signals a programming error in the caller, not a recoverable runtime condition.\n *\n * @group Primitive Validation\n */\nexport const E_INVALID_INITIAL_TOOL_CALL_VALUE = createException(\n 'E_INVALID_INITIAL_TOOL_CALL_VALUE',\n 'Attempted to initialize a tool call with an invalid value.',\n 'E_INVALID_INITIAL_TOOL_CALL_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown when a {@link @nhtio/adk!Tool} is constructed with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Tools\n */\nexport const E_INVALID_INITIAL_TOOL_VALUE = createException(\n 'E_INVALID_INITIAL_TOOL_VALUE',\n 'Attempted to initialize a tool with an invalid value.',\n 'E_INVALID_INITIAL_TOOL_VALUE',\n 500,\n true\n)\n\n/**\n * Thrown synchronously when {@link @nhtio/adk!Tool.validate} is called with arguments that fail the tool's\n * input schema.\n *\n * @remarks\n * Not fatal — an arg validation failure in the tool call loop is a caller mistake that can be\n * surfaced as an error response. The tool handler is NOT called when this is thrown.\n *\n * @group Tools\n */\nexport const E_INVALID_TOOL_ARGS = createException(\n 'E_INVALID_TOOL_ARGS',\n 'The arguments supplied to the tool failed input schema validation.',\n 'E_INVALID_TOOL_ARGS',\n 422,\n false\n)\n\n/**\n * Thrown (as a rejection reason) when a {@link @nhtio/adk!Tool}'s handler throws during execution.\n *\n * @remarks\n * Not fatal — a downstream tool failure is a recoverable runtime condition. The tool call loop\n * catches this error specifically to report the failure back to the model rather than crashing\n * the pipeline.\n *\n * @group Tools\n */\nexport const E_TOOL_DOWNSTREAM_ERROR = createException(\n 'E_TOOL_DOWNSTREAM_ERROR',\n 'The tool handler threw an error during execution.',\n 'E_TOOL_DOWNSTREAM_ERROR',\n 500,\n false\n)\n\n/**\n * Thrown when {@link @nhtio/adk!ToolRegistry.register} is called for a tool name that is already registered\n * and `overwrite` is not `true`.\n *\n * @remarks\n * Fatal — accidentally overwriting a registered tool indicates a programming error. Pass\n * `overwrite: true` to replace an existing tool intentionally.\n *\n * @group Tools\n */\nexport const E_TOOL_ALREADY_REGISTERED = createException(\n 'E_TOOL_ALREADY_REGISTERED',\n 'A tool with this name is already registered. Pass overwrite: true to replace it.',\n 'E_TOOL_ALREADY_REGISTERED',\n 409,\n true\n)\n\n/**\n * Thrown when {@link @nhtio/adk!DispatchContext} is constructed with a value that fails schema validation.\n *\n * @remarks\n * Fatal — bad construction arguments indicate a programming error in the caller.\n *\n * @group Dispatch\n */\nexport const E_INVALID_LLM_EXECUTION_CONTEXT = createException(\n 'E_INVALID_LLM_EXECUTION_CONTEXT',\n 'The LLM execution context cannot be instantiated with the provided value.',\n 'E_INVALID_LLM_EXECUTION_CONTEXT',\n 529,\n true\n)\n\n/**\n * Thrown (as a rejection reason) when {@link @nhtio/adk!DispatchContext.waitFor} is called on a\n * standalone context that was constructed without a `waitFor` function.\n *\n * @remarks\n * Not fatal — the caller can catch this and handle the case where gate suspension is not\n * supported for this execution context.\n *\n * @group Dispatch\n */\nexport const E_LLM_EXECUTION_GATE_NOT_SUPPORTED = createException(\n 'E_LLM_EXECUTION_GATE_NOT_SUPPORTED',\n 'waitFor was called on a standalone DispatchContext with no gate function provided.',\n 'E_LLM_EXECUTION_GATE_NOT_SUPPORTED',\n 501,\n false\n)\n\n/**\n * Thrown when {@link @nhtio/adk!DispatchContext.ack} or {@link @nhtio/adk!DispatchContext.nack} is called on a\n * context that has already been signalled.\n *\n * @remarks\n * Fatal — signalling twice is a programming error in the caller. The first signal wins; the\n * second call is rejected loudly so callers cannot accidentally race between ack and nack.\n *\n * @danger\n * Signalling is **not** silently idempotent. The first `ack()` or `nack()` wins; the second\n * throws immediately. Guard with `if (!ctx.isSignalled)` when more than one seam may signal.\n *\n * @group Dispatch\n */\nexport const E_LLM_EXECUTION_ALREADY_SIGNALLED = createException(\n 'E_LLM_EXECUTION_ALREADY_SIGNALLED',\n 'ack() or nack() was called on an DispatchContext that has already been signalled.',\n 'E_LLM_EXECUTION_ALREADY_SIGNALLED',\n 500,\n true\n)\n\n/**\n * Thrown when {@link @nhtio/adk!DispatchRunner.dispatch} receives an input that fails schema validation.\n *\n * @remarks\n * Fatal — invalid dispatch input indicates a programming error in the caller.\n *\n * @group Dispatch\n */\nexport const E_INVALID_LLM_DISPATCH_INPUT = createException(\n 'E_INVALID_LLM_DISPATCH_INPUT',\n 'The LLM execution runner received an invalid dispatch input.',\n 'E_INVALID_LLM_DISPATCH_INPUT',\n 529,\n true\n)\n\n/**\n * Emitted (via the observability `error` hook) and re-thrown when a non-abort error propagates\n * out of the input or output middleware pipeline during {@link @nhtio/adk!DispatchRunner.dispatch}.\n *\n * @remarks\n * Not fatal — pipeline errors are recoverable runtime conditions. `dispatch()` rejects with this\n * exception so callers can handle the failure via try/catch. Both `dispatchInputPipeline` and\n * `dispatchOutputPipeline` share this one code — the runner does not split input vs. output at\n * this layer.\n *\n * @group Pipelines\n */\nexport const E_DISPATCH_PIPELINE_ERROR = createException(\n 'E_DISPATCH_PIPELINE_ERROR',\n 'An error occurred in an LLM execution pipeline.',\n 'E_DISPATCH_PIPELINE_ERROR',\n 500,\n false\n)\n\n/**\n * Emitted (via the observability `error` hook) and re-thrown when the user-supplied executor\n * callback throws during {@link @nhtio/adk!DispatchRunner.dispatch}.\n *\n * @remarks\n * Not fatal — executor errors are recoverable runtime conditions. `dispatch()` rejects with this\n * exception so callers can handle the failure via try/catch.\n *\n * @group Dispatch\n */\nexport const E_LLM_EXECUTION_EXECUTOR_ERROR = createException(\n 'E_LLM_EXECUTION_EXECUTOR_ERROR',\n 'The LLM execution executor callback threw an error.',\n 'E_LLM_EXECUTION_EXECUTOR_ERROR',\n 500,\n false\n)\n\n/**\n * Thrown when `encode()`-ing a reader-backed primitive ({@link @nhtio/adk!Media},\n * {@link @nhtio/adk!SpooledArtifact}) whose underlying reader cannot describe itself.\n *\n * @remarks\n * The encoder serialises reader-backed primitives as **handles**, not bytes: the reader emits a\n * `{ tag, locator }` descriptor (via its optional `describe()` method) and decode re-binds it through a\n * registered resolver. A reader with no `describe()` has no serialisable handle — there is nothing to\n * write down. The single printf argument names the offending field (e.g. `\"reader\"`).\n *\n * This is deliberately not silent: dropping the reader would yield a `Media`/`SpooledArtifact` that\n * decodes into a handle pointing at nothing. The framework refuses to fabricate that. The canonical\n * trigger is a `fromWebFile`-backed `Media` — a browser `Blob` is not re-openable across a\n * serialisation boundary, and the encoder is synchronous so it cannot drain the bytes inline. Re-wrap\n * the bytes in a describable reader (e.g. persist to a spool/media store) before encoding.\n *\n * Not fatal — an un-encodable value is a caller condition, not a runner failure.\n *\n * @group Primitive Validation\n */\nexport const E_READER_NOT_DESCRIBABLE = createException<[string]>(\n 'E_READER_NOT_DESCRIBABLE',\n 'Cannot encode this value: its %s reader does not implement describe(), so it has no serialisable handle. Back it with a describable reader (a spool/media store) before encoding.',\n 'E_READER_NOT_DESCRIBABLE',\n 422,\n false\n)\n\n/**\n * Thrown when `decode()`-ing a reader handle whose `tag` has no registered resolver.\n *\n * @remarks\n * A reader descriptor's `tag` (e.g. `\"spool:flydrive\"`, `\"media:in-memory\"`) names the resolver that\n * re-binds the handle to a live reader. In-memory and fetch resolvers auto-register when the\n * `@nhtio/adk/batteries/encoding` battery loads; durable-store resolvers (flydrive, OPFS) must be\n * registered by the consumer **with the live `Disk`/OPFS root** before decoding, because the locator\n * carries only the key — not the binding. The single printf argument is the unresolved `tag`.\n *\n * The fix is always the same: call `registerSpoolReaderResolver(tag, …)` /\n * `registerMediaReaderResolver(tag, …)` (re-exported from the encoding battery) at application startup,\n * supplying the same ambient store the bytes were written to.\n *\n * Not fatal — a missing resolver is a wiring condition the caller can correct and retry.\n *\n * @group Primitive Validation\n */\nexport const E_NO_READER_RESOLVER = createException<[string]>(\n 'E_NO_READER_RESOLVER',\n 'No reader resolver registered for tag \"%s\". Register one (with its live store binding) before decoding — see the @nhtio/adk/batteries/encoding battery.',\n 'E_NO_READER_RESOLVER',\n 422,\n false\n)\n\n/**\n * Thrown by {@link @nhtio/adk!Tokenizable} when a DYNAMIC (evaluatable) value's evaluator function fails to\n * produce a usable string at resolve time — either it THREW, or it RETURNED A NON-STRING.\n *\n * @remarks\n * An evaluatable Tokenizable wraps a `(ctx?) => string` that is invoked at prompt-assembly time (and, with\n * no context, at measurement/serialization time). Both failure modes are PROGRAMMER errors, not recoverable\n * runtime conditions: an evaluator that throws is buggy, and a non-string return would otherwise coerce\n * silent garbage into the prompt (`undefined` → \"undefined\", an object → \"[object Object]\"). So we surface\n * loudly rather than degrade — the only sanctioned fallback is the evaluator's OWN `ctx === undefined`\n * branch, which must itself return a string. Inside a runner the throw rides the nack → error seam (a\n * dispatch error / banner); outside a runner it propagates as the real bug it is.\n *\n * The single printf argument describes the failure (\"threw\" or \"returned a non-string (`type`)\"); the\n * original error, when the evaluator threw, is attached on `cause`.\n *\n * @group Primitive Validation\n */\nexport const E_TOKENIZABLE_EVALUATOR_INVALID = createException<[string]>(\n 'E_TOKENIZABLE_EVALUATOR_INVALID',\n 'A dynamic Tokenizable evaluator did not produce a string: %s. The evaluator must return a string for every input (including when the context is undefined), and must not throw.',\n 'E_TOKENIZABLE_EVALUATOR_INVALID',\n 500,\n true\n)\n","import { isInstanceOf } from './guards'\nimport type { TokenEncoding } from '../classes/tokenizable'\n\n/**\n * Ambient channel that lets a leaf token estimator ({@link @nhtio/adk!Tokenizable.estimateTokens} and the\n * primitives that delegate to it) discover whether it is running inside a runner execution — and, if so,\n * surface a non-fatal warning instead of throwing.\n *\n * @remarks\n * **Why this exists.** `estimateTokens(encoding)` takes only an encoding — it is never handed the\n * {@link @nhtio/adk!DispatchContext}. JavaScript closures are lexical, so the runner's context (a\n * different module) is NOT in scope inside the estimator; the estimator cannot check it directly. The\n * behavioural contract we need is:\n *\n * - **inside a TurnRunner run or DispatchRunner dispatch** — a token-estimation failure must DEGRADE to a\n * cheap char-based guesstimate AND emit a `warning` (never kill the turn/dispatch);\n * - **outside those executions** — FAIL LOUD (throw), because a genuine encoder failure in non-runner code\n * is a real bug that must surface.\n *\n * A runner publishes its warn-emit capability here for the duration of its run; the estimator reads\n * {@link currentEstimationWarnEmitter} in its catch — present ⇒ degrade + warn, absent ⇒ throw. The\n * ambient scope IS the definition of \"am I in a runner execution?\".\n *\n * **Stack, not a single slot.** `DispatchRunner.dispatch()` is a public entry point called both standalone\n * AND nested inside `TurnRunner.run()`. A LIFO stack means the innermost active runner wins: a dispatch\n * running inside a turn pushes on top of the turn's emitter, so estimations during the dispatch route to\n * the (richer, dispatch-scoped) emitter, and the turn's is restored when the dispatch returns. \"Prefer the\n * dispatch channel when both are active\" is the stack order, not a special case.\n *\n * **Synchronous by design.** Token estimation is synchronous, so the emitter on top of the stack is always\n * the one for the currently-executing estimation. {@link runWithEstimationWarnings} still restores the\n * stack in a `finally`, so an async runner body that awaits (with no synchronous estimation crossing the\n * await) remains correct: the push/pop bracket the whole body. No `async_hooks` — this runs in the browser\n * bundle too.\n */\nexport interface EstimationWarning {\n /** The encoding whose real tokenizer failed, triggering the degrade. */\n encoding: TokenEncoding\n /** The underlying error thrown by the encoder (surfaced for diagnostics). */\n error: unknown\n /** A short, bounded preview of the text being estimated — never the full value. */\n textPreview: string\n}\n\n/** Sink invoked by the estimator when it degrades inside a runner. */\nexport type EstimationWarnEmitter = (warning: EstimationWarning) => void\n\n// Module-level LIFO of active warn-emit sinks. Empty ⇒ no runner execution is active ⇒ estimators throw.\nconst stack: EstimationWarnEmitter[] = []\n\n/**\n * Run `body` with `emit` published as the active estimation warn-sink, restoring the previous state\n * afterwards. Runners bracket their whole run/dispatch in this so any token estimation performed within\n * (in an executor, a pipeline, a gate) can degrade-and-warn instead of throwing.\n *\n * @param emit - Sink the leaf estimator calls when it degrades; the runner forwards it to its `warning` bus.\n * @param body - The runner's work. May be sync or return a Promise; the sink stays active until it settles.\n * @returns Whatever `body` returns (including a Promise, which is awaited so the `finally` pops after it).\n */\nexport function runWithEstimationWarnings<T>(emit: EstimationWarnEmitter, body: () => T): T {\n stack.push(emit)\n let popped = false\n const pop = (): void => {\n if (popped) return\n popped = true\n // Pop OUR entry specifically (by identity) rather than blindly truncating, so a misuse elsewhere\n // cannot desynchronise the stack.\n const idx = stack.lastIndexOf(emit)\n if (idx !== -1) stack.splice(idx, 1)\n }\n try {\n const result = body()\n // Cross-realm-safe Promise check (bare `instanceof Promise` is fragile across realms — see\n // CONTRIBUTING §Class identity guards). Runner bodies are async, so this is the live path.\n if (isInstanceOf<Promise<unknown>>(result, 'Promise', Promise)) {\n // Keep the sink active until the async body settles, then pop regardless of outcome.\n return result.finally(pop) as unknown as T\n }\n pop()\n return result\n } catch (err) {\n pop()\n throw err\n }\n}\n\n/**\n * The warn-sink for the innermost active runner execution, or `undefined` when none is active. A leaf\n * estimator reads this in its catch: `undefined` is the signal to THROW (outside any runner); a defined\n * sink is the signal to emit a warning and return the char-based guesstimate.\n */\nexport function currentEstimationWarnEmitter(): EstimationWarnEmitter | undefined {\n return stack.length > 0 ? stack[stack.length - 1] : undefined\n}\n","import { getEncoding } from 'js-tiktoken'\nimport { validator } from '@nhtio/validation'\nimport { LlamaTokenizer } from 'llama-tokenizer-js'\nimport { createException } from '../utils/exceptions'\nimport { isInstanceOf, isError } from '../utils/guards'\nimport { ENCODE_METHOD, DECODE_METHOD } from '../utils/encoder_symbols'\nimport { E_TOKENIZABLE_EVALUATOR_INVALID } from '../exceptions/runtime'\nimport { currentEstimationWarnEmitter } from '../utils/estimation_context'\nimport { fromPreTrained as geminiFromPreTrained } from '@lenml/tokenizer-gemini'\nimport type { Tiktoken } from 'js-tiktoken'\nimport type { AdkEncodableSnapshot } from './encodable'\nimport type { DispatchContext } from '../contracts/dispatch_context'\n\n/**\n * A DYNAMIC Tokenizable value: a function evaluated at prompt-ASSEMBLY time with the live dispatch\n * context, so the wrapped content computes itself coherent with the dispatch it ships in (e.g. a\n * citation instruction that adapts to whether the answer tool survived the subtractive-pass shed).\n *\n * @remarks\n * The context is OPTIONAL: the same Tokenizable is also read outside any dispatch (token measurement,\n * serialization, plain string coercion). The evaluator MUST therefore handle `ctx === undefined` and\n * return a string for EVERY input — that no-ctx branch IS its fallback. It must never throw and must\n * never return a non-string; either violation raises {@link @nhtio/adk!E_TOKENIZABLE_EVALUATOR_INVALID}\n * (loud — a mis-authored evaluator must not silently coerce garbage into the prompt). Keep evaluators\n * serializer-friendly (capture only module-level refs or values passed as explicit bindings, NOT live\n * per-turn state) so a dynamic Tokenizable round-trips its evaluator and stays dynamic across encode/decode.\n */\nexport type TokenizableEvaluator = (ctx?: DispatchContext) => string\n\n/**\n * The set of supported token encoding identifiers.\n *\n * @remarks\n * Each value maps to a specific estimation backend:\n * - `gpt2`, `r50k_base`, `p50k_base`, `p50k_edit`, `cl100k_base`, `o200k_base` — exact counts\n * via `js-tiktoken` (OpenAI / tiktoken-compatible models).\n * - `gemini` — exact counts via `@lenml/tokenizer-gemini`, which embeds Gemini's actual\n * SentencePiece vocabulary locally with no API call required.\n * - `gemma` — exact counts for Google's Gemma models (Gemma 2/3/4, incl. the on-device\n * `.litertlm` / ONNX builds). Backed by the SAME `@lenml/tokenizer-gemini` package, whose bundled\n * `tokenizer_config.json` declares `\"tokenizer_class\": \"GemmaTokenizer\"` over the shared 256k-vocab\n * SentencePiece tokenizer — Gemini and Gemma share it, and it encodes Gemma's control tokens\n * (`<start_of_turn>`, `<end_of_turn>`, `<eos>`, …) as single ids. Deliberate reuse, not a proxy: no\n * extra dependency. Distinct identifier so callers can say what model they mean.\n * - `llama2` — exact counts via `llama-tokenizer-js` (Llama 1 and 2). Llama 3+ uses a\n * different vocabulary and should use the `llama3` identifier once a suitable sync backend\n * is available.\n * - `claude` — heuristic approximation using Anthropic's published ~3.5 chars/token ratio.\n * No local tokenizer is available for Claude 3+ models; the Anthropic SDK's\n * `messages.countTokens()` API is the only exact path but requires a network call.\n *\n * This array is the CANONICAL, closed set of backends built into core — adding one of these\n * requires editing core (add a case to {@link Tokenizable.estimateTokens}'s internal switch). For\n * every OTHER encoding a battery or consumer wants to measure (a model-specific tokenizer core has\n * no business knowing about), call {@link registerTokenEstimator} instead — no core edit required.\n * See {@link TokenEncodingId} for the widened identifier type that accepts both.\n */\nexport const TokenEncoding = [\n 'gpt2',\n 'r50k_base',\n 'p50k_base',\n 'p50k_edit',\n 'cl100k_base',\n 'o200k_base',\n 'gemini',\n 'gemma',\n 'llama2',\n 'claude',\n] as const\n\n/**\n * Union of all recognised token encoding identifier strings.\n *\n * @remarks\n * Derived from {@link TokenEncoding} so the type and the runtime array stay in sync\n * automatically when new encodings are added.\n */\nexport type TokenEncoding = (typeof TokenEncoding)[number]\n\n/**\n * A recognised token-encoding identifier: one of the closed {@link TokenEncoding} built-ins, OR any\n * other string registered via {@link registerTokenEstimator}.\n *\n * @remarks\n * The `(string & {})` half of the union is a widening trick, not a real intersection — `string & {}`\n * has no members beyond `string`, so it accepts any string value while `TokenEncoding` still\n * contributes its literal members to editor autocomplete (a bare `string` union member would erase\n * that autocomplete entirely, since TypeScript collapses `TokenEncoding | string` to `string`). Use\n * this type wherever an API accepts \"a built-in encoding, or a custom one\" — including the `tokenEncoding`\n * property on battery adapter options, which treat the built-ins as suggestions but permit any string.\n */\nexport type TokenEncodingId = TokenEncoding | (string & {})\n\n/**\n * A custom token-count function registered for a non-built-in {@link TokenEncodingId} via\n * {@link registerTokenEstimator}.\n *\n * @remarks\n * Synchronous, matching the built-in estimation backends: every backend behind the\n * {@link TokenEncoding} switch (`js-tiktoken`, `@lenml/tokenizer-gemini`, `llama-tokenizer-js`, the\n * Claude heuristic) resolves synchronously, and {@link Tokenizable.estimateTokens} itself returns a\n * plain `number` — not a `Promise<number>`. A custom estimator therefore must not be async either, so\n * a registered encoding stays a drop-in peer of the built-ins (same call shape, no `await` threaded\n * through `estimateTokens` for some encodings and not others). Wrap an inherently-async tokenizer in a\n * synchronous cache (measure ahead of time / memoize a warmed instance) before registering it.\n *\n * @param value - The already-RESOLVED text to count (the same string `countFor` measures for the\n * built-in backends — i.e. `render(ctx)`'s output, never the raw evaluator or ctx).\n * @returns The estimated token count for `value`.\n */\nexport type TokenEstimatorFn = (value: string) => number\n\n/**\n * Thrown by {@link registerTokenEstimator} when the given encoding identifier names a built-in\n * {@link TokenEncoding} rather than a genuinely custom one.\n *\n * @remarks\n * The built-in encodings are canonical: `'gemma'`, `'cl100k_base'`, and friends must always resolve\n * to their core backend (`js-tiktoken`, `@lenml/tokenizer-gemini`, `llama-tokenizer-js`, the Claude\n * heuristic), never to a consumer-supplied override. Allowing a shadow registration would let one\n * battery silently change another's token counts for a shared built-in name — a correctness hazard\n * that is cheap to prevent at registration time. Fatal: this is a programming error in the caller\n * (pick a distinct identifier), not a runtime condition to recover from.\n */\nexport const E_TOKEN_ESTIMATOR_SHADOWS_BUILTIN = createException<[string]>(\n 'E_TOKEN_ESTIMATOR_SHADOWS_BUILTIN',\n 'Cannot register a token estimator for \"%s\": it shadows a built-in TokenEncoding. Built-in encodings always resolve to their core backend and cannot be overridden — register a distinct encoding identifier instead.',\n 'E_TOKEN_ESTIMATOR_SHADOWS_BUILTIN',\n 409,\n true\n)\n\n// Custom encodings registered via registerTokenEstimator, consulted AFTER the built-in switch so the\n// closed set's fast path (and its degrade-vs-throw contract) is never disturbed by registration.\nconst customEstimators = new Map<string, TokenEstimatorFn>()\nconst warnedUnregisteredEncodings = new Set<string>()\n\n// The built-in identifiers as a Set for O(1) shadow-checks and the isBuiltinEncoding guard below.\nconst builtinEncodingSet = new Set<string>(TokenEncoding)\n\n/** Narrows a {@link TokenEncodingId} to the closed {@link TokenEncoding} union when it names a built-in. */\nconst isBuiltinEncoding = (encoding: string): encoding is TokenEncoding =>\n builtinEncodingSet.has(encoding)\n\n/**\n * Register (or replace) a {@link TokenEstimatorFn} for a custom {@link TokenEncodingId}, so\n * {@link Tokenizable.estimateTokens} can measure it without a core code change.\n *\n * @remarks\n * This is the additive escape hatch for the closed {@link TokenEncoding} set. Say a context-management\n * battery needs to measure tokens for a model that core has no built-in backend for — it simply calls\n * this once, at startup, for that model's identifier. From then on the encoding is measurable, with no\n * core code change (a new case in {@link Tokenizable.estimateTokens}'s switch) ever required. Mirrors the\n * {@link @nhtio/adk!registerMediaReaderResolver} / {@link @nhtio/adk!registerSpoolReaderResolver} registry\n * idiom used for reader handles — register a factory once, core (or the primitive) consults it, nobody\n * imports a battery from core.\n *\n * Resolution order inside {@link Tokenizable.estimateTokens}: the built-in switch is tried FIRST (so\n * the closed set's fast path — including its degrade-to-heuristic-on-encoder-failure contract — is\n * completely unaffected by the registry existing), and only an encoding the switch doesn't recognise\n * falls through to this registry.\n *\n * Idempotent-by-overwrite: registering the same `encoding` twice replaces the previous estimator —\n * useful for hot-swapping a warmed tokenizer instance without restarting. Registering a name that\n * shadows a BUILT-IN {@link TokenEncoding} (e.g. `'gemma'`, `'cl100k_base'`) is rejected: the built-ins\n * are canonical and must always resolve to their core backend, never to a consumer override.\n *\n * @param encoding - The custom encoding identifier this estimator handles. Must not be one of the\n * built-in {@link TokenEncoding} values.\n * @param estimator - The synchronous token-count function to call for `encoding`.\n * @throws {@link @nhtio/adk!E_TOKEN_ESTIMATOR_SHADOWS_BUILTIN} when `encoding` names a built-in.\n */\nexport function registerTokenEstimator(encoding: string, estimator: TokenEstimatorFn): void {\n if (isBuiltinEncoding(encoding)) {\n throw new E_TOKEN_ESTIMATOR_SHADOWS_BUILTIN([encoding])\n }\n customEstimators.set(encoding, estimator)\n}\n\n/**\n * Backing schema for {@link Tokenizable.schema}.\n *\n * @remarks\n * Accepts a plain `string` or an existing {@link Tokenizable} instance. Strings pass through\n * unchanged; {@link Tokenizable} instances are accepted via {@link Tokenizable.isTokenizable}\n * to remain cross-realm safe.\n */\nconst stringOrTokenizableSchema = validator.alternatives(\n validator.string(),\n validator.custom((value, helpers) => {\n if (Tokenizable.isTokenizable(value)) {\n return value\n }\n return helpers.error('any.invalid')\n })\n)\n\n/**\n * Backing schema for {@link Tokenizable.emptyableSchema}.\n *\n * @remarks\n * Identical to {@link stringOrTokenizableSchema} except that the EMPTY string is accepted. Joi\n * strings disallow `''` by default, so the strict fragment rejects it while a `new Tokenizable('')`\n * instance sails through the custom branch — an inconsistency that only shows up once a caller\n * legitimately has nothing to put in the field.\n *\n * Deliberately a SEPARATE fragment rather than relaxing the strict one: `Tokenizable.schema` also\n * backs `systemPrompt`, `standingInstructions`, `Identity.representation`, and `Memory.content`,\n * where an empty value is meaningless and should stay a validation error. Opt in per-field.\n */\nconst emptyableStringOrTokenizableSchema = validator.alternatives(\n validator.string().allow(''),\n validator.custom((value, helpers) => {\n if (Tokenizable.isTokenizable(value)) {\n return value\n }\n return helpers.error('any.invalid')\n })\n)\n\n// Lazily-initialised singletons — tokenizers are expensive to load so we defer\n// until first use and reuse across all Tokenizable instances thereafter.\nlet geminiTokenizerInstance: ReturnType<typeof geminiFromPreTrained> | undefined\nlet llamaTokenizerInstance: InstanceType<typeof LlamaTokenizer> | undefined\n\n// js-tiktoken's `getEncoding` has no internal cache — each call does `new Tiktoken(<ranks>)`,\n// parsing the full BPE rank table (~800ms for o200k_base). Building the encoder dwarfs the\n// subsequent `encode()` (~0.6ms) by ~1000×, so a fresh encoder per `estimateTokens` call turns\n// repeated counting (e.g. re-measuring an accumulating dispatch context every iteration) into\n// O(iterations) encoder rebuilds that monopolise a single-threaded host. Cache the encoder per\n// encoding, mirroring the Gemini/Llama singletons above — Tiktoken instances are stateless and\n// safe to reuse across all Tokenizable instances.\nconst tiktokenEncoderInstances = new Map<TokenEncoding, Tiktoken>()\n\nconst getGeminiTokenizer = () => {\n if (!geminiTokenizerInstance) {\n geminiTokenizerInstance = geminiFromPreTrained()\n }\n return geminiTokenizerInstance\n}\n\nconst getLlamaTokenizer = () => {\n if (!llamaTokenizerInstance) {\n llamaTokenizerInstance = new LlamaTokenizer()\n }\n return llamaTokenizerInstance\n}\n\nconst getTiktokenEncoder = (encoding: TokenEncoding): Tiktoken => {\n let enc = tiktokenEncoderInstances.get(encoding)\n if (!enc) {\n enc = getEncoding(encoding as any)\n tiktokenEncoderInstances.set(encoding, enc)\n }\n return enc\n}\n\n/**\n * A mutable string with a built-in token counter.\n *\n * @remarks\n * The wrapped string can be read via the standard coercion protocol and updated at any time via\n * {@link Tokenizable.set}. Token counts are computed lazily on first access per encoding and\n * cached until the value changes, avoiding redundant encoder invocations when the same content\n * is measured multiple times across a pipeline.\n *\n * Estimation is dispatched by encoding identifier — see {@link TokenEncoding} for the full list of\n * built-in backends and their accuracy characteristics, and {@link registerTokenEstimator} for adding\n * more without a core change. An encoding that is neither a built-in nor registered resolves to\n * `undefined` (see {@link Tokenizable.estimateTokens}) — this pre-dates the registry and is unchanged\n * by it. Separately, a built-in encoder that THROWS while measuring (as opposed to an unrecognised\n * name) degrades to a `ceil(length / 3.5)` character heuristic inside a runner execution — see\n * `degradeOrThrow` and `utils/estimation_context`.\n *\n * The class implements the standard JS value-coercion protocol (`toString`, `valueOf`,\n * `toJSON`, `toLocaleString`, `Symbol.for('nodejs.util.inspect.custom')`) so instances behave\n * transparently as strings in most contexts.\n */\nexport class Tokenizable {\n /** The set of supported token-encoding identifiers, re-exposed as a static for convenience. */\n public static TokenEncoding = TokenEncoding\n\n /**\n * Validator schema that accepts a plain `string` or a {@link Tokenizable} instance.\n *\n * @remarks\n * Reusable fragment for any schema that wants to accept either form — for example,\n * `systemPrompt` and each item in `standingInstructions` in `turnContextSchema`.\n */\n public static schema = stringOrTokenizableSchema\n\n /**\n * Variant of {@link Tokenizable.schema} that additionally accepts the EMPTY string.\n *\n * @remarks\n * For fields where \"present but empty\" is a legitimate state rather than a mistake — e.g.\n * {@link @nhtio/adk!Thought.content} in opaque-replay mode, where the meaning lives in the vendor\n * `payload` and the prose is only kept for token-accounting and observer inspection.\n *\n * Do NOT reach for this by default. {@link Tokenizable.schema} stays strict precisely because an\n * empty system prompt or a blank standing instruction is a bug worth failing on.\n */\n public static emptyableSchema = emptyableStringOrTokenizableSchema\n\n declare toJSON: () => string\n declare toString: () => string\n declare valueOf: () => string\n declare toLocaleString: () => string\n /** Replace the wrapped value (string or evaluator) and invalidate the cached token estimates. */\n declare set: (value: string | TokenizableEvaluator) => void\n /**\n * Resolve the wrapped content against an OPTIONAL dispatch context and return the string. For a static\n * value the context is ignored. For a dynamic (evaluatable) value the evaluator is invoked with `ctx`\n * ({@link TokenizableEvaluator}); assembly passes the live context so the content matches the dispatch\n * it ships in, while a no-context call returns the evaluator's `undefined`-branch fallback.\n */\n /** Whether the current wrapped value is evaluator-backed rather than a static string. */\n declare readonly dynamic: boolean\n /** Resolve the value against an optional dispatch context. */\n declare render: (ctx?: DispatchContext) => string\n /**\n * Estimate the token count under the given {@link TokenEncodingId} of the string this Tokenizable\n * resolves to for the OPTIONAL context — i.e. of `render(ctx)`. Passing the same `ctx` assembly uses\n * keeps the budget count honest for dynamic content (it measures exactly what will ship). Accepts\n * both a built-in {@link TokenEncoding} and any encoding registered via {@link registerTokenEstimator}.\n */\n declare estimateTokens: (encoding: TokenEncodingId, ctx?: DispatchContext) => number\n\n // Exactly one of these is set. A static value keeps `#value`; a dynamic value keeps `#evaluator`\n // (and `#value` stays the empty string, never read on the dynamic path).\n #value: string\n #evaluator: TokenizableEvaluator | undefined\n // Per-encoding cache for the STATIC string and the no-ctx (fallback) resolution — both stable.\n #cache: Map<TokenEncodingId, number> = new Map()\n // Per-context cache for DYNAMIC + ctx resolutions: WeakMap<ctxObject, Map<encoding, count>>. A dynamic\n // value resolves differently per ctx, so a single number can't be cached; keying by the ctx object\n // reuses the count across the several measures of one dispatch (subtractive pass + overflow guard) and\n // auto-frees when the ctx is garbage-collected. (Same ctx object ⇒ same resolved string within a\n // dispatch, since the evaluator is a pure read of that ctx's state.)\n #ctxCache: WeakMap<object, Map<TokenEncodingId, number>> = new WeakMap()\n\n /**\n * @param value - The initial value to wrap: a plain `string` (static) or a {@link TokenizableEvaluator}\n * evaluated at assembly time (dynamic).\n */\n constructor(value: string | TokenizableEvaluator) {\n const isFn = typeof value === 'function'\n this.#evaluator = isFn ? (value as TokenizableEvaluator) : undefined\n this.#value = isFn ? '' : (value as string)\n\n // Resolve the wrapped content to a string for an OPTIONAL context. Static → the stored string.\n // Dynamic → invoke the evaluator; a throw OR a non-string return is a programmer bug → raise\n // E_TOKENIZABLE_EVALUATOR_INVALID (loud, no silent coercion, no degrade). The evaluator's own\n // `ctx === undefined` branch is the only sanctioned fallback and must itself return a string.\n const resolve = (ctx?: DispatchContext): string => {\n const fn = this.#evaluator\n if (!fn) return this.#value\n let result: string\n try {\n result = fn(ctx)\n } catch (err) {\n throw new E_TOKENIZABLE_EVALUATOR_INVALID(['the evaluator threw'], {\n cause: isError(err) ? err : new Error(String(err)),\n })\n }\n if (typeof result !== 'string') {\n throw new E_TOKENIZABLE_EVALUATOR_INVALID([`returned a non-string (${typeof result})`])\n }\n return result\n }\n\n // Raw, dependency-free token estimate (~3.5 chars/token) of the RESOLVED text. No encoder, no\n // special-token rules, effectively cannot throw — the guesstimate a real tokenizer degrades TO.\n const estimateTokensRaw = (text: string): number => Math.ceil(text.length / 3.5)\n\n // Shared failure policy for the real tokenizers, enforcing the degrade-vs-throw CONTRACT:\n // - inside a TurnRunner run / DispatchRunner dispatch (an estimation warn-sink is on the ambient\n // stack) → emit a `warning` and DEGRADE to the raw guesstimate, so a token-estimation failure\n // NEVER kills the turn/dispatch;\n // - outside any runner (no sink) → RE-THROW, because a genuine encoder failure in non-runner code is\n // a real bug that must surface (loud), not be silently papered over.\n // This replaces the former `catch → Number.POSITIVE_INFINITY`, which — with the armed overflow guards —\n // made `Infinity > contextWindow` spuriously trip `E_*_CONTEXT_OVERFLOW` on, e.g., text containing a\n // special token. See utils/estimation_context.\n const degradeOrThrow = (encoding: TokenEncoding, text: string, error: unknown): number => {\n const emit = currentEstimationWarnEmitter()\n if (!emit) throw error\n emit({ encoding, error, textPreview: text.slice(0, 80) })\n return estimateTokensRaw(text)\n }\n\n const estimateTokensWithTiktoken = (encoding: TokenEncoding, text: string): number => {\n try {\n const enc: Tiktoken = getTiktokenEncoder(encoding)\n // `encode(text, allowedSpecial, disallowedSpecial)`. js-tiktoken DEFAULTS `disallowedSpecial` to\n // \"all\", so any registered special-token substring in the text (e.g. a doc that mentions\n // `<|endoftext|>`, or model output echoing `<|im_start|>`) makes `encode` THROW\n // (\"The text contains a special token that is not allowed\"). We are ESTIMATING a token count, not\n // round-tripping through the model, so a special-token literal must be counted as ordinary text,\n // never rejected. Pass `disallowedSpecial: []` to disable the guard: specials are BPE-encoded as\n // plain text. Any OTHER encoder failure follows the degrade-vs-throw contract (degradeOrThrow).\n return enc.encode(text, [], []).length\n } catch (err) {\n return degradeOrThrow(encoding, text, err)\n }\n }\n\n const estimateTokensWithGemini = (text: string): number => {\n try {\n return getGeminiTokenizer().encode(text).length\n } catch (err) {\n return degradeOrThrow('gemini', text, err)\n }\n }\n\n // Gemma reuses the very same tokenizer: `@lenml/tokenizer-gemini` bundles the shared 256k-vocab\n // SentencePiece tokenizer whose config is `\"tokenizer_class\": \"GemmaTokenizer\"`. Kept as its own\n // function (rather than folding 'gemma' into the gemini case) so the intent is explicit and a future\n // swap to a dedicated Gemma package is a one-line change here.\n const estimateTokensWithGemma = (text: string): number => {\n try {\n return getGeminiTokenizer().encode(text).length\n } catch (err) {\n return degradeOrThrow('gemma', text, err)\n }\n }\n\n const estimateTokensWithLlama2 = (text: string): number => {\n try {\n return getLlamaTokenizer().encode(text, false).length\n } catch (err) {\n return degradeOrThrow('llama2', text, err)\n }\n }\n\n const estimateTokensWithClaudeHeuristic = (text: string): number => estimateTokensRaw(text)\n\n // Count tokens of an already-RESOLVED string under one of the CLOSED built-in encodings (the\n // switch shared by all built-in callers). Unchanged fast path — `countFor` below only reaches this\n // once it has already narrowed `encoding` to a real {@link TokenEncoding} member.\n const countForBuiltin = (encoding: TokenEncoding, text: string): number => {\n switch (encoding) {\n case 'gpt2':\n case 'r50k_base':\n case 'p50k_base':\n case 'p50k_edit':\n case 'cl100k_base':\n case 'o200k_base':\n return estimateTokensWithTiktoken(encoding, text)\n case 'gemini':\n return estimateTokensWithGemini(text)\n case 'gemma':\n return estimateTokensWithGemma(text)\n case 'llama2':\n return estimateTokensWithLlama2(text)\n case 'claude':\n return estimateTokensWithClaudeHeuristic(text)\n }\n }\n\n // Count tokens of an already-RESOLVED string under any recognised {@link TokenEncodingId}.\n // Resolution order: (1) the built-in switch — completely unchanged, so the closed set's fast path\n // and degrade-vs-throw contract are untouched by the registry existing; (2) the custom-estimator\n // registry, for anything {@link registerTokenEstimator} has registered; (3) the pre-existing\n // fallback path for a truly unrecognised encoding (emits a warning and falls back to the safe\n // 3.5 chars/token heuristic, ensuring overflow math always gets a finite upper-bound estimate).\n const countFor = (encoding: TokenEncodingId, text: string): number => {\n if (isBuiltinEncoding(encoding)) {\n return countForBuiltin(encoding, text)\n }\n const custom = customEstimators.get(encoding)\n if (custom) {\n return custom(text)\n }\n // Unrecognised AND unregistered encodings use the generic character heuristic. Warn once per\n // encoding so callers know the estimate is uncalibrated, while preserving a finite count for\n // context-window arithmetic.\n if (!warnedUnregisteredEncodings.has(encoding)) {\n warnedUnregisteredEncodings.add(encoding)\n console.warn(\n `No token estimator is registered for \"${encoding}\"; using the uncalibrated character heuristic.`\n )\n }\n return text.length\n }\n\n // The standard coercion protocol takes NO argument, so it resolves with no context → the static\n // string, or (dynamic) the evaluator's `undefined`-branch fallback. `render(ctx)` is the explicit,\n // context-aware read that prompt assembly uses.\n const coerce = (): string => resolve(undefined)\n\n Object.defineProperties(this, {\n toJSON: {\n value: coerce,\n enumerable: false,\n configurable: false,\n writable: false,\n },\n toString: {\n value: coerce,\n enumerable: false,\n configurable: false,\n writable: false,\n },\n valueOf: {\n value: coerce,\n enumerable: false,\n configurable: false,\n writable: false,\n },\n toLocaleString: {\n value: coerce,\n enumerable: false,\n configurable: false,\n writable: false,\n },\n [Symbol.for('nodejs.util.inspect.custom')]: {\n value: coerce,\n enumerable: false,\n configurable: false,\n writable: false,\n },\n dynamic: {\n get: () => this.#evaluator !== undefined,\n enumerable: true,\n configurable: false,\n },\n render: {\n value: (ctx?: DispatchContext): string => resolve(ctx),\n enumerable: false,\n configurable: false,\n writable: false,\n },\n set: {\n value: (next: string | TokenizableEvaluator) => {\n const nextIsFn = typeof next === 'function'\n this.#evaluator = nextIsFn ? (next as TokenizableEvaluator) : undefined\n this.#value = nextIsFn ? '' : (next as string)\n this.#cache.clear()\n this.#ctxCache = new WeakMap()\n },\n enumerable: false,\n configurable: false,\n writable: false,\n },\n estimateTokens: {\n value: (encoding: TokenEncodingId, ctx?: DispatchContext): number => {\n // Cache selection: a STATIC value (or a no-ctx resolution — the stable fallback) uses the\n // per-encoding Map; a DYNAMIC value WITH a ctx uses the per-ctx WeakMap (the resolved string\n // varies by ctx, so a single number can't be shared). `ctx === undefined` always hits the\n // stable per-encoding cache regardless of static/dynamic.\n const useCtxCache = this.#evaluator !== undefined && ctx !== undefined\n if (useCtxCache) {\n let m = this.#ctxCache.get(ctx as unknown as object)\n if (m?.has(encoding)) return m.get(encoding)!\n const text = resolve(ctx)\n const est = countFor(encoding, text)\n if (!m) {\n m = new Map()\n this.#ctxCache.set(ctx as unknown as object, m)\n }\n m.set(encoding, est)\n return est\n }\n if (this.#cache.has(encoding)) {\n return this.#cache.get(encoding)!\n }\n const text = resolve(undefined)\n const estimate = countFor(encoding, text)\n this.#cache.set(encoding, estimate)\n return estimate\n },\n enumerable: false,\n configurable: false,\n writable: false,\n },\n })\n }\n\n /**\n * Convenience overload for one-off token counting without managing a {@link Tokenizable} instance.\n *\n * @remarks\n * Creates a temporary instance and immediately discards it — no caching benefit. Use the\n * instance method when you need to count the same value under multiple encodings or when the\n * value may change over time.\n *\n * @param value - The string (or {@link TokenizableEvaluator}) to count tokens for.\n * @param encoding - The encoding identifier to use for counting — a built-in {@link TokenEncoding} or\n * any encoding registered via {@link registerTokenEstimator}.\n * @param ctx - Optional dispatch context; for a dynamic value it selects which resolved string is\n * counted (so the count matches what assembly ships). Ignored for a static string.\n * @returns The estimated number of tokens.\n */\n public static estimateTokens(\n value: string | TokenizableEvaluator,\n encoding: TokenEncodingId,\n ctx?: DispatchContext\n ): number {\n const temp = new Tokenizable(value)\n return temp.estimateTokens(encoding, ctx)\n }\n\n /**\n * Returns `true` if `value` is a {@link Tokenizable} 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 Tokenizable} instance.\n */\n public static isTokenizable(value: unknown): value is Tokenizable {\n return isInstanceOf(value, 'Tokenizable', Tokenizable)\n }\n\n /**\n * Serialise this Tokenizable into an `@nhtio/encoder` snapshot.\n *\n * @remarks\n * The wrapped VALUE is the entire state; the token-count caches are derived and deliberately not encoded\n * (they rebuild lazily after decode). For a STATIC value the snapshot is the string. For a DYNAMIC value\n * the snapshot is the EVALUATOR FUNCTION itself — `@nhtio/encoder` serialises functions (source +\n * explicit bindings), so a dynamic Tokenizable round-trips its evaluator and stays dynamic, re-evaluating\n * live on the next assembly (it does NOT downgrade to a frozen string). Evaluators must therefore stay\n * serializer-friendly: capture only module-level refs / explicit bindings, not live per-turn state.\n * Round-trips via {@link Tokenizable.[DECODE_METHOD]}.\n *\n * @returns The wrapped string, or the evaluator function for a dynamic value.\n */\n [ENCODE_METHOD](): AdkEncodableSnapshot {\n return this.#evaluator ?? this.#value\n }\n\n /**\n * Reconstruct a {@link Tokenizable} from an {@link Tokenizable.[ENCODE_METHOD]} snapshot.\n *\n * @param data - The wrapped string (static) or evaluator function (dynamic) produced by\n * {@link Tokenizable.[ENCODE_METHOD]}.\n * @returns A fresh {@link Tokenizable} over the same value.\n */\n static [DECODE_METHOD](data: AdkEncodableSnapshot): Tokenizable {\n return new Tokenizable(data as string | TokenizableEvaluator)\n }\n}\n\n/**\n * Returns `true` if `value` is a {@link Tokenizable} instance.\n *\n * @remarks\n * Module-level convenience alias for {@link Tokenizable.isTokenizable}. Prefer this form when\n * you need a standalone type guard without importing the full class.\n *\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 Tokenizable} instance.\n */\nexport const isTokenizable = (value: unknown): value is Tokenizable => {\n return isInstanceOf(value, 'Tokenizable', Tokenizable)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAa,gBAA+B,OAAO,IAAI,0BAA0B;;AAGjF,IAAa,gBAA+B,OAAO,IAAI,4BAA4B;;;;;;;;;;;;;;;;ACXnF,IAAa,+BAA+B,gBAC1C,gCACA,8EACA,gCACA,KACA,IACF;;;;;;;;;;;;AAaA,IAAa,yBAAyB,gBACpC,0BACA,uDACA,0BACA,KACA,IACF;;;;;;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OACZ,KAAKA,UAAU,IAAI,KAA0B,CAAC;MAChD;MACA,EAAE,IAAI,UAAU,GAAG;MACnB,OAAO;KACT;KACA,IAAI,KAAKD,OAAO,IAAI,QAAQ,GAC1B,OAAO,KAAKA,OAAO,IAAI,QAAQ;KAGjC,MAAM,WAAW,SAAS,UADb,QAAQ,KAAA,CACe,CAAI;KACxC,KAAKA,OAAO,IAAI,UAAU,QAAQ;KAClC,OAAO;IACT;IACA,YAAY;IACZ,cAAc;IACd,UAAU;GACZ;EACF,CAAC;CACH;;;;;;;;;;;;;;;;CAiBA,OAAc,eACZ,OACA,UACA,KACQ;EAER,OAAO,IADU,YAAY,KACtB,EAAK,eAAe,UAAU,GAAG;CAC1C;;;;;;;;;;;CAYA,OAAc,cAAc,OAAsC;EAChE,OAAO,aAAa,OAAO,eAAe,WAAW;CACvD;;;;;;;;;;;;;;;CAgBA,CAAC,iBAAuC;EACtC,OAAO,KAAKF,cAAc,KAAKC;CACjC;;;;;;;;CASA,QAAQ,eAAe,MAAyC;EAC9D,OAAO,IAAI,YAAY,IAAqC;CAC9D;AACF"}
@@ -1,9 +1,9 @@
1
1
  const require_exceptions = require("./exceptions-DrHnAGQz.cjs");
2
2
  const require_guards = require("./guards-5-XmJgD2.cjs");
3
- const require_tokenizable = require("./tokenizable-DDIdXbJN.cjs");
4
- const require_spooled_artifact = require("./spooled_artifact-BLgbGT8b.cjs");
5
- let uuid = require("uuid");
3
+ const require_tokenizable = require("./tokenizable-BcodRtoW.cjs");
4
+ const require_spooled_artifact = require("./spooled_artifact---DmicFW.cjs");
6
5
  let _nhtio_validation = require("@nhtio/validation");
6
+ let uuid = require("uuid");
7
7
  //#region src/lib/helpers/base64.ts
8
8
  var getBuffer = () => {
9
9
  return globalThis.Buffer;
@@ -758,4 +758,4 @@ Object.defineProperty(exports, "mediaReaderSchema", {
758
758
  }
759
759
  });
760
760
 
761
- //# sourceMappingURL=tool_call-JbjeUpRK.cjs.map
761
+ //# sourceMappingURL=tool_call-B9px4W9k.cjs.map