@nhtio/adk 0.1.0-master-2a4e1bd2 → 0.1.0-master-cd595e6f

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 (413) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/artifact_methods-CJDQ5Lv-.mjs +1 -0
  3. package/artifact_methods-D6k_82r3.js +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 +2 -2
  17. package/batteries/dev-tools.mjs +2 -2
  18. package/batteries/encoding.cjs +7 -7
  19. package/batteries/encoding.mjs +7 -7
  20. package/batteries/generation/gemini/adapter.cjs +1 -1
  21. package/batteries/generation/gemini/adapter.mjs +1 -1
  22. package/batteries/generation/local_diffusion/adapter.cjs +1 -1
  23. package/batteries/generation/local_diffusion/adapter.mjs +1 -1
  24. package/batteries/generation/openai/adapter.cjs +1 -1
  25. package/batteries/generation/openai/adapter.mjs +1 -1
  26. package/batteries/isolation/browser.d.ts +1 -1
  27. package/batteries/isolation/child_process/transport.d.ts +2 -2
  28. package/batteries/isolation/child_process.cjs +4 -4
  29. package/batteries/isolation/child_process.cjs.map +1 -1
  30. package/batteries/isolation/child_process.mjs +4 -4
  31. package/batteries/isolation/child_process.mjs.map +1 -1
  32. package/batteries/isolation/codec.d.ts +2 -2
  33. package/batteries/isolation/crash_policy.d.ts +1 -1
  34. package/batteries/isolation/isolate_function.d.ts +2 -2
  35. package/batteries/isolation/protocol.d.ts +4 -4
  36. package/batteries/isolation/serve.d.ts +2 -2
  37. package/batteries/isolation/types.d.ts +4 -4
  38. package/batteries/isolation.cjs +1 -1
  39. package/batteries/isolation.mjs +1 -1
  40. package/batteries/llm/anthropic_messages/adapter.cjs +6 -6
  41. package/batteries/llm/anthropic_messages/adapter.cjs.map +1 -1
  42. package/batteries/llm/anthropic_messages/adapter.mjs +6 -6
  43. package/batteries/llm/anthropic_messages/adapter.mjs.map +1 -1
  44. package/batteries/llm/anthropic_messages/count_tokens.cjs +1 -1
  45. package/batteries/llm/anthropic_messages/count_tokens.mjs +1 -1
  46. package/batteries/llm/anthropic_messages/helpers.cjs +3 -3
  47. package/batteries/llm/anthropic_messages/helpers.mjs +3 -3
  48. package/batteries/llm/anthropic_messages/types.d.ts +2 -2
  49. package/batteries/llm/anthropic_messages/validation.cjs +3 -3
  50. package/batteries/llm/anthropic_messages/validation.cjs.map +1 -1
  51. package/batteries/llm/anthropic_messages/validation.mjs +3 -3
  52. package/batteries/llm/anthropic_messages/validation.mjs.map +1 -1
  53. package/batteries/llm/anthropic_messages.cjs +2 -2
  54. package/batteries/llm/anthropic_messages.mjs +2 -2
  55. package/batteries/llm/bedrock_converse/adapter.cjs +29 -7
  56. package/batteries/llm/bedrock_converse/adapter.cjs.map +1 -1
  57. package/batteries/llm/bedrock_converse/adapter.mjs +30 -8
  58. package/batteries/llm/bedrock_converse/adapter.mjs.map +1 -1
  59. package/batteries/llm/bedrock_converse/exceptions.cjs +3 -0
  60. package/batteries/llm/bedrock_converse/exceptions.cjs.map +1 -1
  61. package/batteries/llm/bedrock_converse/exceptions.d.ts +6 -0
  62. package/batteries/llm/bedrock_converse/exceptions.mjs +3 -1
  63. package/batteries/llm/bedrock_converse/exceptions.mjs.map +1 -1
  64. package/batteries/llm/bedrock_converse/helpers.cjs +1 -1
  65. package/batteries/llm/bedrock_converse/helpers.mjs +1 -1
  66. package/batteries/llm/bedrock_converse/types.d.ts +6 -2
  67. package/batteries/llm/bedrock_converse/validation.cjs +7 -1
  68. package/batteries/llm/bedrock_converse/validation.cjs.map +1 -1
  69. package/batteries/llm/bedrock_converse/validation.mjs +7 -1
  70. package/batteries/llm/bedrock_converse/validation.mjs.map +1 -1
  71. package/batteries/llm/bedrock_converse.cjs +2 -2
  72. package/batteries/llm/bedrock_converse.mjs +2 -2
  73. package/batteries/llm/claude_code_cli/adapter.cjs +6 -6
  74. package/batteries/llm/claude_code_cli/adapter.cjs.map +1 -1
  75. package/batteries/llm/claude_code_cli/adapter.mjs +6 -6
  76. package/batteries/llm/claude_code_cli/adapter.mjs.map +1 -1
  77. package/batteries/llm/claude_code_cli/helpers.cjs +3 -3
  78. package/batteries/llm/claude_code_cli/helpers.mjs +3 -3
  79. package/batteries/llm/claude_code_cli/types.d.ts +3 -2
  80. package/batteries/llm/claude_code_cli/validation.cjs +3 -3
  81. package/batteries/llm/claude_code_cli/validation.cjs.map +1 -1
  82. package/batteries/llm/claude_code_cli/validation.mjs +3 -3
  83. package/batteries/llm/claude_code_cli/validation.mjs.map +1 -1
  84. package/batteries/llm/claude_code_cli.cjs +1 -1
  85. package/batteries/llm/claude_code_cli.mjs +1 -1
  86. package/batteries/llm/gemini_generate_content/adapter.cjs +29 -7
  87. package/batteries/llm/gemini_generate_content/adapter.cjs.map +1 -1
  88. package/batteries/llm/gemini_generate_content/adapter.mjs +30 -8
  89. package/batteries/llm/gemini_generate_content/adapter.mjs.map +1 -1
  90. package/batteries/llm/gemini_generate_content/exceptions.cjs +3 -0
  91. package/batteries/llm/gemini_generate_content/exceptions.cjs.map +1 -1
  92. package/batteries/llm/gemini_generate_content/exceptions.d.ts +6 -0
  93. package/batteries/llm/gemini_generate_content/exceptions.mjs +3 -1
  94. package/batteries/llm/gemini_generate_content/exceptions.mjs.map +1 -1
  95. package/batteries/llm/gemini_generate_content/helpers.cjs +1 -1
  96. package/batteries/llm/gemini_generate_content/helpers.mjs +1 -1
  97. package/batteries/llm/gemini_generate_content/types.d.ts +7 -3
  98. package/batteries/llm/gemini_generate_content/validation.cjs +11 -2
  99. package/batteries/llm/gemini_generate_content/validation.cjs.map +1 -1
  100. package/batteries/llm/gemini_generate_content/validation.mjs +11 -2
  101. package/batteries/llm/gemini_generate_content/validation.mjs.map +1 -1
  102. package/batteries/llm/gemini_generate_content.cjs +1 -1
  103. package/batteries/llm/gemini_generate_content.mjs +1 -1
  104. package/batteries/llm/litert_lm/adapter.cjs +6 -6
  105. package/batteries/llm/litert_lm/adapter.cjs.map +1 -1
  106. package/batteries/llm/litert_lm/adapter.mjs +6 -6
  107. package/batteries/llm/litert_lm/adapter.mjs.map +1 -1
  108. package/batteries/llm/litert_lm/helpers.cjs +3 -3
  109. package/batteries/llm/litert_lm/helpers.mjs +3 -3
  110. package/batteries/llm/litert_lm/types.d.ts +2 -2
  111. package/batteries/llm/litert_lm/validation.cjs +3 -3
  112. package/batteries/llm/litert_lm/validation.cjs.map +1 -1
  113. package/batteries/llm/litert_lm/validation.mjs +3 -3
  114. package/batteries/llm/litert_lm/validation.mjs.map +1 -1
  115. package/batteries/llm/litert_lm.cjs +1 -1
  116. package/batteries/llm/litert_lm.mjs +1 -1
  117. package/batteries/llm/ollama/adapter.cjs +6 -6
  118. package/batteries/llm/ollama/adapter.cjs.map +1 -1
  119. package/batteries/llm/ollama/adapter.mjs +6 -6
  120. package/batteries/llm/ollama/adapter.mjs.map +1 -1
  121. package/batteries/llm/ollama/helpers.cjs +4 -4
  122. package/batteries/llm/ollama/helpers.mjs +4 -4
  123. package/batteries/llm/ollama/types.d.ts +2 -2
  124. package/batteries/llm/ollama/validation.cjs +3 -3
  125. package/batteries/llm/ollama/validation.cjs.map +1 -1
  126. package/batteries/llm/ollama/validation.mjs +3 -3
  127. package/batteries/llm/ollama/validation.mjs.map +1 -1
  128. package/batteries/llm/ollama.cjs +2 -2
  129. package/batteries/llm/ollama.mjs +2 -2
  130. package/batteries/llm/openai_chat_completions/adapter.cjs +6 -6
  131. package/batteries/llm/openai_chat_completions/adapter.cjs.map +1 -1
  132. package/batteries/llm/openai_chat_completions/adapter.mjs +6 -6
  133. package/batteries/llm/openai_chat_completions/adapter.mjs.map +1 -1
  134. package/batteries/llm/openai_chat_completions/helpers.cjs +4 -4
  135. package/batteries/llm/openai_chat_completions/helpers.mjs +4 -4
  136. package/batteries/llm/openai_chat_completions/types.d.ts +2 -2
  137. package/batteries/llm/openai_chat_completions/validation.cjs +3 -3
  138. package/batteries/llm/openai_chat_completions/validation.cjs.map +1 -1
  139. package/batteries/llm/openai_chat_completions/validation.mjs +3 -3
  140. package/batteries/llm/openai_chat_completions/validation.mjs.map +1 -1
  141. package/batteries/llm/openai_chat_completions.cjs +2 -2
  142. package/batteries/llm/openai_chat_completions.mjs +2 -2
  143. package/batteries/llm/openai_responses/adapter.cjs +6 -6
  144. package/batteries/llm/openai_responses/adapter.cjs.map +1 -1
  145. package/batteries/llm/openai_responses/adapter.mjs +6 -6
  146. package/batteries/llm/openai_responses/adapter.mjs.map +1 -1
  147. package/batteries/llm/openai_responses/helpers.cjs +3 -3
  148. package/batteries/llm/openai_responses/helpers.mjs +3 -3
  149. package/batteries/llm/openai_responses/types.d.ts +2 -2
  150. package/batteries/llm/openai_responses/validation.cjs +3 -3
  151. package/batteries/llm/openai_responses/validation.cjs.map +1 -1
  152. package/batteries/llm/openai_responses/validation.mjs +3 -3
  153. package/batteries/llm/openai_responses/validation.mjs.map +1 -1
  154. package/batteries/llm/openai_responses.cjs +2 -2
  155. package/batteries/llm/openai_responses.mjs +2 -2
  156. package/batteries/llm/transformers_js/adapter.cjs +6 -6
  157. package/batteries/llm/transformers_js/adapter.cjs.map +1 -1
  158. package/batteries/llm/transformers_js/adapter.mjs +6 -6
  159. package/batteries/llm/transformers_js/adapter.mjs.map +1 -1
  160. package/batteries/llm/transformers_js/helpers.cjs +3 -3
  161. package/batteries/llm/transformers_js/helpers.mjs +3 -3
  162. package/batteries/llm/transformers_js/types.d.ts +2 -2
  163. package/batteries/llm/transformers_js/validation.cjs +3 -3
  164. package/batteries/llm/transformers_js/validation.cjs.map +1 -1
  165. package/batteries/llm/transformers_js/validation.mjs +3 -3
  166. package/batteries/llm/transformers_js/validation.mjs.map +1 -1
  167. package/batteries/llm/transformers_js.cjs +1 -1
  168. package/batteries/llm/transformers_js.mjs +1 -1
  169. package/batteries/llm/webllm_chat_completions/adapter.cjs +6 -6
  170. package/batteries/llm/webllm_chat_completions/adapter.cjs.map +1 -1
  171. package/batteries/llm/webllm_chat_completions/adapter.mjs +6 -6
  172. package/batteries/llm/webllm_chat_completions/adapter.mjs.map +1 -1
  173. package/batteries/llm/webllm_chat_completions/helpers.cjs +1 -1
  174. package/batteries/llm/webllm_chat_completions/helpers.mjs +1 -1
  175. package/batteries/llm/webllm_chat_completions/validation.cjs +3 -3
  176. package/batteries/llm/webllm_chat_completions/validation.cjs.map +1 -1
  177. package/batteries/llm/webllm_chat_completions/validation.mjs +3 -3
  178. package/batteries/llm/webllm_chat_completions/validation.mjs.map +1 -1
  179. package/batteries/llm/webllm_chat_completions.cjs +2 -2
  180. package/batteries/llm/webllm_chat_completions.mjs +2 -2
  181. package/batteries/llm.cjs +2 -2
  182. package/batteries/llm.mjs +2 -2
  183. package/batteries/media/builder.d.ts +3 -0
  184. package/batteries/media/contracts.cjs.map +1 -1
  185. package/batteries/media/contracts.d.ts +40 -1
  186. package/batteries/media/contracts.mjs.map +1 -1
  187. package/batteries/media/engines/sharp.cjs +36 -2
  188. package/batteries/media/engines/sharp.cjs.map +1 -1
  189. package/batteries/media/engines/sharp.mjs +36 -2
  190. package/batteries/media/engines/sharp.mjs.map +1 -1
  191. package/batteries/media/forge.cjs +5 -5
  192. package/batteries/media/forge.mjs +5 -5
  193. package/batteries/media/index.d.ts +1 -1
  194. package/batteries/media/lint.cjs +3 -2
  195. package/batteries/media/lint.cjs.map +1 -1
  196. package/batteries/media/lint.mjs +3 -2
  197. package/batteries/media/lint.mjs.map +1 -1
  198. package/batteries/media.cjs +66 -2
  199. package/batteries/media.cjs.map +1 -1
  200. package/batteries/media.mjs +66 -2
  201. package/batteries/media.mjs.map +1 -1
  202. package/batteries/orchestration/conformance.cjs +123 -74
  203. package/batteries/orchestration/conformance.cjs.map +1 -1
  204. package/batteries/orchestration/conformance.d.ts +10 -8
  205. package/batteries/orchestration/conformance.mjs +54 -5
  206. package/batteries/orchestration/conformance.mjs.map +1 -1
  207. package/batteries/orchestration/dispatch_reasoner.cjs +4 -4
  208. package/batteries/orchestration/dispatch_reasoner.mjs +4 -4
  209. package/batteries/orchestration/executor.cjs +2 -2
  210. package/batteries/orchestration/executor.mjs +2 -2
  211. package/batteries/orchestration/forge.cjs +4 -4
  212. package/batteries/orchestration/forge.mjs +4 -4
  213. package/batteries/orchestration/validation.cjs +2 -2
  214. package/batteries/orchestration/validation.mjs +2 -2
  215. package/batteries/orchestration.cjs +4 -4
  216. package/batteries/orchestration.mjs +4 -4
  217. package/batteries/sandbox/contracts/policy_enforcer.d.ts +13 -1
  218. package/batteries/sandbox/js/compartment.d.ts +7 -2
  219. package/batteries/sandbox/js/exceptions.d.ts +4 -0
  220. package/batteries/sandbox/js/runner.d.ts +1 -1
  221. package/batteries/sandbox/js/service.d.ts +1 -1
  222. package/batteries/sandbox/js/ses_contracts.d.ts +4 -3
  223. package/batteries/sandbox/js.cjs +17 -8
  224. package/batteries/sandbox/js.cjs.map +1 -1
  225. package/batteries/sandbox/js.mjs +17 -9
  226. package/batteries/sandbox/js.mjs.map +1 -1
  227. package/batteries/sandbox/manager.d.ts +4 -3
  228. package/batteries/sandbox/node/srt_enforcer.d.ts +1 -1
  229. package/batteries/sandbox/node.cjs +36 -12
  230. package/batteries/sandbox/node.cjs.map +1 -1
  231. package/batteries/sandbox/node.mjs +36 -12
  232. package/batteries/sandbox/node.mjs.map +1 -1
  233. package/batteries/sandbox/tools.cjs +1 -1
  234. package/batteries/sandbox/tools.mjs +1 -1
  235. package/batteries/sandbox/types.d.ts +10 -1
  236. package/batteries/sandbox.cjs +27 -9
  237. package/batteries/sandbox.cjs.map +1 -1
  238. package/batteries/sandbox.mjs +28 -11
  239. package/batteries/sandbox.mjs.map +1 -1
  240. package/batteries/skills.cjs +9 -9
  241. package/batteries/skills.mjs +9 -9
  242. package/batteries/tools/_shared.cjs +1 -1
  243. package/batteries/tools/_shared.mjs +1 -1
  244. package/batteries/tools/color.cjs +2 -2
  245. package/batteries/tools/color.mjs +2 -2
  246. package/batteries/tools/comparison.cjs +2 -2
  247. package/batteries/tools/comparison.mjs +2 -2
  248. package/batteries/tools/data_structure.cjs +2 -2
  249. package/batteries/tools/data_structure.mjs +2 -2
  250. package/batteries/tools/datetime_extended.cjs +3 -3
  251. package/batteries/tools/datetime_extended.mjs +3 -3
  252. package/batteries/tools/datetime_math.cjs +3 -3
  253. package/batteries/tools/datetime_math.mjs +3 -3
  254. package/batteries/tools/encoding.cjs +2 -2
  255. package/batteries/tools/encoding.mjs +2 -2
  256. package/batteries/tools/formatting.cjs +2 -2
  257. package/batteries/tools/formatting.mjs +2 -2
  258. package/batteries/tools/geo_basics.cjs +2 -2
  259. package/batteries/tools/geo_basics.mjs +2 -2
  260. package/batteries/tools/math.cjs +2 -2
  261. package/batteries/tools/math.mjs +2 -2
  262. package/batteries/tools/memory.cjs +5 -5
  263. package/batteries/tools/memory.mjs +5 -5
  264. package/batteries/tools/parsing.cjs +3 -3
  265. package/batteries/tools/parsing.mjs +3 -3
  266. package/batteries/tools/retrievables.cjs +5 -5
  267. package/batteries/tools/retrievables.mjs +5 -5
  268. package/batteries/tools/scrapper.cjs +1 -1
  269. package/batteries/tools/scrapper.mjs +1 -1
  270. package/batteries/tools/searxng.cjs +1 -1
  271. package/batteries/tools/searxng.mjs +1 -1
  272. package/batteries/tools/standing_instructions.cjs +3 -3
  273. package/batteries/tools/standing_instructions.mjs +3 -3
  274. package/batteries/tools/statistics.cjs +3 -3
  275. package/batteries/tools/statistics.mjs +3 -3
  276. package/batteries/tools/string_processing.cjs +2 -2
  277. package/batteries/tools/string_processing.mjs +2 -2
  278. package/batteries/tools/structured_data.cjs +2 -2
  279. package/batteries/tools/structured_data.mjs +2 -2
  280. package/batteries/tools/text_analysis.cjs +3 -3
  281. package/batteries/tools/text_analysis.mjs +3 -3
  282. package/batteries/tools/text_comparison.cjs +2 -2
  283. package/batteries/tools/text_comparison.mjs +2 -2
  284. package/batteries/tools/time.cjs +3 -3
  285. package/batteries/tools/time.mjs +3 -3
  286. package/batteries/tools/unit_conversion.cjs +2 -2
  287. package/batteries/tools/unit_conversion.mjs +2 -2
  288. package/batteries/tools.cjs +2 -2
  289. package/batteries/tools.mjs +2 -2
  290. package/batteries/validation.cjs +5 -5
  291. package/batteries/validation.mjs +5 -5
  292. package/batteries/vector/conformance/index.d.ts +11 -16
  293. package/batteries/vector/conformance.cjs +107 -36
  294. package/batteries/vector/conformance.cjs.map +1 -1
  295. package/batteries/vector/conformance.mjs +84 -13
  296. package/batteries/vector/conformance.mjs.map +1 -1
  297. package/batteries/vector/retrievable.cjs +1 -1
  298. package/batteries/vector/retrievable.mjs +1 -1
  299. package/batteries.cjs +5 -5
  300. package/batteries.mjs +5 -5
  301. package/{chat_common-DbbIESdo.mjs → chat_common-CmKV5Dz4.mjs} +2 -2
  302. package/{chat_common-DbbIESdo.mjs.map → chat_common-CmKV5Dz4.mjs.map} +1 -1
  303. package/{chat_common-B3O3zz-i.js → chat_common-Dpan9moo.js} +2 -2
  304. package/{chat_common-B3O3zz-i.js.map → chat_common-Dpan9moo.js.map} +1 -1
  305. package/{common-v9Jo9M5k.mjs → common-BpdHIpQE.mjs} +7 -7
  306. package/{common-v9Jo9M5k.mjs.map → common-BpdHIpQE.mjs.map} +1 -1
  307. package/{common-BV3HGeLj.js → common-H44Ik9ou.js} +7 -7
  308. package/{common-BV3HGeLj.js.map → common-H44Ik9ou.js.map} +1 -1
  309. package/common.cjs +7 -7
  310. package/common.mjs +7 -7
  311. package/{dispatch_runner-CbNyqSMy.mjs → dispatch_runner-BZDXUe0G.mjs} +5 -5
  312. package/{dispatch_runner-CbNyqSMy.mjs.map → dispatch_runner-BZDXUe0G.mjs.map} +1 -1
  313. package/{dispatch_runner-Bl3Xwebu.js → dispatch_runner-CKhm-scw.js} +5 -5
  314. package/{dispatch_runner-Bl3Xwebu.js.map → dispatch_runner-CKhm-scw.js.map} +1 -1
  315. package/dispatch_runner.cjs +1 -1
  316. package/dispatch_runner.mjs +1 -1
  317. package/{ecmascript-BSnvyY8T.js → ecmascript-CCtgamDh.js} +3 -3
  318. package/{ecmascript-BSnvyY8T.js.map → ecmascript-CCtgamDh.js.map} +1 -1
  319. package/{ecmascript-CZ7_YKfZ.mjs → ecmascript-DcmUQ9Jx.mjs} +3 -3
  320. package/{ecmascript-CZ7_YKfZ.mjs.map → ecmascript-DcmUQ9Jx.mjs.map} +1 -1
  321. package/eslint.cjs +1 -1
  322. package/eslint.mjs +1 -1
  323. package/exceptions.cjs +1 -1
  324. package/exceptions.mjs +1 -1
  325. package/forge.cjs +2 -2
  326. package/forge.mjs +2 -2
  327. package/guards.cjs +7 -7
  328. package/guards.mjs +7 -7
  329. package/{helpers-CDmLDBq5.mjs → helpers-BH7HTtkD.mjs} +3 -3
  330. package/{helpers-CDmLDBq5.mjs.map → helpers-BH7HTtkD.mjs.map} +1 -1
  331. package/{helpers-Tvvwpx1M.js → helpers-CEjjkXso.js} +3 -3
  332. package/{helpers-Tvvwpx1M.js.map → helpers-CEjjkXso.js.map} +1 -1
  333. package/index.cjs +10 -10
  334. package/index.mjs +10 -10
  335. package/{isolation-BQCTQYZ_.js → isolation-7Jrcucgc.js} +11 -11
  336. package/isolation-7Jrcucgc.js.map +1 -0
  337. package/{isolation-7xbkc12r.mjs → isolation-CO0NiK8R.mjs} +11 -11
  338. package/isolation-CO0NiK8R.mjs.map +1 -0
  339. package/lib/classes/tokenizable.d.ts +2 -3
  340. package/mcp/adk-docs-corpus.json +2 -2
  341. package/package.json +469 -469
  342. package/{retrievable-C5dXuDhD.js → retrievable-BTwjmPnl.js} +3 -3
  343. package/{retrievable-C5dXuDhD.js.map → retrievable-BTwjmPnl.js.map} +1 -1
  344. package/{retrievable-gl_TIHnX.mjs → retrievable-CXTAUuuv.mjs} +3 -3
  345. package/{retrievable-gl_TIHnX.mjs.map → retrievable-CXTAUuuv.mjs.map} +1 -1
  346. package/{scrapper-DD6-_2u-.js → scrapper-CJexXXK-.js} +4 -4
  347. package/{scrapper-DD6-_2u-.js.map → scrapper-CJexXXK-.js.map} +1 -1
  348. package/{scrapper-u_orpxIB.mjs → scrapper-DiQ5FfDL.mjs} +4 -4
  349. package/{scrapper-u_orpxIB.mjs.map → scrapper-DiQ5FfDL.mjs.map} +1 -1
  350. package/{searxng-fVdJUCK2.mjs → searxng-BFTJ6rTE.mjs} +4 -4
  351. package/{searxng-fVdJUCK2.mjs.map → searxng-BFTJ6rTE.mjs.map} +1 -1
  352. package/{searxng-C7GK0Nrz.js → searxng-DzlGZG4V.js} +4 -4
  353. package/{searxng-C7GK0Nrz.js.map → searxng-DzlGZG4V.js.map} +1 -1
  354. package/server.json +2 -2
  355. package/skills/adk-assembly/SKILL.md +2 -2
  356. package/{spooled_artifact-DriNQRj7.js → spooled_artifact-BpcesRBv.js} +384 -384
  357. package/spooled_artifact-BpcesRBv.js.map +1 -0
  358. package/{spooled_artifact-BkueYJhR.mjs → spooled_artifact-Bw_7swIp.mjs} +385 -385
  359. package/spooled_artifact-Bw_7swIp.mjs.map +1 -0
  360. package/spooled_artifact.cjs +2 -2
  361. package/spooled_artifact.mjs +2 -2
  362. package/{spooled_markdown_artifact-CfHRZUkl.mjs → spooled_markdown_artifact-vd6eNtIP.mjs} +3 -3
  363. package/{spooled_markdown_artifact-CfHRZUkl.mjs.map → spooled_markdown_artifact-vd6eNtIP.mjs.map} +1 -1
  364. package/{spooled_markdown_artifact-C_VkCDhF.js → spooled_markdown_artifact-wJPnE8Ij.js} +3 -3
  365. package/{spooled_markdown_artifact-C_VkCDhF.js.map → spooled_markdown_artifact-wJPnE8Ij.js.map} +1 -1
  366. package/{thought-B8JAi3-W.mjs → thought-BE1KGEhV.mjs} +3 -3
  367. package/{thought-B8JAi3-W.mjs.map → thought-BE1KGEhV.mjs.map} +1 -1
  368. package/{thought--fRgOwTP.js → thought-bS7O9O5H.js} +3 -3
  369. package/{thought--fRgOwTP.js.map → thought-bS7O9O5H.js.map} +1 -1
  370. package/{tokenizable-CWW7iSrD.js → tokenizable-BMZuGWRd.js} +35 -29
  371. package/tokenizable-BMZuGWRd.js.map +1 -0
  372. package/{tokenizable-DLMP68ZV.mjs → tokenizable-VB4Av8GF.mjs} +36 -30
  373. package/tokenizable-VB4Av8GF.mjs.map +1 -0
  374. package/{tool_call-CPjyvkm4.mjs → tool_call-Cfaj-6zK.mjs} +4 -4
  375. package/{tool_call-CPjyvkm4.mjs.map → tool_call-Cfaj-6zK.mjs.map} +1 -1
  376. package/{tool_call-DgqVwL5n.js → tool_call-Fs_Uh5wQ.js} +4 -4
  377. package/{tool_call-DgqVwL5n.js.map → tool_call-Fs_Uh5wQ.js.map} +1 -1
  378. package/{tools-BmLzkvNr.mjs → tools-B3_8C78Q.mjs} +6 -6
  379. package/{tools-BmLzkvNr.mjs.map → tools-B3_8C78Q.mjs.map} +1 -1
  380. package/{tools-DmcIe2Cb.js → tools-CqOcmHR8.js} +6 -6
  381. package/{tools-DmcIe2Cb.js.map → tools-CqOcmHR8.js.map} +1 -1
  382. package/{toon-BvTQsKdN.mjs → toon-BSlr88px.mjs} +5 -5
  383. package/{toon-BvTQsKdN.mjs.map → toon-BSlr88px.mjs.map} +1 -1
  384. package/{toon-B05eKx-q.js → toon-D71tkyI3.js} +5 -5
  385. package/{toon-B05eKx-q.js.map → toon-D71tkyI3.js.map} +1 -1
  386. package/{turn_runner-DEGCvfVZ.mjs → turn_runner-BHHD6h77.mjs} +5 -5
  387. package/{turn_runner-DEGCvfVZ.mjs.map → turn_runner-BHHD6h77.mjs.map} +1 -1
  388. package/{turn_runner-DT8TseR4.js → turn_runner-DhLI7OTH.js} +5 -5
  389. package/{turn_runner-DT8TseR4.js.map → turn_runner-DhLI7OTH.js.map} +1 -1
  390. package/turn_runner.cjs +1 -1
  391. package/turn_runner.mjs +1 -1
  392. package/types-D6X_aUIb.mjs.map +1 -1
  393. package/types-DrSosVaM.js.map +1 -1
  394. package/{validate-lzy9nG_E.mjs → validate-Bi7FGjoq.mjs} +13 -1
  395. package/{validate-lzy9nG_E.mjs.map → validate-Bi7FGjoq.mjs.map} +1 -1
  396. package/{validate-CdOS7S2u.js → validate-CkQI-48O.js} +13 -1
  397. package/{validate-CdOS7S2u.js.map → validate-CkQI-48O.js.map} +1 -1
  398. package/{xml-DDTIMpY3.js → xml-BeNvlifb.js} +5 -5
  399. package/{xml-DDTIMpY3.js.map → xml-BeNvlifb.js.map} +1 -1
  400. package/{xml-VhJ4NrMB.mjs → xml-vyCZZiF_.mjs} +5 -5
  401. package/{xml-VhJ4NrMB.mjs.map → xml-vyCZZiF_.mjs.map} +1 -1
  402. package/{yaml-Cx16IYJq.js → yaml-DhLLa2cj.js} +5 -5
  403. package/{yaml-Cx16IYJq.js.map → yaml-DhLLa2cj.js.map} +1 -1
  404. package/{yaml-Du4wFGzL.mjs → yaml-Dtz0Bd7J.mjs} +5 -5
  405. package/{yaml-Du4wFGzL.mjs.map → yaml-Dtz0Bd7J.mjs.map} +1 -1
  406. package/artifact_methods-BMCahBLn.mjs +0 -1
  407. package/artifact_methods-f_bSy4kX.js +0 -1
  408. package/isolation-7xbkc12r.mjs.map +0 -1
  409. package/isolation-BQCTQYZ_.js.map +0 -1
  410. package/spooled_artifact-BkueYJhR.mjs.map +0 -1
  411. package/spooled_artifact-DriNQRj7.js.map +0 -1
  412. package/tokenizable-CWW7iSrD.js.map +0 -1
  413. package/tokenizable-DLMP68ZV.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.cjs","names":["#baseline"],"sources":["../../../../src/batteries/llm/claude_code_cli/adapter.ts"],"sourcesContent":["/**\n * Cross-environment executor adapter that wraps the Claude Code CLI as a `DispatchExecutorFn`\n * destination.\n *\n * @module @nhtio/adk/batteries/llm/claude_code_cli/adapter\n *\n * @remarks\n * The first battery in the \"CLI harness\" family: rather than a direct wire-format provider, this\n * adapter drives an external coding-agent CLI binary that is itself a complete agent loop. Since a\n * subprocess must be spawned anyway, ALL Claude-Code-specific complexity — spawning the real\n * `claude` binary, hosting an MCP bridge server, translating its stream-json — lives in a\n * dedicated wrapper process (`wrapper.ts`, shipped as a sibling dist asset); this adapter only\n * ever spawns and drives that wrapper over the small, harness-agnostic protocol in `./wire`.\n *\n * Every dispatch iteration is stateless and self-contained: the full accumulated history renders\n * into one `-p` prompt string (`buildClaudeCodeCliPrompt`), a fresh wrapper is spawned, and real\n * ADK tools are bridged into the CLI's own tool loop via MCP — but actual execution always happens\n * on the ADK side, through `tool.executor(ctx)(args)`, exactly like every other LLM battery.\n */\n\nimport { sha256 } from 'js-sha256'\nimport { validateOptions } from './validation'\nimport { isError, isObject, isInstanceOf } from '@nhtio/adk/guards'\nimport { createNdjsonLineReader, encodeWrapperCommand } from './wire'\nimport { canonicalStringify } from '../../../lib/utils/canonical_json'\nimport { InMemorySpoolStore } from '@nhtio/adk/batteries/storage/in_memory'\nimport {\n Tokenizable,\n ToolCall,\n Memory,\n Message,\n Media,\n ArtifactTool,\n SpooledArtifact,\n TokenEncoding,\n} from '@nhtio/adk/common'\nimport {\n E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR,\n E_CLAUDE_CODE_CLI_WRAPPER_CRASHED,\n E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO,\n E_CLAUDE_CODE_CLI_STREAM_STALLED,\n E_CLAUDE_CODE_CLI_STARTUP_TIMEOUT,\n E_CLAUDE_CODE_CLI_MCP_BRIDGE_STARTUP_FAILED,\n E_CLAUDE_CODE_CLI_TURN_FAILED,\n E_INVALID_CLAUDE_CODE_CLI_OPTIONS,\n E_CLAUDE_CODE_CLI_CONTEXT_OVERFLOW,\n} from './exceptions'\nimport {\n defaultDescriptionToChatCompletionsJsonSchema,\n defaultRenderUntrustedContent,\n defaultRenderTrustedContent,\n defaultRenderStandingInstructions,\n defaultRenderMemories,\n defaultRenderRetrievables,\n defaultRenderRetrievableHandleBody,\n defaultRenderRetrievableSafetyDirective,\n defaultRenderFirstPartyRetrievables,\n defaultRenderThirdPartyPublicRetrievables,\n defaultRenderThirdPartyPrivateRetrievables,\n defaultRenderThought,\n defaultFilterThoughts,\n defaultToolsToChatCompletionsTools,\n defaultRenderChatCompletionsSystemPrompt,\n defaultRenderClaudeCodeCliTimelineMessage,\n defaultRenderClaudeCodeCliToolCallResult,\n defaultBuildClaudeCodeCliPrompt,\n renderArtifactHandleBody,\n looksLikeSpooledArtifact,\n} from './helpers'\nimport type { Tool } from '@nhtio/adk/common'\nimport type { SpoolStore } from '@nhtio/adk/common'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type { WrapperEvent, WrapperCommand, WrapperBridgedTool } from './wire'\nimport type { DispatchExecutorFn, DispatchExecutorHelpers } from '@nhtio/adk/dispatch_runner'\nimport type {\n ClaudeCodeCliAdapterOptions,\n ClaudeCodeCliHelpers,\n ExecaLike,\n ExecaResolver,\n UnsupportedMediaPolicy,\n} from './types'\n\ntype OutboundContentBlock =\n | { type: 'text'; text: string }\n | { type: 'image'; data: string; mimeType: string }\n\n// ─── wrapper path resolution (Decision C) ──────────────────────────────────────\n\n/**\n * Resolve the built wrapper asset's on-disk path relative to this module's own compiled location.\n * `adapter.ts` carries its own `@module` tag (per the per-file tagging convention every other\n * multi-file battery uses), so it compiles to `dist/batteries/llm/claude_code_cli/adapter.mjs` —\n * three directories below the package root, where the wrapper (an explicit, un-tagged\n * `vite.config.mts` entry key) compiles to `dist/claude-code-cli-wrapper.mjs`.\n */\nexport const resolveDefaultWrapperPath = (): string => {\n // `typeof require === 'function'` alone is not a safe CJS-vs-ESM discriminator: rolldown's ESM\n // output wraps `require` in a shim/Proxy (falling back to itself when the real `require` is\n // absent) that still reports `typeof === 'function'`, but whose `.resolve` is not itself a\n // function — calling it throws instead of falling through to the URL-based ESM branch below.\n if (typeof require === 'function' && typeof require.resolve === 'function') {\n return require.resolve('../../../claude-code-cli-wrapper.cjs')\n }\n // `URL.pathname` is percent-encoded — a real install path containing a space, unicode, or any\n // other URL-reserved character would produce a non-existent argv path (e.g. `%20` instead of a\n // literal space) once handed to `execaFn`/`spawn` below. `decodeURIComponent` undoes that percent\n // encoding to recover the native filesystem path — equivalent to `node:url`'s `fileURLToPath` for\n // a POSIX path (verified directly), which this module avoids importing at module scope: this\n // file is transitively pulled into the browser test project via `src/batteries`'s barrel (e.g.\n // `tests/unit/batteries/index.cross.spec.ts`), and Vite externalizes `node:url` there, throwing\n // on any access to `fileURLToPath` at import time. This battery is POSIX-only in v1 anyway\n // (validated at options-construction time), so a POSIX-only decode is exactly the right amount\n // of `node:url` behavior to reimplement without importing it.\n return decodeURIComponent(\n new URL('../../../claude-code-cli-wrapper.mjs', import.meta.url).pathname\n )\n}\n\n// ─── execa resolution (mirrors execa_executor.ts's lazy-resolver pattern) ──────\n\nconst resolveExeca = async (supplied: ExecaResolver | undefined): Promise<ExecaLike> => {\n let value: unknown =\n supplied ?? (() => import('execa') as unknown as Promise<{ execa: ExecaLike }>)\n if (typeof value === 'function' && !('exec' in (value as object))) {\n try {\n value = await (value as () => unknown)()\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n throw new E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR([\n `execa resolver failed: ${detail} — install the optional peer dependency \"execa\" or supply your own`,\n ])\n }\n }\n if (isObject(value) && 'execa' in value) {\n value = (value as { execa: unknown }).execa\n }\n if (typeof value !== 'function') {\n throw new E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR([\n 'execa resolver did not resolve to a function',\n ])\n }\n return value as ExecaLike\n}\n\n// ─── option merging ─────────────────────────────────────────────────────────\n\nconst mergeRecord = <T extends Record<string, unknown>>(\n layers: ReadonlyArray<T | undefined>\n): T | undefined => {\n let merged: T | undefined\n for (const layer of layers) {\n if (!layer) continue\n merged = { ...(merged ?? ({} as T)), ...layer }\n }\n return merged\n}\n\nconst mergeOptions = (\n baseline: ClaudeCodeCliAdapterOptions,\n exec: Partial<ClaudeCodeCliAdapterOptions> | undefined,\n stash: Partial<ClaudeCodeCliAdapterOptions> | undefined\n): Partial<ClaudeCodeCliAdapterOptions> => {\n const layers = [baseline as Partial<ClaudeCodeCliAdapterOptions>, exec ?? {}, stash ?? {}]\n const out: Record<string, unknown> = {}\n for (const layer of layers) {\n for (const [k, v] of Object.entries(layer)) {\n if (v === undefined) continue\n if (k === 'helpers') continue\n out[k] = v\n }\n }\n const helpers = mergeRecord(layers.map((l) => l.helpers as Record<string, unknown> | undefined))\n if (helpers !== undefined) out.helpers = helpers\n return out as Partial<ClaudeCodeCliAdapterOptions>\n}\n\nconst resolveHelpers = (\n overrides: Partial<ClaudeCodeCliHelpers> | undefined\n): ClaudeCodeCliHelpers => {\n const src = overrides ?? {}\n return {\n descriptionToChatCompletionsJsonSchema:\n src.descriptionToChatCompletionsJsonSchema ?? defaultDescriptionToChatCompletionsJsonSchema,\n renderUntrustedContent: src.renderUntrustedContent ?? defaultRenderUntrustedContent,\n renderTrustedContent: src.renderTrustedContent ?? defaultRenderTrustedContent,\n renderStandingInstructions: src.renderStandingInstructions ?? defaultRenderStandingInstructions,\n renderMemories: src.renderMemories ?? defaultRenderMemories,\n renderRetrievables: src.renderRetrievables ?? defaultRenderRetrievables,\n renderRetrievableHandleBody:\n src.renderRetrievableHandleBody ?? defaultRenderRetrievableHandleBody,\n renderRetrievableSafetyDirective:\n src.renderRetrievableSafetyDirective ?? defaultRenderRetrievableSafetyDirective,\n renderFirstPartyRetrievables:\n src.renderFirstPartyRetrievables ?? defaultRenderFirstPartyRetrievables,\n renderThirdPartyPublicRetrievables:\n src.renderThirdPartyPublicRetrievables ?? defaultRenderThirdPartyPublicRetrievables,\n renderThirdPartyPrivateRetrievables:\n src.renderThirdPartyPrivateRetrievables ?? defaultRenderThirdPartyPrivateRetrievables,\n renderThought: src.renderThought ?? defaultRenderThought,\n filterThoughts: src.filterThoughts ?? defaultFilterThoughts,\n toolsToChatCompletionsTools:\n src.toolsToChatCompletionsTools ?? defaultToolsToChatCompletionsTools,\n renderChatCompletionsSystemPrompt:\n src.renderChatCompletionsSystemPrompt ?? defaultRenderChatCompletionsSystemPrompt,\n renderClaudeCodeCliTimelineMessage:\n src.renderClaudeCodeCliTimelineMessage ?? defaultRenderClaudeCodeCliTimelineMessage,\n renderClaudeCodeCliToolCallResult:\n src.renderClaudeCodeCliToolCallResult ?? defaultRenderClaudeCodeCliToolCallResult,\n buildClaudeCodeCliPrompt: src.buildClaudeCodeCliPrompt ?? defaultBuildClaudeCodeCliPrompt,\n }\n}\n\nconst estimateTokensOf = async (\n value: { estimateTokens: (encoding: TokenEncoding) => number | Promise<number> },\n encoding: TokenEncoding\n): Promise<number> => Promise.resolve(value.estimateTokens(encoding))\n\n// ─── time / checksum helpers ────────────────────────────────────────────────\n\nconst nowIso = (): string => new Date().toISOString()\n\n/**\n * Integrity checksum over `tool`/`args` — matches every other LLM battery's convention\n * (`sha256(canonicalStringify({tool, args}))`, see `ollama/adapter.ts`'s `computeChecksum`), NOT\n * the per-call `requestId`. Identical repeat calls must share this checksum: it feeds\n * `DispatchContext`'s own `#toolCallChecksums` loop-detection counter and cross-bus correlation,\n * neither of which can see a repeat if every call gets a unique value.\n */\nconst computeChecksum = (tool: string, args: unknown): string =>\n sha256(canonicalStringify({ tool, args }))\n\n// ─── outbound tool-result rendering (decision 8) ───────────────────────────────\n\nconst renderMediaListAsOutbound = async (\n mediaList: Media[],\n unsupportedResultMediaPolicy: UnsupportedMediaPolicy\n): Promise<{ content: OutboundContentBlock[]; isError: boolean }> => {\n const content: OutboundContentBlock[] = []\n let anyUnsupported = false\n for (const media of mediaList) {\n if (media.kind === 'image') {\n content.push({ type: 'image', data: await media.asBase64(), mimeType: media.mimeType })\n continue\n }\n // Every non-image modality is unsupported on the outbound MCP wire (only text/image content\n // blocks exist there) — routed through the SAME policy family the inbound direction uses\n // (decision 8), rather than an unconditional hardcoded error.\n if (unsupportedResultMediaPolicy === 'throw') {\n anyUnsupported = true\n content.push({\n type: 'text',\n text: `Unsupported result media modality: ${media.kind} (${media.mimeType})`,\n })\n continue\n }\n const byteLen = await media.byteLength().catch(() => undefined)\n content.push({\n type: 'text',\n text: `[media: ${media.filename}, ${media.mimeType}, ${byteLen ?? 'unknown'} bytes]`,\n })\n }\n return { content, isError: anyUnsupported }\n}\n\nconst renderOutboundResult = async (input: {\n raw: string | Uint8Array | SpooledArtifact | Media | Media[]\n callId: string\n inline: boolean\n spoolStore: SpoolStore\n unsupportedResultMediaPolicy: UnsupportedMediaPolicy\n}): Promise<{ content: OutboundContentBlock[]; isError: boolean }> => {\n const { raw, callId, inline } = input\n\n if (Media.isMedia(raw)) {\n return renderMediaListAsOutbound([raw], input.unsupportedResultMediaPolicy)\n }\n if (Array.isArray(raw) && raw.length > 0 && raw.every((m) => Media.isMedia(m))) {\n return renderMediaListAsOutbound(raw, input.unsupportedResultMediaPolicy)\n }\n if (looksLikeSpooledArtifact(raw)) {\n const artifact = raw as SpooledArtifact\n if (inline === false) {\n let byteLength = 0\n let lineCount = 0\n try {\n byteLength = await artifact.byteLength()\n } catch {\n byteLength = 0\n }\n try {\n lineCount = await artifact.lineCount()\n } catch {\n lineCount = 0\n }\n const body = renderArtifactHandleBody({ callId, artifact, byteLength, lineCount })\n return { content: [{ type: 'text', text: body }], isError: false }\n }\n const text = await artifact.asString()\n return { content: [{ type: 'text', text }], isError: false }\n }\n if (typeof raw === 'string') {\n return { content: [{ type: 'text', text: raw }], isError: false }\n }\n if (isInstanceOf(raw, 'Uint8Array', Uint8Array)) {\n await input.spoolStore.write(callId, raw)\n return {\n content: [{ type: 'text', text: '[binary tool result — see history for details]' }],\n isError: false,\n }\n }\n return { content: [{ type: 'text', text: String(raw) }], isError: false }\n}\n\n// ─── the adapter ────────────────────────────────────────────────────────────\n\n/**\n * Opinionated CLI-harness LLM adapter that drives the Claude Code CLI as a `DispatchExecutorFn`\n * destination.\n *\n * @remarks\n * Construction validates options eagerly via {@link validateOptions} and throws\n * {@link @nhtio/adk/batteries/llm/claude_code_cli!E_INVALID_CLAUDE_CODE_CLI_OPTIONS} on failure\n * (including the POSIX-only platform guard and the `apiKey`/`authToken` XOR check). The returned\n * instance is reusable: call {@link ClaudeCodeCliAdapter.executor} once per `DispatchRunner`\n * configuration.\n */\nexport class ClaudeCodeCliAdapter {\n /** Customary key for per-iteration overrides on `ctx.stash`. */\n public static readonly STASH_KEY = 'claudeCodeCli' as const\n\n readonly #baseline: ClaudeCodeCliAdapterOptions\n\n /**\n * @param options - Constructor-baseline options. Re-validated on every iteration after\n * per-dispatch and per-iteration overrides are layered in.\n * @throws {@link @nhtio/adk/batteries/llm/claude_code_cli!E_INVALID_CLAUDE_CODE_CLI_OPTIONS} when\n * `options` does not satisfy `claudeCodeCliOptionsSchema`.\n */\n constructor(options: unknown) {\n this.#baseline = validateOptions(options)\n }\n\n /**\n * Returns a {@link @nhtio/adk!DispatchExecutorFn} bound to this adapter's baseline plus optional\n * executor-scope overrides.\n */\n executor(overrides?: Partial<ClaudeCodeCliAdapterOptions>): DispatchExecutorFn {\n const baseline = this.#baseline\n const adapterClass = ClaudeCodeCliAdapter\n\n return async (ctx: DispatchContext, helpers: DispatchExecutorHelpers): Promise<void> => {\n const localWarn = (msg: string): void => {\n helpers.log.warn({ kind: 'helper-warning', message: msg })\n }\n\n // ── Step 1: merge & validate ──────────────────────────────────────────\n const stashRaw = ctx.stash.get(adapterClass.STASH_KEY, {}) as unknown\n const stashOverrides =\n stashRaw && typeof stashRaw === 'object'\n ? (stashRaw as Partial<ClaudeCodeCliAdapterOptions>)\n : {}\n const merged = validateOptions(mergeOptions(baseline, overrides, stashOverrides))\n\n if (merged.tokenEncoding !== null && merged.contextWindow === undefined) {\n throw new E_INVALID_CLAUDE_CODE_CLI_OPTIONS([\n 'tokenEncoding is non-null but contextWindow is undefined',\n ])\n }\n\n // ── Step 2: resolve helpers ───────────────────────────────────────────\n const resolvedHelpers = resolveHelpers(merged.helpers)\n\n // ── Step 3: resolve execa + wrapper path ──────────────────────────────\n let execaFn: ExecaLike\n try {\n execaFn = await resolveExeca(merged.execa)\n } catch (err) {\n ctx.nack(isError(err) ? err : new Error(String(err)))\n return\n }\n const wrapperPath = merged.wrapperPath ?? resolveDefaultWrapperPath()\n const claudeBin = merged.claudeBin ?? 'claude'\n\n // ── Step 5: pre-render inbound tool-call results (for history) ────────\n // Key by primitive identity, not id: repeated vendor/request ids must not cross-wire results.\n const renderedToolCallResults = new Map<ToolCall, string>()\n for (const tc of ctx.turnToolCalls) {\n const rendered = await resolvedHelpers.renderClaudeCodeCliToolCallResult({\n toolCall: tc,\n results: tc.results as\n | Tokenizable\n | SpooledArtifact\n | SpooledArtifact[]\n | Media\n | Media[],\n tool: ctx.tools.get(tc.tool) as Tool | undefined,\n renderUntrustedContent: resolvedHelpers.renderUntrustedContent,\n renderTrustedContent: resolvedHelpers.renderTrustedContent,\n unsupportedMediaPolicy: merged.unsupportedMediaPolicy ?? 'throw',\n warn: localWarn,\n })\n renderedToolCallResults.set(tc, rendered)\n }\n\n // ── Step 6: build the -p prompt ────────────────────────────────────────\n const { prompt, reasoningPayloads } = await resolvedHelpers.buildClaudeCodeCliPrompt({\n systemPrompt: ctx.systemPrompt,\n renderCtx: ctx,\n standingInstructions: ctx.standingInstructions,\n memories: ctx.turnMemories,\n retrievables: ctx.turnRetrievables,\n messages: ctx.turnMessages,\n thoughts: ctx.turnThoughts,\n toolCalls: ctx.turnToolCalls,\n tools: ctx.tools,\n renderedToolCallResults,\n bucketOrder: merged.bucketOrder ?? [\n 'standingInstructions',\n 'memories',\n 'retrievables',\n 'timeline',\n ],\n selfIdentity: merged.selfIdentity ?? 'assistant',\n thoughtSurfacing: merged.thoughtSurfacing ?? 'all-self',\n replayCompatibility: merged.replayCompatibility ?? [],\n unsupportedMediaPolicy: merged.unsupportedMediaPolicy ?? 'throw',\n renderChatCompletionsSystemPrompt: resolvedHelpers.renderChatCompletionsSystemPrompt,\n renderStandingInstructions: resolvedHelpers.renderStandingInstructions,\n renderMemories: resolvedHelpers.renderMemories,\n renderRetrievables: resolvedHelpers.renderRetrievables,\n renderRetrievableSafetyDirective: resolvedHelpers.renderRetrievableSafetyDirective,\n renderFirstPartyRetrievables: resolvedHelpers.renderFirstPartyRetrievables,\n renderThirdPartyPublicRetrievables: resolvedHelpers.renderThirdPartyPublicRetrievables,\n renderThirdPartyPrivateRetrievables: resolvedHelpers.renderThirdPartyPrivateRetrievables,\n renderRetrievableHandleBody: resolvedHelpers.renderRetrievableHandleBody,\n renderClaudeCodeCliTimelineMessage: resolvedHelpers.renderClaudeCodeCliTimelineMessage,\n renderClaudeCodeCliToolCallResult: resolvedHelpers.renderClaudeCodeCliToolCallResult,\n renderThought: resolvedHelpers.renderThought,\n filterThoughts: resolvedHelpers.filterThoughts,\n renderUntrustedContent: resolvedHelpers.renderUntrustedContent,\n renderTrustedContent: resolvedHelpers.renderTrustedContent,\n warn: localWarn,\n })\n\n // A `-p` prompt string has no side channel for an opaque, vendor-specific reasoning payload\n // the way Ollama/OpenAI's JSON request bodies do (`_adk_reasoning_payloads`) — there is\n // nowhere in this wire to forward one. Surface that loss as a diagnostic rather than\n // silently dropping it, matching the honesty standard applied to every other documented v1\n // limitation of this battery (text-only media, subagent text).\n if (reasoningPayloads.length > 0) {\n helpers.log.debug({\n kind: 'reasoning-payload-dropped',\n message: `${reasoningPayloads.length} opaque reasoning payload(s) matched replayCompatibility but have no destination on the Claude Code CLI wire (no side channel exists for a '-p' prompt) and were dropped.`,\n })\n }\n\n // ── Step 7: build the bridged-tools set (excluding disallowedTools) ───\n const disallowed = new Set(merged.disallowedTools ?? [])\n const visibleTools = ctx.tools.visible().filter((t) => !disallowed.has(t.name))\n const bridgedTools: WrapperBridgedTool[] = visibleTools.map((t) => {\n const described = t.describe()\n const inputSchema = resolvedHelpers.descriptionToChatCompletionsJsonSchema(\n described.inputSchema as never\n )\n return {\n name: described.name,\n description: described.description,\n inputSchema:\n inputSchema && Object.keys(inputSchema).length > 0\n ? (inputSchema as Record<string, unknown>)\n : { type: 'object', properties: {} },\n }\n })\n\n // ── Step 8: context window enforcement ────────────────────────────────\n if (merged.tokenEncoding !== null && merged.contextWindow !== undefined) {\n const encoding = merged.tokenEncoding as TokenEncoding\n // The rendered prompt is the actual `-p` wire value. Measure it directly rather than\n // re-summing its source buckets: renderers add envelopes, provenance, and ordering.\n const promptTokens = await estimateTokensOf(new Tokenizable(prompt), encoding)\n const appendSystemPromptTokens = merged.appendSystemPrompt\n ? await estimateTokensOf(new Tokenizable(merged.appendSystemPrompt), encoding)\n : 0\n\n // Keep source-bucket diagnostics for middleware deciding what to shed. They are not part\n // of the authoritative total above, since their content is already represented by prompt.\n const rawSystemPrompt = await estimateTokensOf(ctx.systemPrompt, encoding)\n let rawStandingInstructions = 0\n for (const value of ctx.standingInstructions)\n rawStandingInstructions += await estimateTokensOf(value, encoding)\n let rawMemories = 0\n for (const value of ctx.turnMemories as Set<Memory>)\n rawMemories += await estimateTokensOf(value.content, encoding)\n let rawRetrievables = 0\n for (const r of ctx.turnRetrievables) {\n rawRetrievables +=\n !r.inline && SpooledArtifact.isSpooledArtifact(r.content) && r.content.hasSizeHints()\n ? r.content.estimateHandleTokens(\n r.id,\n encoding,\n resolvedHelpers.renderRetrievableHandleBody\n )\n : await estimateTokensOf(r.content, encoding)\n }\n let rawTimeline = 0\n for (const msg of ctx.turnMessages)\n if (msg.content !== undefined)\n rawTimeline += await estimateTokensOf(msg.content, encoding)\n for (const thought of ctx.turnThoughts)\n rawTimeline += await estimateTokensOf(thought.content, encoding)\n for (const rendered of renderedToolCallResults.values())\n rawTimeline += await estimateTokensOf(new Tokenizable(rendered), encoding)\n // Claude Code receives declarations through MCP, not a wire `tools` array. This stable\n // serialization is an honest floor: JSON declarations plus the CLI-visible names.\n const toolSerialization = `${JSON.stringify(bridgedTools)}|${bridgedTools\n .map((t) => `mcp__adk_bridge__${t.name}`)\n .join(',')}`\n const tools = await estimateTokensOf(new Tokenizable(toolSerialization), encoding)\n const perBucket = {\n prompt: promptTokens,\n appendSystemPrompt: appendSystemPromptTokens,\n tools,\n raw: {\n systemPrompt: rawSystemPrompt,\n standingInstructions: rawStandingInstructions,\n memories: rawMemories,\n retrievables: rawRetrievables,\n timeline: rawTimeline,\n },\n }\n const total = promptTokens + appendSystemPromptTokens + tools\n helpers.log.debug({\n kind: 'context-window-usage',\n message: `Context window usage: ${total}/${merged.contextWindow} tokens`,\n payload: { total, limit: merged.contextWindow, encoding, perBucket },\n })\n if (total > merged.contextWindow)\n throw new E_CLAUDE_CODE_CLI_CONTEXT_OVERFLOW([\n total,\n merged.contextWindow,\n encoding,\n JSON.stringify(perBucket),\n ])\n }\n\n // ── Step 9: spawn the wrapper ──────────────────────────────────────────\n const spoolStore = merged.spoolStore ?? new InMemorySpoolStore()\n let child: ReturnType<ExecaLike>\n try {\n child = execaFn(process.execPath, [wrapperPath], { cleanup: true })\n } catch (err) {\n ctx.nack(\n new E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR([isError(err) ? err.message : String(err)])\n )\n return\n }\n\n const startupTimeoutMs = merged.startupTimeoutMs ?? 45_000\n const streamIdleTimeoutMs = merged.streamIdleTimeoutMs ?? 60_000\n const disposeGraceMs = merged.disposeGraceMs ?? 2_000\n\n let sawReady = false\n let sawInit = false\n // Set SYNCHRONOUSLY the instant a terminal `result`/`error` event is observed — before any\n // `await` (e.g. `sealCurrentMessage()`) runs. The wrapper closing stdout immediately after\n // writing its terminal line is a real, observed race: without this flag, `stdout`'s `'end'`\n // handler can fire and call `settleOnce` (nacking the turn as an unexpected exit) while the\n // `result` handler is still awaiting `sealCurrentMessage()`, even though `settleOnce` itself\n // is idempotent-guarded — the guard only helps once one of the two paths has actually run.\n let sawTerminalEvent = false\n let startupTimer: ReturnType<typeof setTimeout> | undefined\n let idleTimer: ReturnType<typeof setTimeout> | undefined\n let settled = false\n // Set once the outer `await new Promise<void>(...)` below is constructed. The startup/idle\n // timers are armed BEFORE that promise exists, so their settleOnce() callbacks must resolve\n // it through this indirection rather than a `finish` closure defined only inside it — without\n // this, a startup or stream-idle timeout would settle ctx (nack) but never resolve the outer\n // promise, hanging the executor forever.\n let resolveIteration: (() => void) | undefined\n let currentMessageId: string | undefined\n let currentMessageBuffer = ''\n let sealedMessage = false\n\n const clearStartupTimer = (): void => {\n if (startupTimer) clearTimeout(startupTimer)\n startupTimer = undefined\n }\n const clearIdleTimer = (): void => {\n if (idleTimer) clearTimeout(idleTimer)\n idleTimer = undefined\n }\n const maybeClearStartupTimer = (): void => {\n if (sawReady && sawInit) clearStartupTimer()\n }\n\n const writeCommand = (command: WrapperCommand): void => {\n try {\n child.stdin?.write(encodeWrapperCommand(command))\n } catch {\n /* the wrapper's stdin may already be gone */\n }\n }\n\n const gracefulShutdown = async (): Promise<void> => {\n writeCommand({ type: 'shutdown' })\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, disposeGraceMs)\n void Promise.resolve(child).finally(() => {\n clearTimeout(timer)\n resolve()\n })\n })\n try {\n child.kill('SIGTERM')\n } catch {\n /* already exited */\n }\n }\n\n const abortListener = (): void => {\n void gracefulShutdown()\n }\n ctx.abortSignal.addEventListener('abort', abortListener, { once: true })\n const detachAbortListener = (): void =>\n ctx.abortSignal.removeEventListener('abort', abortListener)\n\n const settleOnce = (fn: () => void): void => {\n if (settled) return\n settled = true\n clearStartupTimer()\n clearIdleTimer()\n detachAbortListener()\n fn()\n }\n\n startupTimer = setTimeout(() => {\n settleOnce(() => {\n resolveIteration?.()\n void gracefulShutdown()\n ctx.nack(new E_CLAUDE_CODE_CLI_STARTUP_TIMEOUT([startupTimeoutMs]))\n })\n }, startupTimeoutMs)\n\n const armIdleTimer = (): void => {\n if (!sawReady || !sawInit) return\n clearIdleTimer()\n idleTimer = setTimeout(() => {\n settleOnce(() => {\n resolveIteration?.()\n void gracefulShutdown()\n ctx.nack(new E_CLAUDE_CODE_CLI_STREAM_STALLED([streamIdleTimeoutMs]))\n })\n }, streamIdleTimeoutMs)\n }\n\n const sealCurrentMessage = async (): Promise<void> => {\n if (sealedMessage || currentMessageId === undefined) return\n sealedMessage = true\n await ctx.storeMessage(\n new Message({\n id: currentMessageId,\n role: 'assistant',\n content: currentMessageBuffer,\n identity: merged.selfIdentity ?? 'assistant',\n createdAt: nowIso(),\n updatedAt: nowIso(),\n })\n )\n }\n\n const handleToolCallRequest = async (\n requestId: string,\n toolName: string,\n rawArgs: unknown\n ): Promise<void> => {\n const tool = ctx.tools.get(toolName)\n if (!tool) {\n writeCommand({\n type: 'tool_call_response',\n requestId,\n results: {\n content: [{ type: 'text', text: `Tool not found: ${toolName}` }],\n isError: true,\n },\n })\n return\n }\n // MCP's own JSON-RPC CallTool wire always sends `arguments` as an object; a non-object\n // here would indicate a malformed request from the bridge, not a legitimate call — defend\n // the same way the Ollama battery does for its own non-object case.\n const args: string | Record<string, unknown> = isObject(rawArgs) ? rawArgs : {}\n helpers.reportToolCall(requestId, { tool: tool.name, args })\n const isArtifactTool = ArtifactTool.isArtifactTool(tool)\n let results: Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[] =\n new Tokenizable('')\n let toolHadError = false\n try {\n const raw = await tool.executor(ctx)(args)\n if (isArtifactTool) {\n if (Tokenizable.isTokenizable(raw)) {\n results = raw\n } else if (typeof raw === 'string') {\n results = new Tokenizable(raw)\n } else {\n throw new Error(\n `ArtifactTool \"${tool.name}\" returned a non-string/non-Tokenizable value`\n )\n }\n } else if (Media.isMedia(raw)) {\n results = raw\n } else if (Array.isArray(raw) && raw.length > 0 && raw.every((m) => Media.isMedia(m))) {\n results = raw as Media[]\n } else if (looksLikeSpooledArtifact(raw)) {\n results = raw as SpooledArtifact\n } else if (typeof raw === 'string' || isInstanceOf(raw, 'Uint8Array', Uint8Array)) {\n const reader = await spoolStore.write(requestId, raw)\n const ArtifactCtor = (tool as Tool).artifactConstructor?.() ?? SpooledArtifact\n results = new ArtifactCtor(reader)\n } else {\n const reader = await spoolStore.write(requestId, String(raw))\n const ArtifactCtor = (tool as Tool).artifactConstructor?.() ?? SpooledArtifact\n results = new ArtifactCtor(reader)\n }\n } catch (err) {\n toolHadError = true\n results = new Tokenizable(isError(err) ? err.message : String(err))\n }\n helpers.reportToolCall(requestId, { results, isError: toolHadError, isComplete: true })\n const completedAt = nowIso()\n await ctx.storeToolCall(\n new ToolCall({\n id: requestId,\n tool: tool.name,\n args,\n checksum: computeChecksum(tool.name, args),\n isComplete: true,\n isError: toolHadError,\n results,\n fromArtifactTool: isArtifactTool,\n inline: isArtifactTool,\n createdAt: completedAt,\n updatedAt: completedAt,\n completedAt,\n })\n )\n\n let rendered: { content: OutboundContentBlock[]; isError: boolean }\n try {\n rendered = await renderOutboundResult({\n raw: results as string | Uint8Array | SpooledArtifact | Media | Media[],\n callId: requestId,\n inline: isArtifactTool,\n spoolStore,\n unsupportedResultMediaPolicy:\n merged.unsupportedResultMediaPolicy ?? merged.unsupportedMediaPolicy ?? 'throw',\n })\n } catch (err) {\n rendered = {\n content: [{ type: 'text', text: isError(err) ? err.message : String(err) }],\n isError: true,\n }\n }\n writeCommand({\n type: 'tool_call_response',\n requestId,\n results: { content: rendered.content, isError: toolHadError || rendered.isError },\n })\n }\n\n await new Promise<void>((resolve) => {\n const finish = (): void => resolve()\n resolveIteration = finish\n\n const onEvent = async (event: WrapperEvent): Promise<void> => {\n if (event.type === 'ready') {\n sawReady = true\n maybeClearStartupTimer()\n const runCommand: WrapperCommand = {\n type: 'run',\n prompt,\n appendSystemPrompt: merged.appendSystemPrompt,\n model: merged.model,\n cwd: merged.cwd,\n addDir: merged.addDir,\n allowedTools: bridgedTools.map((t) => t.name),\n maxBudgetUsd: merged.maxBudgetUsd,\n fallbackModel: merged.fallbackModel,\n auth: {\n apiKey: merged.apiKey,\n authToken: merged.authToken,\n baseUrl: merged.baseURL,\n },\n disableTelemetry: merged.disableTelemetry,\n disableErrorReporting: merged.disableErrorReporting,\n disableNonessentialTraffic: merged.disableNonessentialTraffic,\n mcpToolIdleTimeoutMs: merged.mcpToolIdleTimeoutMs,\n claudeBin,\n forwardSubagentText: merged.forwardSubagentText,\n unsupportedResultMediaPolicy: String(\n merged.unsupportedResultMediaPolicy ?? merged.unsupportedMediaPolicy ?? 'throw'\n ),\n bridgedTools,\n extraArgs: merged.extraArgs,\n }\n writeCommand(runCommand)\n armIdleTimer()\n return\n }\n if (event.type === 'init') {\n sawInit = true\n maybeClearStartupTimer()\n helpers.log.info({\n kind: 'claude-init',\n message: 'Claude Code CLI initialized.',\n payload: event as unknown as Record<string, unknown>,\n })\n if (event.mcpServerErrors && event.mcpServerErrors.length > 0) {\n settleOnce(() => {\n finish()\n void gracefulShutdown()\n ctx.nack(\n new E_CLAUDE_CODE_CLI_MCP_BRIDGE_STARTUP_FAILED([\n event.mcpServerErrors!.join(', '),\n ])\n )\n })\n }\n return\n }\n if (event.type === 'retry') {\n helpers.log.warn({\n kind: 'claude-retry',\n message: `Claude API retry, attempt ${event.attempt}`,\n payload: event as unknown as Record<string, unknown>,\n })\n return\n }\n if (event.type === 'message_delta') {\n currentMessageId = event.id\n currentMessageBuffer += event.delta\n helpers.reportMessage(event.id, event.delta, { isComplete: event.isComplete })\n if (event.isComplete) {\n await sealCurrentMessage()\n }\n return\n }\n if (event.type === 'thought_delta') {\n helpers.reportThought(event.id, event.delta, { isComplete: event.isComplete })\n return\n }\n if (event.type === 'tool_call_request') {\n await handleToolCallRequest(event.requestId, event.tool, event.args)\n return\n }\n if (event.type === 'result') {\n sawTerminalEvent = true\n await sealCurrentMessage()\n settleOnce(() => {\n if (event.isError && event.subtype !== 'error_max_turns') {\n ctx.nack(\n new E_CLAUDE_CODE_CLI_TURN_FAILED([\n event.stopReason ?? 'unknown',\n event.resultText ?? '',\n ])\n )\n return\n }\n if (event.isError && event.subtype === 'error_max_turns') {\n helpers.log.debug({\n kind: 'claude-max-turns-reached',\n message:\n 'Claude reached the fixed single-turn limit; treating it as normal completion.',\n payload: { subtype: event.subtype },\n })\n }\n helpers.reportGenerationStats({\n provider: 'claude_code_cli',\n model: merged.model,\n raw: event.raw as Record<string, unknown> | undefined,\n })\n if (merged.autoAck) ctx.ack()\n })\n // The wrapper, not the adapter, initiates its own shutdown on this path (Decision D\n // step 5) — a terminal NDJSON line proves the wrapper WROTE it, not that the OS\n // process has actually exited yet. Await the wrapper's real exit before resolving so\n // the executor doesn't return while the wrapper (and its `claude` grandchild) are\n // still tearing down.\n await Promise.resolve(child).catch(() => undefined)\n finish()\n return\n }\n if (event.type === 'error') {\n settleOnce(() => {\n finish()\n void gracefulShutdown()\n ctx.nack(new E_CLAUDE_CODE_CLI_WRAPPER_CRASHED([event.message]))\n })\n return\n }\n if (event.type === 'log') {\n helpers.log[event.level]({\n kind: event.kind,\n message: event.message,\n payload: event.payload as Record<string, unknown> | undefined,\n })\n return\n }\n // 'shutdown_complete' — nothing further to do; the wrapper is exiting on its own.\n }\n\n const eventReader = createNdjsonLineReader<WrapperEvent>((raw) => {\n let event: WrapperEvent\n try {\n event = JSON.parse(raw) as WrapperEvent\n } catch {\n helpers.log.trace({\n kind: 'malformed-wrapper-event',\n message: 'Failed to parse wrapper event line; skipping.',\n payload: { linePreview: raw.slice(0, 256) },\n })\n return undefined\n }\n void onEvent(event)\n return event\n })\n\n child.stdout?.on('data', (chunk: Uint8Array) => {\n // Parse BEFORE arming: `armIdleTimer()` is gated on `sawReady && sawInit`, and the very\n // chunk that carries the `init` event is what flips `sawInit` — parsing first lets that\n // same chunk's processing arm the timer immediately, rather than requiring a chunk AFTER\n // init to ever arrive (which, on a genuinely idle stream, never happens).\n eventReader.push(chunk)\n armIdleTimer()\n })\n child.stdout?.on('end', () => {\n // A terminal `result`/`error` event was already observed and its own handler is (or will\n // shortly be) in the middle of its own `settleOnce` — defer to it rather than racing it\n // with a wrong \"stdout ended without a terminal event\" nack for what was actually a\n // successful turn. `sawTerminalEvent` is set synchronously by that handler before any\n // `await`, so it is already true here whenever this really is that race.\n if (sawTerminalEvent) return\n settleOnce(() => {\n finish()\n ctx.nack(\n new E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO([\n 0,\n 'stdout ended without a terminal event',\n ])\n )\n })\n })\n\n void Promise.resolve(child)\n .then((result: unknown) => {\n // Same race as the `stdout.on('end')` guard above: the `result` handler may still be\n // awaiting `sealCurrentMessage()`/the child's own exit when the wrapper process itself\n // settles — defer to the terminal-event path rather than nacking a successful turn.\n if (sawTerminalEvent) return\n const exitCode =\n isObject(result) && 'exitCode' in result\n ? ((result as { exitCode: number | null }).exitCode ?? -1)\n : -1\n settleOnce(() => {\n finish()\n ctx.nack(\n new E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO([\n exitCode,\n 'wrapper process exited with no terminal event observed',\n ])\n )\n })\n })\n .catch(() => {\n if (sawTerminalEvent) return\n settleOnce(() => {\n finish()\n ctx.nack(new E_CLAUDE_CODE_CLI_WRAPPER_CRASHED(['wrapper process rejected']))\n })\n })\n })\n }\n }\n\n /**\n * Returns `true` when `value` is a {@link ClaudeCodeCliAdapter} instance.\n */\n public static isClaudeCodeCliAdapter(value: unknown): value is ClaudeCodeCliAdapter {\n return isInstanceOf(value, 'ClaudeCodeCliAdapter', ClaudeCodeCliAdapter)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+FA,IAAa,kCAA0C;CAKrD,IAAI,OAAO,YAAY,cAAc,OAAO,QAAQ,YAAY,YAC9D,OAAO,QAAQ,QAAQ,sCAAsC;CAY/D,OAAO,mBACL,IAAA,IAAA,wCAAA,KAAA,CAAA,EAAA,GAAA,EAAiE,QACnE;AACF;AAIA,IAAM,eAAe,OAAO,aAA4D;CACtF,IAAI,QACF,mBAAmB,OAAO;CAC5B,IAAI,OAAO,UAAU,cAAc,EAAE,UAAW,QA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,CAC3C,GACA,uCACF,CAAC,CACH;KACF,CAAC;IACH,CAAC;IAED,QAAa,QAAQ,KAAK,EACvB,MAAM,WAAoB;KAIzB,IAAI,kBAAkB;KACtB,MAAM,WACJ,eAAA,SAAS,MAAM,KAAK,cAAc,SAC5B,OAAuC,YAAY,KACrD;KACN,iBAAiB;MACf,OAAO;MACP,IAAI,KACF,IAAI,iDAAA,yCAAyC,CAC3C,UACA,wDACF,CAAC,CACH;KACF,CAAC;IACH,CAAC,EACA,YAAY;KACX,IAAI,kBAAkB;KACtB,iBAAiB;MACf,OAAO;MACP,IAAI,KAAK,IAAI,iDAAA,kCAAkC,CAAC,0BAA0B,CAAC,CAAC;KAC9E,CAAC;IACH,CAAC;GACL,CAAC;EACH;CACF;;;;CAKA,OAAc,uBAAuB,OAA+C;EAClF,OAAO,eAAA,aAAa,OAAO,wBAAwB,oBAAoB;CACzE;AACF"}
1
+ {"version":3,"file":"adapter.cjs","names":["#baseline"],"sources":["../../../../src/batteries/llm/claude_code_cli/adapter.ts"],"sourcesContent":["/**\n * Cross-environment executor adapter that wraps the Claude Code CLI as a `DispatchExecutorFn`\n * destination.\n *\n * @module @nhtio/adk/batteries/llm/claude_code_cli/adapter\n *\n * @remarks\n * The first battery in the \"CLI harness\" family: rather than a direct wire-format provider, this\n * adapter drives an external coding-agent CLI binary that is itself a complete agent loop. Since a\n * subprocess must be spawned anyway, ALL Claude-Code-specific complexity — spawning the real\n * `claude` binary, hosting an MCP bridge server, translating its stream-json — lives in a\n * dedicated wrapper process (`wrapper.ts`, shipped as a sibling dist asset); this adapter only\n * ever spawns and drives that wrapper over the small, harness-agnostic protocol in `./wire`.\n *\n * Every dispatch iteration is stateless and self-contained: the full accumulated history renders\n * into one `-p` prompt string (`buildClaudeCodeCliPrompt`), a fresh wrapper is spawned, and real\n * ADK tools are bridged into the CLI's own tool loop via MCP — but actual execution always happens\n * on the ADK side, through `tool.executor(ctx)(args)`, exactly like every other LLM battery.\n */\n\nimport { sha256 } from 'js-sha256'\nimport { validateOptions } from './validation'\nimport { isError, isObject, isInstanceOf } from '@nhtio/adk/guards'\nimport { createNdjsonLineReader, encodeWrapperCommand } from './wire'\nimport { canonicalStringify } from '../../../lib/utils/canonical_json'\nimport { InMemorySpoolStore } from '@nhtio/adk/batteries/storage/in_memory'\nimport {\n Tokenizable,\n ToolCall,\n Memory,\n Message,\n Media,\n ArtifactTool,\n SpooledArtifact,\n} from '@nhtio/adk/common'\nimport {\n E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR,\n E_CLAUDE_CODE_CLI_WRAPPER_CRASHED,\n E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO,\n E_CLAUDE_CODE_CLI_STREAM_STALLED,\n E_CLAUDE_CODE_CLI_STARTUP_TIMEOUT,\n E_CLAUDE_CODE_CLI_MCP_BRIDGE_STARTUP_FAILED,\n E_CLAUDE_CODE_CLI_TURN_FAILED,\n E_INVALID_CLAUDE_CODE_CLI_OPTIONS,\n E_CLAUDE_CODE_CLI_CONTEXT_OVERFLOW,\n} from './exceptions'\nimport {\n defaultDescriptionToChatCompletionsJsonSchema,\n defaultRenderUntrustedContent,\n defaultRenderTrustedContent,\n defaultRenderStandingInstructions,\n defaultRenderMemories,\n defaultRenderRetrievables,\n defaultRenderRetrievableHandleBody,\n defaultRenderRetrievableSafetyDirective,\n defaultRenderFirstPartyRetrievables,\n defaultRenderThirdPartyPublicRetrievables,\n defaultRenderThirdPartyPrivateRetrievables,\n defaultRenderThought,\n defaultFilterThoughts,\n defaultToolsToChatCompletionsTools,\n defaultRenderChatCompletionsSystemPrompt,\n defaultRenderClaudeCodeCliTimelineMessage,\n defaultRenderClaudeCodeCliToolCallResult,\n defaultBuildClaudeCodeCliPrompt,\n renderArtifactHandleBody,\n looksLikeSpooledArtifact,\n} from './helpers'\nimport type { Tool } from '@nhtio/adk/common'\nimport type { SpoolStore } from '@nhtio/adk/common'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type { TokenEncoding, TokenEncodingId } from '@nhtio/adk/types'\nimport type { WrapperEvent, WrapperCommand, WrapperBridgedTool } from './wire'\nimport type { DispatchExecutorFn, DispatchExecutorHelpers } from '@nhtio/adk/dispatch_runner'\nimport type {\n ClaudeCodeCliAdapterOptions,\n ClaudeCodeCliHelpers,\n ExecaLike,\n ExecaResolver,\n UnsupportedMediaPolicy,\n} from './types'\n\ntype OutboundContentBlock =\n | { type: 'text'; text: string }\n | { type: 'image'; data: string; mimeType: string }\n\n// ─── wrapper path resolution (Decision C) ──────────────────────────────────────\n\n/**\n * Resolve the built wrapper asset's on-disk path relative to this module's own compiled location.\n * `adapter.ts` carries its own `@module` tag (per the per-file tagging convention every other\n * multi-file battery uses), so it compiles to `dist/batteries/llm/claude_code_cli/adapter.mjs` —\n * three directories below the package root, where the wrapper (an explicit, un-tagged\n * `vite.config.mts` entry key) compiles to `dist/claude-code-cli-wrapper.mjs`.\n */\nexport const resolveDefaultWrapperPath = (): string => {\n // `typeof require === 'function'` alone is not a safe CJS-vs-ESM discriminator: rolldown's ESM\n // output wraps `require` in a shim/Proxy (falling back to itself when the real `require` is\n // absent) that still reports `typeof === 'function'`, but whose `.resolve` is not itself a\n // function — calling it throws instead of falling through to the URL-based ESM branch below.\n if (typeof require === 'function' && typeof require.resolve === 'function') {\n return require.resolve('../../../claude-code-cli-wrapper.cjs')\n }\n // `URL.pathname` is percent-encoded — a real install path containing a space, unicode, or any\n // other URL-reserved character would produce a non-existent argv path (e.g. `%20` instead of a\n // literal space) once handed to `execaFn`/`spawn` below. `decodeURIComponent` undoes that percent\n // encoding to recover the native filesystem path — equivalent to `node:url`'s `fileURLToPath` for\n // a POSIX path (verified directly), which this module avoids importing at module scope: this\n // file is transitively pulled into the browser test project via `src/batteries`'s barrel (e.g.\n // `tests/unit/batteries/index.cross.spec.ts`), and Vite externalizes `node:url` there, throwing\n // on any access to `fileURLToPath` at import time. This battery is POSIX-only in v1 anyway\n // (validated at options-construction time), so a POSIX-only decode is exactly the right amount\n // of `node:url` behavior to reimplement without importing it.\n return decodeURIComponent(\n new URL('../../../claude-code-cli-wrapper.mjs', import.meta.url).pathname\n )\n}\n\n// ─── execa resolution (mirrors execa_executor.ts's lazy-resolver pattern) ──────\n\nconst resolveExeca = async (supplied: ExecaResolver | undefined): Promise<ExecaLike> => {\n let value: unknown =\n supplied ?? (() => import('execa') as unknown as Promise<{ execa: ExecaLike }>)\n if (typeof value === 'function' && !('exec' in (value as object))) {\n try {\n value = await (value as () => unknown)()\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n throw new E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR([\n `execa resolver failed: ${detail} — install the optional peer dependency \"execa\" or supply your own`,\n ])\n }\n }\n if (isObject(value) && 'execa' in value) {\n value = (value as { execa: unknown }).execa\n }\n if (typeof value !== 'function') {\n throw new E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR([\n 'execa resolver did not resolve to a function',\n ])\n }\n return value as ExecaLike\n}\n\n// ─── option merging ─────────────────────────────────────────────────────────\n\nconst mergeRecord = <T extends Record<string, unknown>>(\n layers: ReadonlyArray<T | undefined>\n): T | undefined => {\n let merged: T | undefined\n for (const layer of layers) {\n if (!layer) continue\n merged = { ...(merged ?? ({} as T)), ...layer }\n }\n return merged\n}\n\nconst mergeOptions = (\n baseline: ClaudeCodeCliAdapterOptions,\n exec: Partial<ClaudeCodeCliAdapterOptions> | undefined,\n stash: Partial<ClaudeCodeCliAdapterOptions> | undefined\n): Partial<ClaudeCodeCliAdapterOptions> => {\n const layers = [baseline as Partial<ClaudeCodeCliAdapterOptions>, exec ?? {}, stash ?? {}]\n const out: Record<string, unknown> = {}\n for (const layer of layers) {\n for (const [k, v] of Object.entries(layer)) {\n if (v === undefined) continue\n if (k === 'helpers') continue\n out[k] = v\n }\n }\n const helpers = mergeRecord(layers.map((l) => l.helpers as Record<string, unknown> | undefined))\n if (helpers !== undefined) out.helpers = helpers\n return out as Partial<ClaudeCodeCliAdapterOptions>\n}\n\nconst resolveHelpers = (\n overrides: Partial<ClaudeCodeCliHelpers> | undefined\n): ClaudeCodeCliHelpers => {\n const src = overrides ?? {}\n return {\n descriptionToChatCompletionsJsonSchema:\n src.descriptionToChatCompletionsJsonSchema ?? defaultDescriptionToChatCompletionsJsonSchema,\n renderUntrustedContent: src.renderUntrustedContent ?? defaultRenderUntrustedContent,\n renderTrustedContent: src.renderTrustedContent ?? defaultRenderTrustedContent,\n renderStandingInstructions: src.renderStandingInstructions ?? defaultRenderStandingInstructions,\n renderMemories: src.renderMemories ?? defaultRenderMemories,\n renderRetrievables: src.renderRetrievables ?? defaultRenderRetrievables,\n renderRetrievableHandleBody:\n src.renderRetrievableHandleBody ?? defaultRenderRetrievableHandleBody,\n renderRetrievableSafetyDirective:\n src.renderRetrievableSafetyDirective ?? defaultRenderRetrievableSafetyDirective,\n renderFirstPartyRetrievables:\n src.renderFirstPartyRetrievables ?? defaultRenderFirstPartyRetrievables,\n renderThirdPartyPublicRetrievables:\n src.renderThirdPartyPublicRetrievables ?? defaultRenderThirdPartyPublicRetrievables,\n renderThirdPartyPrivateRetrievables:\n src.renderThirdPartyPrivateRetrievables ?? defaultRenderThirdPartyPrivateRetrievables,\n renderThought: src.renderThought ?? defaultRenderThought,\n filterThoughts: src.filterThoughts ?? defaultFilterThoughts,\n toolsToChatCompletionsTools:\n src.toolsToChatCompletionsTools ?? defaultToolsToChatCompletionsTools,\n renderChatCompletionsSystemPrompt:\n src.renderChatCompletionsSystemPrompt ?? defaultRenderChatCompletionsSystemPrompt,\n renderClaudeCodeCliTimelineMessage:\n src.renderClaudeCodeCliTimelineMessage ?? defaultRenderClaudeCodeCliTimelineMessage,\n renderClaudeCodeCliToolCallResult:\n src.renderClaudeCodeCliToolCallResult ?? defaultRenderClaudeCodeCliToolCallResult,\n buildClaudeCodeCliPrompt: src.buildClaudeCodeCliPrompt ?? defaultBuildClaudeCodeCliPrompt,\n }\n}\n\nconst estimateTokensOf = async (\n value: { estimateTokens: (encoding: TokenEncoding) => number | Promise<number> },\n encoding: TokenEncodingId\n): Promise<number> => Promise.resolve(value.estimateTokens(encoding as TokenEncoding))\n\n// ─── time / checksum helpers ────────────────────────────────────────────────\n\nconst nowIso = (): string => new Date().toISOString()\n\n/**\n * Integrity checksum over `tool`/`args` — matches every other LLM battery's convention\n * (`sha256(canonicalStringify({tool, args}))`, see `ollama/adapter.ts`'s `computeChecksum`), NOT\n * the per-call `requestId`. Identical repeat calls must share this checksum: it feeds\n * `DispatchContext`'s own `#toolCallChecksums` loop-detection counter and cross-bus correlation,\n * neither of which can see a repeat if every call gets a unique value.\n */\nconst computeChecksum = (tool: string, args: unknown): string =>\n sha256(canonicalStringify({ tool, args }))\n\n// ─── outbound tool-result rendering (decision 8) ───────────────────────────────\n\nconst renderMediaListAsOutbound = async (\n mediaList: Media[],\n unsupportedResultMediaPolicy: UnsupportedMediaPolicy\n): Promise<{ content: OutboundContentBlock[]; isError: boolean }> => {\n const content: OutboundContentBlock[] = []\n let anyUnsupported = false\n for (const media of mediaList) {\n if (media.kind === 'image') {\n content.push({ type: 'image', data: await media.asBase64(), mimeType: media.mimeType })\n continue\n }\n // Every non-image modality is unsupported on the outbound MCP wire (only text/image content\n // blocks exist there) — routed through the SAME policy family the inbound direction uses\n // (decision 8), rather than an unconditional hardcoded error.\n if (unsupportedResultMediaPolicy === 'throw') {\n anyUnsupported = true\n content.push({\n type: 'text',\n text: `Unsupported result media modality: ${media.kind} (${media.mimeType})`,\n })\n continue\n }\n const byteLen = await media.byteLength().catch(() => undefined)\n content.push({\n type: 'text',\n text: `[media: ${media.filename}, ${media.mimeType}, ${byteLen ?? 'unknown'} bytes]`,\n })\n }\n return { content, isError: anyUnsupported }\n}\n\nconst renderOutboundResult = async (input: {\n raw: string | Uint8Array | SpooledArtifact | Media | Media[]\n callId: string\n inline: boolean\n spoolStore: SpoolStore\n unsupportedResultMediaPolicy: UnsupportedMediaPolicy\n}): Promise<{ content: OutboundContentBlock[]; isError: boolean }> => {\n const { raw, callId, inline } = input\n\n if (Media.isMedia(raw)) {\n return renderMediaListAsOutbound([raw], input.unsupportedResultMediaPolicy)\n }\n if (Array.isArray(raw) && raw.length > 0 && raw.every((m) => Media.isMedia(m))) {\n return renderMediaListAsOutbound(raw, input.unsupportedResultMediaPolicy)\n }\n if (looksLikeSpooledArtifact(raw)) {\n const artifact = raw as SpooledArtifact\n if (inline === false) {\n let byteLength = 0\n let lineCount = 0\n try {\n byteLength = await artifact.byteLength()\n } catch {\n byteLength = 0\n }\n try {\n lineCount = await artifact.lineCount()\n } catch {\n lineCount = 0\n }\n const body = renderArtifactHandleBody({ callId, artifact, byteLength, lineCount })\n return { content: [{ type: 'text', text: body }], isError: false }\n }\n const text = await artifact.asString()\n return { content: [{ type: 'text', text }], isError: false }\n }\n if (typeof raw === 'string') {\n return { content: [{ type: 'text', text: raw }], isError: false }\n }\n if (isInstanceOf(raw, 'Uint8Array', Uint8Array)) {\n await input.spoolStore.write(callId, raw)\n return {\n content: [{ type: 'text', text: '[binary tool result — see history for details]' }],\n isError: false,\n }\n }\n return { content: [{ type: 'text', text: String(raw) }], isError: false }\n}\n\n// ─── the adapter ────────────────────────────────────────────────────────────\n\n/**\n * Opinionated CLI-harness LLM adapter that drives the Claude Code CLI as a `DispatchExecutorFn`\n * destination.\n *\n * @remarks\n * Construction validates options eagerly via {@link validateOptions} and throws\n * {@link @nhtio/adk/batteries/llm/claude_code_cli!E_INVALID_CLAUDE_CODE_CLI_OPTIONS} on failure\n * (including the POSIX-only platform guard and the `apiKey`/`authToken` XOR check). The returned\n * instance is reusable: call {@link ClaudeCodeCliAdapter.executor} once per `DispatchRunner`\n * configuration.\n */\nexport class ClaudeCodeCliAdapter {\n /** Customary key for per-iteration overrides on `ctx.stash`. */\n public static readonly STASH_KEY = 'claudeCodeCli' as const\n\n readonly #baseline: ClaudeCodeCliAdapterOptions\n\n /**\n * @param options - Constructor-baseline options. Re-validated on every iteration after\n * per-dispatch and per-iteration overrides are layered in.\n * @throws {@link @nhtio/adk/batteries/llm/claude_code_cli!E_INVALID_CLAUDE_CODE_CLI_OPTIONS} when\n * `options` does not satisfy `claudeCodeCliOptionsSchema`.\n */\n constructor(options: unknown) {\n this.#baseline = validateOptions(options)\n }\n\n /**\n * Returns a {@link @nhtio/adk!DispatchExecutorFn} bound to this adapter's baseline plus optional\n * executor-scope overrides.\n */\n executor(overrides?: Partial<ClaudeCodeCliAdapterOptions>): DispatchExecutorFn {\n const baseline = this.#baseline\n const adapterClass = ClaudeCodeCliAdapter\n\n return async (ctx: DispatchContext, helpers: DispatchExecutorHelpers): Promise<void> => {\n const localWarn = (msg: string): void => {\n helpers.log.warn({ kind: 'helper-warning', message: msg })\n }\n\n // ── Step 1: merge & validate ──────────────────────────────────────────\n const stashRaw = ctx.stash.get(adapterClass.STASH_KEY, {}) as unknown\n const stashOverrides =\n stashRaw && typeof stashRaw === 'object'\n ? (stashRaw as Partial<ClaudeCodeCliAdapterOptions>)\n : {}\n const merged = validateOptions(mergeOptions(baseline, overrides, stashOverrides))\n\n if (merged.tokenEncoding !== null && merged.contextWindow === undefined) {\n throw new E_INVALID_CLAUDE_CODE_CLI_OPTIONS([\n 'tokenEncoding is non-null but contextWindow is undefined',\n ])\n }\n\n // ── Step 2: resolve helpers ───────────────────────────────────────────\n const resolvedHelpers = resolveHelpers(merged.helpers)\n\n // ── Step 3: resolve execa + wrapper path ──────────────────────────────\n let execaFn: ExecaLike\n try {\n execaFn = await resolveExeca(merged.execa)\n } catch (err) {\n ctx.nack(isError(err) ? err : new Error(String(err)))\n return\n }\n const wrapperPath = merged.wrapperPath ?? resolveDefaultWrapperPath()\n const claudeBin = merged.claudeBin ?? 'claude'\n\n // ── Step 5: pre-render inbound tool-call results (for history) ────────\n // Key by primitive identity, not id: repeated vendor/request ids must not cross-wire results.\n const renderedToolCallResults = new Map<ToolCall, string>()\n for (const tc of ctx.turnToolCalls) {\n const rendered = await resolvedHelpers.renderClaudeCodeCliToolCallResult({\n toolCall: tc,\n results: tc.results as\n | Tokenizable\n | SpooledArtifact\n | SpooledArtifact[]\n | Media\n | Media[],\n tool: ctx.tools.get(tc.tool) as Tool | undefined,\n renderUntrustedContent: resolvedHelpers.renderUntrustedContent,\n renderTrustedContent: resolvedHelpers.renderTrustedContent,\n unsupportedMediaPolicy: merged.unsupportedMediaPolicy ?? 'throw',\n warn: localWarn,\n })\n renderedToolCallResults.set(tc, rendered)\n }\n\n // ── Step 6: build the -p prompt ────────────────────────────────────────\n const { prompt, reasoningPayloads } = await resolvedHelpers.buildClaudeCodeCliPrompt({\n systemPrompt: ctx.systemPrompt,\n renderCtx: ctx,\n standingInstructions: ctx.standingInstructions,\n memories: ctx.turnMemories,\n retrievables: ctx.turnRetrievables,\n messages: ctx.turnMessages,\n thoughts: ctx.turnThoughts,\n toolCalls: ctx.turnToolCalls,\n tools: ctx.tools,\n renderedToolCallResults,\n bucketOrder: merged.bucketOrder ?? [\n 'standingInstructions',\n 'memories',\n 'retrievables',\n 'timeline',\n ],\n selfIdentity: merged.selfIdentity ?? 'assistant',\n thoughtSurfacing: merged.thoughtSurfacing ?? 'all-self',\n replayCompatibility: merged.replayCompatibility ?? [],\n unsupportedMediaPolicy: merged.unsupportedMediaPolicy ?? 'throw',\n renderChatCompletionsSystemPrompt: resolvedHelpers.renderChatCompletionsSystemPrompt,\n renderStandingInstructions: resolvedHelpers.renderStandingInstructions,\n renderMemories: resolvedHelpers.renderMemories,\n renderRetrievables: resolvedHelpers.renderRetrievables,\n renderRetrievableSafetyDirective: resolvedHelpers.renderRetrievableSafetyDirective,\n renderFirstPartyRetrievables: resolvedHelpers.renderFirstPartyRetrievables,\n renderThirdPartyPublicRetrievables: resolvedHelpers.renderThirdPartyPublicRetrievables,\n renderThirdPartyPrivateRetrievables: resolvedHelpers.renderThirdPartyPrivateRetrievables,\n renderRetrievableHandleBody: resolvedHelpers.renderRetrievableHandleBody,\n renderClaudeCodeCliTimelineMessage: resolvedHelpers.renderClaudeCodeCliTimelineMessage,\n renderClaudeCodeCliToolCallResult: resolvedHelpers.renderClaudeCodeCliToolCallResult,\n renderThought: resolvedHelpers.renderThought,\n filterThoughts: resolvedHelpers.filterThoughts,\n renderUntrustedContent: resolvedHelpers.renderUntrustedContent,\n renderTrustedContent: resolvedHelpers.renderTrustedContent,\n warn: localWarn,\n })\n\n // A `-p` prompt string has no side channel for an opaque, vendor-specific reasoning payload\n // the way Ollama/OpenAI's JSON request bodies do (`_adk_reasoning_payloads`) — there is\n // nowhere in this wire to forward one. Surface that loss as a diagnostic rather than\n // silently dropping it, matching the honesty standard applied to every other documented v1\n // limitation of this battery (text-only media, subagent text).\n if (reasoningPayloads.length > 0) {\n helpers.log.debug({\n kind: 'reasoning-payload-dropped',\n message: `${reasoningPayloads.length} opaque reasoning payload(s) matched replayCompatibility but have no destination on the Claude Code CLI wire (no side channel exists for a '-p' prompt) and were dropped.`,\n })\n }\n\n // ── Step 7: build the bridged-tools set (excluding disallowedTools) ───\n const disallowed = new Set(merged.disallowedTools ?? [])\n const visibleTools = ctx.tools.visible().filter((t) => !disallowed.has(t.name))\n const bridgedTools: WrapperBridgedTool[] = visibleTools.map((t) => {\n const described = t.describe()\n const inputSchema = resolvedHelpers.descriptionToChatCompletionsJsonSchema(\n described.inputSchema as never\n )\n return {\n name: described.name,\n description: described.description,\n inputSchema:\n inputSchema && Object.keys(inputSchema).length > 0\n ? (inputSchema as Record<string, unknown>)\n : { type: 'object', properties: {} },\n }\n })\n\n // ── Step 8: context window enforcement ────────────────────────────────\n if (merged.tokenEncoding !== null && merged.contextWindow !== undefined) {\n const encoding = merged.tokenEncoding as TokenEncodingId\n // The rendered prompt is the actual `-p` wire value. Measure it directly rather than\n // re-summing its source buckets: renderers add envelopes, provenance, and ordering.\n const promptTokens = await estimateTokensOf(new Tokenizable(prompt), encoding)\n const appendSystemPromptTokens = merged.appendSystemPrompt\n ? await estimateTokensOf(new Tokenizable(merged.appendSystemPrompt), encoding)\n : 0\n\n // Keep source-bucket diagnostics for middleware deciding what to shed. They are not part\n // of the authoritative total above, since their content is already represented by prompt.\n const rawSystemPrompt = await estimateTokensOf(ctx.systemPrompt, encoding)\n let rawStandingInstructions = 0\n for (const value of ctx.standingInstructions)\n rawStandingInstructions += await estimateTokensOf(value, encoding)\n let rawMemories = 0\n for (const value of ctx.turnMemories as Set<Memory>)\n rawMemories += await estimateTokensOf(value.content, encoding)\n let rawRetrievables = 0\n for (const r of ctx.turnRetrievables) {\n rawRetrievables +=\n !r.inline && SpooledArtifact.isSpooledArtifact(r.content) && r.content.hasSizeHints()\n ? r.content.estimateHandleTokens(\n r.id,\n encoding as TokenEncoding,\n resolvedHelpers.renderRetrievableHandleBody\n )\n : await estimateTokensOf(r.content, encoding)\n }\n let rawTimeline = 0\n for (const msg of ctx.turnMessages)\n if (msg.content !== undefined)\n rawTimeline += await estimateTokensOf(msg.content, encoding)\n for (const thought of ctx.turnThoughts)\n rawTimeline += await estimateTokensOf(thought.content, encoding)\n for (const rendered of renderedToolCallResults.values())\n rawTimeline += await estimateTokensOf(new Tokenizable(rendered), encoding)\n // Claude Code receives declarations through MCP, not a wire `tools` array. This stable\n // serialization is an honest floor: JSON declarations plus the CLI-visible names.\n const toolSerialization = `${JSON.stringify(bridgedTools)}|${bridgedTools\n .map((t) => `mcp__adk_bridge__${t.name}`)\n .join(',')}`\n const tools = await estimateTokensOf(new Tokenizable(toolSerialization), encoding)\n const perBucket = {\n prompt: promptTokens,\n appendSystemPrompt: appendSystemPromptTokens,\n tools,\n raw: {\n systemPrompt: rawSystemPrompt,\n standingInstructions: rawStandingInstructions,\n memories: rawMemories,\n retrievables: rawRetrievables,\n timeline: rawTimeline,\n },\n }\n const total = promptTokens + appendSystemPromptTokens + tools\n helpers.log.debug({\n kind: 'context-window-usage',\n message: `Context window usage: ${total}/${merged.contextWindow} tokens`,\n payload: { total, limit: merged.contextWindow, encoding, perBucket },\n })\n if (total > merged.contextWindow)\n throw new E_CLAUDE_CODE_CLI_CONTEXT_OVERFLOW([\n total,\n merged.contextWindow,\n encoding,\n JSON.stringify(perBucket),\n ])\n }\n\n // ── Step 9: spawn the wrapper ──────────────────────────────────────────\n const spoolStore = merged.spoolStore ?? new InMemorySpoolStore()\n let child: ReturnType<ExecaLike>\n try {\n child = execaFn(process.execPath, [wrapperPath], { cleanup: true })\n } catch (err) {\n ctx.nack(\n new E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR([isError(err) ? err.message : String(err)])\n )\n return\n }\n\n const startupTimeoutMs = merged.startupTimeoutMs ?? 45_000\n const streamIdleTimeoutMs = merged.streamIdleTimeoutMs ?? 60_000\n const disposeGraceMs = merged.disposeGraceMs ?? 2_000\n\n let sawReady = false\n let sawInit = false\n // Set SYNCHRONOUSLY the instant a terminal `result`/`error` event is observed — before any\n // `await` (e.g. `sealCurrentMessage()`) runs. The wrapper closing stdout immediately after\n // writing its terminal line is a real, observed race: without this flag, `stdout`'s `'end'`\n // handler can fire and call `settleOnce` (nacking the turn as an unexpected exit) while the\n // `result` handler is still awaiting `sealCurrentMessage()`, even though `settleOnce` itself\n // is idempotent-guarded — the guard only helps once one of the two paths has actually run.\n let sawTerminalEvent = false\n let startupTimer: ReturnType<typeof setTimeout> | undefined\n let idleTimer: ReturnType<typeof setTimeout> | undefined\n let settled = false\n // Set once the outer `await new Promise<void>(...)` below is constructed. The startup/idle\n // timers are armed BEFORE that promise exists, so their settleOnce() callbacks must resolve\n // it through this indirection rather than a `finish` closure defined only inside it — without\n // this, a startup or stream-idle timeout would settle ctx (nack) but never resolve the outer\n // promise, hanging the executor forever.\n let resolveIteration: (() => void) | undefined\n let currentMessageId: string | undefined\n let currentMessageBuffer = ''\n let sealedMessage = false\n\n const clearStartupTimer = (): void => {\n if (startupTimer) clearTimeout(startupTimer)\n startupTimer = undefined\n }\n const clearIdleTimer = (): void => {\n if (idleTimer) clearTimeout(idleTimer)\n idleTimer = undefined\n }\n const maybeClearStartupTimer = (): void => {\n if (sawReady && sawInit) clearStartupTimer()\n }\n\n const writeCommand = (command: WrapperCommand): void => {\n try {\n child.stdin?.write(encodeWrapperCommand(command))\n } catch {\n /* the wrapper's stdin may already be gone */\n }\n }\n\n const gracefulShutdown = async (): Promise<void> => {\n writeCommand({ type: 'shutdown' })\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, disposeGraceMs)\n void Promise.resolve(child).finally(() => {\n clearTimeout(timer)\n resolve()\n })\n })\n try {\n child.kill('SIGTERM')\n } catch {\n /* already exited */\n }\n }\n\n const abortListener = (): void => {\n void gracefulShutdown()\n }\n ctx.abortSignal.addEventListener('abort', abortListener, { once: true })\n const detachAbortListener = (): void =>\n ctx.abortSignal.removeEventListener('abort', abortListener)\n\n const settleOnce = (fn: () => void): void => {\n if (settled) return\n settled = true\n clearStartupTimer()\n clearIdleTimer()\n detachAbortListener()\n fn()\n }\n\n startupTimer = setTimeout(() => {\n settleOnce(() => {\n resolveIteration?.()\n void gracefulShutdown()\n ctx.nack(new E_CLAUDE_CODE_CLI_STARTUP_TIMEOUT([startupTimeoutMs]))\n })\n }, startupTimeoutMs)\n\n const armIdleTimer = (): void => {\n if (!sawReady || !sawInit) return\n clearIdleTimer()\n idleTimer = setTimeout(() => {\n settleOnce(() => {\n resolveIteration?.()\n void gracefulShutdown()\n ctx.nack(new E_CLAUDE_CODE_CLI_STREAM_STALLED([streamIdleTimeoutMs]))\n })\n }, streamIdleTimeoutMs)\n }\n\n const sealCurrentMessage = async (): Promise<void> => {\n if (sealedMessage || currentMessageId === undefined) return\n sealedMessage = true\n await ctx.storeMessage(\n new Message({\n id: currentMessageId,\n role: 'assistant',\n content: currentMessageBuffer,\n identity: merged.selfIdentity ?? 'assistant',\n createdAt: nowIso(),\n updatedAt: nowIso(),\n })\n )\n }\n\n const handleToolCallRequest = async (\n requestId: string,\n toolName: string,\n rawArgs: unknown\n ): Promise<void> => {\n const tool = ctx.tools.get(toolName)\n if (!tool) {\n writeCommand({\n type: 'tool_call_response',\n requestId,\n results: {\n content: [{ type: 'text', text: `Tool not found: ${toolName}` }],\n isError: true,\n },\n })\n return\n }\n // MCP's own JSON-RPC CallTool wire always sends `arguments` as an object; a non-object\n // here would indicate a malformed request from the bridge, not a legitimate call — defend\n // the same way the Ollama battery does for its own non-object case.\n const args: string | Record<string, unknown> = isObject(rawArgs) ? rawArgs : {}\n helpers.reportToolCall(requestId, { tool: tool.name, args })\n const isArtifactTool = ArtifactTool.isArtifactTool(tool)\n let results: Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[] =\n new Tokenizable('')\n let toolHadError = false\n try {\n const raw = await tool.executor(ctx)(args)\n if (isArtifactTool) {\n if (Tokenizable.isTokenizable(raw)) {\n results = raw\n } else if (typeof raw === 'string') {\n results = new Tokenizable(raw)\n } else {\n throw new Error(\n `ArtifactTool \"${tool.name}\" returned a non-string/non-Tokenizable value`\n )\n }\n } else if (Media.isMedia(raw)) {\n results = raw\n } else if (Array.isArray(raw) && raw.length > 0 && raw.every((m) => Media.isMedia(m))) {\n results = raw as Media[]\n } else if (looksLikeSpooledArtifact(raw)) {\n results = raw as SpooledArtifact\n } else if (typeof raw === 'string' || isInstanceOf(raw, 'Uint8Array', Uint8Array)) {\n const reader = await spoolStore.write(requestId, raw)\n const ArtifactCtor = (tool as Tool).artifactConstructor?.() ?? SpooledArtifact\n results = new ArtifactCtor(reader)\n } else {\n const reader = await spoolStore.write(requestId, String(raw))\n const ArtifactCtor = (tool as Tool).artifactConstructor?.() ?? SpooledArtifact\n results = new ArtifactCtor(reader)\n }\n } catch (err) {\n toolHadError = true\n results = new Tokenizable(isError(err) ? err.message : String(err))\n }\n helpers.reportToolCall(requestId, { results, isError: toolHadError, isComplete: true })\n const completedAt = nowIso()\n await ctx.storeToolCall(\n new ToolCall({\n id: requestId,\n tool: tool.name,\n args,\n checksum: computeChecksum(tool.name, args),\n isComplete: true,\n isError: toolHadError,\n results,\n fromArtifactTool: isArtifactTool,\n inline: isArtifactTool,\n createdAt: completedAt,\n updatedAt: completedAt,\n completedAt,\n })\n )\n\n let rendered: { content: OutboundContentBlock[]; isError: boolean }\n try {\n rendered = await renderOutboundResult({\n raw: results as string | Uint8Array | SpooledArtifact | Media | Media[],\n callId: requestId,\n inline: isArtifactTool,\n spoolStore,\n unsupportedResultMediaPolicy:\n merged.unsupportedResultMediaPolicy ?? merged.unsupportedMediaPolicy ?? 'throw',\n })\n } catch (err) {\n rendered = {\n content: [{ type: 'text', text: isError(err) ? err.message : String(err) }],\n isError: true,\n }\n }\n writeCommand({\n type: 'tool_call_response',\n requestId,\n results: { content: rendered.content, isError: toolHadError || rendered.isError },\n })\n }\n\n await new Promise<void>((resolve) => {\n const finish = (): void => resolve()\n resolveIteration = finish\n\n const onEvent = async (event: WrapperEvent): Promise<void> => {\n if (event.type === 'ready') {\n sawReady = true\n maybeClearStartupTimer()\n const runCommand: WrapperCommand = {\n type: 'run',\n prompt,\n appendSystemPrompt: merged.appendSystemPrompt,\n model: merged.model,\n cwd: merged.cwd,\n addDir: merged.addDir,\n allowedTools: bridgedTools.map((t) => t.name),\n maxBudgetUsd: merged.maxBudgetUsd,\n fallbackModel: merged.fallbackModel,\n auth: {\n apiKey: merged.apiKey,\n authToken: merged.authToken,\n baseUrl: merged.baseURL,\n },\n disableTelemetry: merged.disableTelemetry,\n disableErrorReporting: merged.disableErrorReporting,\n disableNonessentialTraffic: merged.disableNonessentialTraffic,\n mcpToolIdleTimeoutMs: merged.mcpToolIdleTimeoutMs,\n claudeBin,\n forwardSubagentText: merged.forwardSubagentText,\n unsupportedResultMediaPolicy: String(\n merged.unsupportedResultMediaPolicy ?? merged.unsupportedMediaPolicy ?? 'throw'\n ),\n bridgedTools,\n extraArgs: merged.extraArgs,\n }\n writeCommand(runCommand)\n armIdleTimer()\n return\n }\n if (event.type === 'init') {\n sawInit = true\n maybeClearStartupTimer()\n helpers.log.info({\n kind: 'claude-init',\n message: 'Claude Code CLI initialized.',\n payload: event as unknown as Record<string, unknown>,\n })\n if (event.mcpServerErrors && event.mcpServerErrors.length > 0) {\n settleOnce(() => {\n finish()\n void gracefulShutdown()\n ctx.nack(\n new E_CLAUDE_CODE_CLI_MCP_BRIDGE_STARTUP_FAILED([\n event.mcpServerErrors!.join(', '),\n ])\n )\n })\n }\n return\n }\n if (event.type === 'retry') {\n helpers.log.warn({\n kind: 'claude-retry',\n message: `Claude API retry, attempt ${event.attempt}`,\n payload: event as unknown as Record<string, unknown>,\n })\n return\n }\n if (event.type === 'message_delta') {\n currentMessageId = event.id\n currentMessageBuffer += event.delta\n helpers.reportMessage(event.id, event.delta, { isComplete: event.isComplete })\n if (event.isComplete) {\n await sealCurrentMessage()\n }\n return\n }\n if (event.type === 'thought_delta') {\n helpers.reportThought(event.id, event.delta, { isComplete: event.isComplete })\n return\n }\n if (event.type === 'tool_call_request') {\n await handleToolCallRequest(event.requestId, event.tool, event.args)\n return\n }\n if (event.type === 'result') {\n sawTerminalEvent = true\n await sealCurrentMessage()\n settleOnce(() => {\n if (event.isError && event.subtype !== 'error_max_turns') {\n ctx.nack(\n new E_CLAUDE_CODE_CLI_TURN_FAILED([\n event.stopReason ?? 'unknown',\n event.resultText ?? '',\n ])\n )\n return\n }\n if (event.isError && event.subtype === 'error_max_turns') {\n helpers.log.debug({\n kind: 'claude-max-turns-reached',\n message:\n 'Claude reached the fixed single-turn limit; treating it as normal completion.',\n payload: { subtype: event.subtype },\n })\n }\n helpers.reportGenerationStats({\n provider: 'claude_code_cli',\n model: merged.model,\n raw: event.raw as Record<string, unknown> | undefined,\n })\n if (merged.autoAck) ctx.ack()\n })\n // The wrapper, not the adapter, initiates its own shutdown on this path (Decision D\n // step 5) — a terminal NDJSON line proves the wrapper WROTE it, not that the OS\n // process has actually exited yet. Await the wrapper's real exit before resolving so\n // the executor doesn't return while the wrapper (and its `claude` grandchild) are\n // still tearing down.\n await Promise.resolve(child).catch(() => undefined)\n finish()\n return\n }\n if (event.type === 'error') {\n settleOnce(() => {\n finish()\n void gracefulShutdown()\n ctx.nack(new E_CLAUDE_CODE_CLI_WRAPPER_CRASHED([event.message]))\n })\n return\n }\n if (event.type === 'log') {\n helpers.log[event.level]({\n kind: event.kind,\n message: event.message,\n payload: event.payload as Record<string, unknown> | undefined,\n })\n return\n }\n // 'shutdown_complete' — nothing further to do; the wrapper is exiting on its own.\n }\n\n const eventReader = createNdjsonLineReader<WrapperEvent>((raw) => {\n let event: WrapperEvent\n try {\n event = JSON.parse(raw) as WrapperEvent\n } catch {\n helpers.log.trace({\n kind: 'malformed-wrapper-event',\n message: 'Failed to parse wrapper event line; skipping.',\n payload: { linePreview: raw.slice(0, 256) },\n })\n return undefined\n }\n void onEvent(event)\n return event\n })\n\n child.stdout?.on('data', (chunk: Uint8Array) => {\n // Parse BEFORE arming: `armIdleTimer()` is gated on `sawReady && sawInit`, and the very\n // chunk that carries the `init` event is what flips `sawInit` — parsing first lets that\n // same chunk's processing arm the timer immediately, rather than requiring a chunk AFTER\n // init to ever arrive (which, on a genuinely idle stream, never happens).\n eventReader.push(chunk)\n armIdleTimer()\n })\n child.stdout?.on('end', () => {\n // A terminal `result`/`error` event was already observed and its own handler is (or will\n // shortly be) in the middle of its own `settleOnce` — defer to it rather than racing it\n // with a wrong \"stdout ended without a terminal event\" nack for what was actually a\n // successful turn. `sawTerminalEvent` is set synchronously by that handler before any\n // `await`, so it is already true here whenever this really is that race.\n if (sawTerminalEvent) return\n settleOnce(() => {\n finish()\n ctx.nack(\n new E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO([\n 0,\n 'stdout ended without a terminal event',\n ])\n )\n })\n })\n\n void Promise.resolve(child)\n .then((result: unknown) => {\n // Same race as the `stdout.on('end')` guard above: the `result` handler may still be\n // awaiting `sealCurrentMessage()`/the child's own exit when the wrapper process itself\n // settles — defer to the terminal-event path rather than nacking a successful turn.\n if (sawTerminalEvent) return\n const exitCode =\n isObject(result) && 'exitCode' in result\n ? ((result as { exitCode: number | null }).exitCode ?? -1)\n : -1\n settleOnce(() => {\n finish()\n ctx.nack(\n new E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO([\n exitCode,\n 'wrapper process exited with no terminal event observed',\n ])\n )\n })\n })\n .catch(() => {\n if (sawTerminalEvent) return\n settleOnce(() => {\n finish()\n ctx.nack(new E_CLAUDE_CODE_CLI_WRAPPER_CRASHED(['wrapper process rejected']))\n })\n })\n })\n }\n }\n\n /**\n * Returns `true` when `value` is a {@link ClaudeCodeCliAdapter} instance.\n */\n public static isClaudeCodeCliAdapter(value: unknown): value is ClaudeCodeCliAdapter {\n return isInstanceOf(value, 'ClaudeCodeCliAdapter', ClaudeCodeCliAdapter)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+FA,IAAa,kCAA0C;CAKrD,IAAI,OAAO,YAAY,cAAc,OAAO,QAAQ,YAAY,YAC9D,OAAO,QAAQ,QAAQ,sCAAsC;CAY/D,OAAO,mBACL,IAAA,IAAA,wCAAA,KAAA,CAAA,EAAA,GAAA,EAAiE,QACnE;AACF;AAIA,IAAM,eAAe,OAAO,aAA4D;CACtF,IAAI,QACF,mBAAmB,OAAO;CAC5B,IAAI,OAAO,UAAU,cAAc,EAAE,UAAW,QAC9C,IAAI;EACF,QAAQ,MAAO,MAAwB;CACzC,SAAS,KAAK;EAEZ,MAAM,IAAI,iDAAA,sCAAsC,CAC9C,0BAFa,eAAA,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG,EAEnB,mEACnC,CAAC;CACH;CAEF,IAAI,eAAA,SAAS,KAAK,KAAK,WAAW,OAChC,QAAS,MAA6B;CAExC,IAAI,OAAO,UAAU,YACnB,MAAM,IAAI,iDAAA,sCAAsC,CAC9C,8CACF,CAAC;CAEH,OAAO;AACT;AAIA,IAAM,eACJ,WACkB;CAClB,IAAI;CACJ,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,CAAC,OAAO;EACZ,SAAS;GAAE,GAAI,UAAW,CAAC;GAAU,GAAG;EAAM;CAChD;CACA,OAAO;AACT;AAEA,IAAM,gB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,aAAa,OAAO,wBAAwB,oBAAoB;CACzE;AACF"}
@@ -1,13 +1,13 @@
1
1
  import { i as __require } from "../../../chunk-Cf1989ZW.mjs";
2
2
  import { n as isInstanceOf, r as isObject, t as isError } from "../../../guards-BEpY7lBI.mjs";
3
- import { r as Tokenizable } from "../../../tokenizable-DLMP68ZV.mjs";
4
- import { d as ArtifactTool, h as canonicalStringify, t as SpooledArtifact } from "../../../spooled_artifact-BkueYJhR.mjs";
5
- import { n as Message } from "../../../thought-B8JAi3-W.mjs";
6
- import { n as Media, t as ToolCall } from "../../../tool_call-CPjyvkm4.mjs";
7
- import "../../../common-v9Jo9M5k.mjs";
3
+ import { r as Tokenizable } from "../../../tokenizable-VB4Av8GF.mjs";
4
+ import { f as ArtifactTool, h as canonicalStringify, t as SpooledArtifact } from "../../../spooled_artifact-Bw_7swIp.mjs";
5
+ import { n as Message } from "../../../thought-BE1KGEhV.mjs";
6
+ import { n as Media, t as ToolCall } from "../../../tool_call-Cfaj-6zK.mjs";
7
+ import "../../../common-BpdHIpQE.mjs";
8
8
  import "../../../guards.mjs";
9
9
  import { InMemorySpoolStore } from "../../storage/in_memory.mjs";
10
- import { C as looksLikeSpooledArtifact, D as renderArtifactHandleBody, _ as defaultRenderUntrustedContent, c as defaultRenderMemories, d as defaultRenderRetrievables, f as defaultRenderStandingInstructions, g as defaultRenderTrustedContent, h as defaultRenderThought, i as defaultFilterThoughts, l as defaultRenderRetrievableHandleBody, m as defaultRenderThirdPartyPublicRetrievables, o as defaultRenderChatCompletionsSystemPrompt, p as defaultRenderThirdPartyPrivateRetrievables, r as defaultDescriptionToChatCompletionsJsonSchema, s as defaultRenderFirstPartyRetrievables, u as defaultRenderRetrievableSafetyDirective, v as defaultToolsToChatCompletionsTools } from "../../../helpers-CDmLDBq5.mjs";
10
+ import { C as looksLikeSpooledArtifact, D as renderArtifactHandleBody, _ as defaultRenderUntrustedContent, c as defaultRenderMemories, d as defaultRenderRetrievables, f as defaultRenderStandingInstructions, g as defaultRenderTrustedContent, h as defaultRenderThought, i as defaultFilterThoughts, l as defaultRenderRetrievableHandleBody, m as defaultRenderThirdPartyPublicRetrievables, o as defaultRenderChatCompletionsSystemPrompt, p as defaultRenderThirdPartyPrivateRetrievables, r as defaultDescriptionToChatCompletionsJsonSchema, s as defaultRenderFirstPartyRetrievables, u as defaultRenderRetrievableSafetyDirective, v as defaultToolsToChatCompletionsTools } from "../../../helpers-BH7HTtkD.mjs";
11
11
  import { E_CLAUDE_CODE_CLI_CONTEXT_OVERFLOW, E_CLAUDE_CODE_CLI_MCP_BRIDGE_STARTUP_FAILED, E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO, E_CLAUDE_CODE_CLI_STARTUP_TIMEOUT, E_CLAUDE_CODE_CLI_STREAM_STALLED, E_CLAUDE_CODE_CLI_TURN_FAILED, E_CLAUDE_CODE_CLI_WRAPPER_CRASHED, E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR, E_INVALID_CLAUDE_CODE_CLI_OPTIONS } from "./exceptions.mjs";
12
12
  import { validateOptions } from "./validation.mjs";
13
13
  import { createNdjsonLineReader, encodeWrapperCommand } from "./wire.mjs";
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.mjs","names":["#baseline"],"sources":["../../../../src/batteries/llm/claude_code_cli/adapter.ts"],"sourcesContent":["/**\n * Cross-environment executor adapter that wraps the Claude Code CLI as a `DispatchExecutorFn`\n * destination.\n *\n * @module @nhtio/adk/batteries/llm/claude_code_cli/adapter\n *\n * @remarks\n * The first battery in the \"CLI harness\" family: rather than a direct wire-format provider, this\n * adapter drives an external coding-agent CLI binary that is itself a complete agent loop. Since a\n * subprocess must be spawned anyway, ALL Claude-Code-specific complexity — spawning the real\n * `claude` binary, hosting an MCP bridge server, translating its stream-json — lives in a\n * dedicated wrapper process (`wrapper.ts`, shipped as a sibling dist asset); this adapter only\n * ever spawns and drives that wrapper over the small, harness-agnostic protocol in `./wire`.\n *\n * Every dispatch iteration is stateless and self-contained: the full accumulated history renders\n * into one `-p` prompt string (`buildClaudeCodeCliPrompt`), a fresh wrapper is spawned, and real\n * ADK tools are bridged into the CLI's own tool loop via MCP — but actual execution always happens\n * on the ADK side, through `tool.executor(ctx)(args)`, exactly like every other LLM battery.\n */\n\nimport { sha256 } from 'js-sha256'\nimport { validateOptions } from './validation'\nimport { isError, isObject, isInstanceOf } from '@nhtio/adk/guards'\nimport { createNdjsonLineReader, encodeWrapperCommand } from './wire'\nimport { canonicalStringify } from '../../../lib/utils/canonical_json'\nimport { InMemorySpoolStore } from '@nhtio/adk/batteries/storage/in_memory'\nimport {\n Tokenizable,\n ToolCall,\n Memory,\n Message,\n Media,\n ArtifactTool,\n SpooledArtifact,\n TokenEncoding,\n} from '@nhtio/adk/common'\nimport {\n E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR,\n E_CLAUDE_CODE_CLI_WRAPPER_CRASHED,\n E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO,\n E_CLAUDE_CODE_CLI_STREAM_STALLED,\n E_CLAUDE_CODE_CLI_STARTUP_TIMEOUT,\n E_CLAUDE_CODE_CLI_MCP_BRIDGE_STARTUP_FAILED,\n E_CLAUDE_CODE_CLI_TURN_FAILED,\n E_INVALID_CLAUDE_CODE_CLI_OPTIONS,\n E_CLAUDE_CODE_CLI_CONTEXT_OVERFLOW,\n} from './exceptions'\nimport {\n defaultDescriptionToChatCompletionsJsonSchema,\n defaultRenderUntrustedContent,\n defaultRenderTrustedContent,\n defaultRenderStandingInstructions,\n defaultRenderMemories,\n defaultRenderRetrievables,\n defaultRenderRetrievableHandleBody,\n defaultRenderRetrievableSafetyDirective,\n defaultRenderFirstPartyRetrievables,\n defaultRenderThirdPartyPublicRetrievables,\n defaultRenderThirdPartyPrivateRetrievables,\n defaultRenderThought,\n defaultFilterThoughts,\n defaultToolsToChatCompletionsTools,\n defaultRenderChatCompletionsSystemPrompt,\n defaultRenderClaudeCodeCliTimelineMessage,\n defaultRenderClaudeCodeCliToolCallResult,\n defaultBuildClaudeCodeCliPrompt,\n renderArtifactHandleBody,\n looksLikeSpooledArtifact,\n} from './helpers'\nimport type { Tool } from '@nhtio/adk/common'\nimport type { SpoolStore } from '@nhtio/adk/common'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type { WrapperEvent, WrapperCommand, WrapperBridgedTool } from './wire'\nimport type { DispatchExecutorFn, DispatchExecutorHelpers } from '@nhtio/adk/dispatch_runner'\nimport type {\n ClaudeCodeCliAdapterOptions,\n ClaudeCodeCliHelpers,\n ExecaLike,\n ExecaResolver,\n UnsupportedMediaPolicy,\n} from './types'\n\ntype OutboundContentBlock =\n | { type: 'text'; text: string }\n | { type: 'image'; data: string; mimeType: string }\n\n// ─── wrapper path resolution (Decision C) ──────────────────────────────────────\n\n/**\n * Resolve the built wrapper asset's on-disk path relative to this module's own compiled location.\n * `adapter.ts` carries its own `@module` tag (per the per-file tagging convention every other\n * multi-file battery uses), so it compiles to `dist/batteries/llm/claude_code_cli/adapter.mjs` —\n * three directories below the package root, where the wrapper (an explicit, un-tagged\n * `vite.config.mts` entry key) compiles to `dist/claude-code-cli-wrapper.mjs`.\n */\nexport const resolveDefaultWrapperPath = (): string => {\n // `typeof require === 'function'` alone is not a safe CJS-vs-ESM discriminator: rolldown's ESM\n // output wraps `require` in a shim/Proxy (falling back to itself when the real `require` is\n // absent) that still reports `typeof === 'function'`, but whose `.resolve` is not itself a\n // function — calling it throws instead of falling through to the URL-based ESM branch below.\n if (typeof require === 'function' && typeof require.resolve === 'function') {\n return require.resolve('../../../claude-code-cli-wrapper.cjs')\n }\n // `URL.pathname` is percent-encoded — a real install path containing a space, unicode, or any\n // other URL-reserved character would produce a non-existent argv path (e.g. `%20` instead of a\n // literal space) once handed to `execaFn`/`spawn` below. `decodeURIComponent` undoes that percent\n // encoding to recover the native filesystem path — equivalent to `node:url`'s `fileURLToPath` for\n // a POSIX path (verified directly), which this module avoids importing at module scope: this\n // file is transitively pulled into the browser test project via `src/batteries`'s barrel (e.g.\n // `tests/unit/batteries/index.cross.spec.ts`), and Vite externalizes `node:url` there, throwing\n // on any access to `fileURLToPath` at import time. This battery is POSIX-only in v1 anyway\n // (validated at options-construction time), so a POSIX-only decode is exactly the right amount\n // of `node:url` behavior to reimplement without importing it.\n return decodeURIComponent(\n new URL('../../../claude-code-cli-wrapper.mjs', import.meta.url).pathname\n )\n}\n\n// ─── execa resolution (mirrors execa_executor.ts's lazy-resolver pattern) ──────\n\nconst resolveExeca = async (supplied: ExecaResolver | undefined): Promise<ExecaLike> => {\n let value: unknown =\n supplied ?? (() => import('execa') as unknown as Promise<{ execa: ExecaLike }>)\n if (typeof value === 'function' && !('exec' in (value as object))) {\n try {\n value = await (value as () => unknown)()\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n throw new E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR([\n `execa resolver failed: ${detail} — install the optional peer dependency \"execa\" or supply your own`,\n ])\n }\n }\n if (isObject(value) && 'execa' in value) {\n value = (value as { execa: unknown }).execa\n }\n if (typeof value !== 'function') {\n throw new E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR([\n 'execa resolver did not resolve to a function',\n ])\n }\n return value as ExecaLike\n}\n\n// ─── option merging ─────────────────────────────────────────────────────────\n\nconst mergeRecord = <T extends Record<string, unknown>>(\n layers: ReadonlyArray<T | undefined>\n): T | undefined => {\n let merged: T | undefined\n for (const layer of layers) {\n if (!layer) continue\n merged = { ...(merged ?? ({} as T)), ...layer }\n }\n return merged\n}\n\nconst mergeOptions = (\n baseline: ClaudeCodeCliAdapterOptions,\n exec: Partial<ClaudeCodeCliAdapterOptions> | undefined,\n stash: Partial<ClaudeCodeCliAdapterOptions> | undefined\n): Partial<ClaudeCodeCliAdapterOptions> => {\n const layers = [baseline as Partial<ClaudeCodeCliAdapterOptions>, exec ?? {}, stash ?? {}]\n const out: Record<string, unknown> = {}\n for (const layer of layers) {\n for (const [k, v] of Object.entries(layer)) {\n if (v === undefined) continue\n if (k === 'helpers') continue\n out[k] = v\n }\n }\n const helpers = mergeRecord(layers.map((l) => l.helpers as Record<string, unknown> | undefined))\n if (helpers !== undefined) out.helpers = helpers\n return out as Partial<ClaudeCodeCliAdapterOptions>\n}\n\nconst resolveHelpers = (\n overrides: Partial<ClaudeCodeCliHelpers> | undefined\n): ClaudeCodeCliHelpers => {\n const src = overrides ?? {}\n return {\n descriptionToChatCompletionsJsonSchema:\n src.descriptionToChatCompletionsJsonSchema ?? defaultDescriptionToChatCompletionsJsonSchema,\n renderUntrustedContent: src.renderUntrustedContent ?? defaultRenderUntrustedContent,\n renderTrustedContent: src.renderTrustedContent ?? defaultRenderTrustedContent,\n renderStandingInstructions: src.renderStandingInstructions ?? defaultRenderStandingInstructions,\n renderMemories: src.renderMemories ?? defaultRenderMemories,\n renderRetrievables: src.renderRetrievables ?? defaultRenderRetrievables,\n renderRetrievableHandleBody:\n src.renderRetrievableHandleBody ?? defaultRenderRetrievableHandleBody,\n renderRetrievableSafetyDirective:\n src.renderRetrievableSafetyDirective ?? defaultRenderRetrievableSafetyDirective,\n renderFirstPartyRetrievables:\n src.renderFirstPartyRetrievables ?? defaultRenderFirstPartyRetrievables,\n renderThirdPartyPublicRetrievables:\n src.renderThirdPartyPublicRetrievables ?? defaultRenderThirdPartyPublicRetrievables,\n renderThirdPartyPrivateRetrievables:\n src.renderThirdPartyPrivateRetrievables ?? defaultRenderThirdPartyPrivateRetrievables,\n renderThought: src.renderThought ?? defaultRenderThought,\n filterThoughts: src.filterThoughts ?? defaultFilterThoughts,\n toolsToChatCompletionsTools:\n src.toolsToChatCompletionsTools ?? defaultToolsToChatCompletionsTools,\n renderChatCompletionsSystemPrompt:\n src.renderChatCompletionsSystemPrompt ?? defaultRenderChatCompletionsSystemPrompt,\n renderClaudeCodeCliTimelineMessage:\n src.renderClaudeCodeCliTimelineMessage ?? defaultRenderClaudeCodeCliTimelineMessage,\n renderClaudeCodeCliToolCallResult:\n src.renderClaudeCodeCliToolCallResult ?? defaultRenderClaudeCodeCliToolCallResult,\n buildClaudeCodeCliPrompt: src.buildClaudeCodeCliPrompt ?? defaultBuildClaudeCodeCliPrompt,\n }\n}\n\nconst estimateTokensOf = async (\n value: { estimateTokens: (encoding: TokenEncoding) => number | Promise<number> },\n encoding: TokenEncoding\n): Promise<number> => Promise.resolve(value.estimateTokens(encoding))\n\n// ─── time / checksum helpers ────────────────────────────────────────────────\n\nconst nowIso = (): string => new Date().toISOString()\n\n/**\n * Integrity checksum over `tool`/`args` — matches every other LLM battery's convention\n * (`sha256(canonicalStringify({tool, args}))`, see `ollama/adapter.ts`'s `computeChecksum`), NOT\n * the per-call `requestId`. Identical repeat calls must share this checksum: it feeds\n * `DispatchContext`'s own `#toolCallChecksums` loop-detection counter and cross-bus correlation,\n * neither of which can see a repeat if every call gets a unique value.\n */\nconst computeChecksum = (tool: string, args: unknown): string =>\n sha256(canonicalStringify({ tool, args }))\n\n// ─── outbound tool-result rendering (decision 8) ───────────────────────────────\n\nconst renderMediaListAsOutbound = async (\n mediaList: Media[],\n unsupportedResultMediaPolicy: UnsupportedMediaPolicy\n): Promise<{ content: OutboundContentBlock[]; isError: boolean }> => {\n const content: OutboundContentBlock[] = []\n let anyUnsupported = false\n for (const media of mediaList) {\n if (media.kind === 'image') {\n content.push({ type: 'image', data: await media.asBase64(), mimeType: media.mimeType })\n continue\n }\n // Every non-image modality is unsupported on the outbound MCP wire (only text/image content\n // blocks exist there) — routed through the SAME policy family the inbound direction uses\n // (decision 8), rather than an unconditional hardcoded error.\n if (unsupportedResultMediaPolicy === 'throw') {\n anyUnsupported = true\n content.push({\n type: 'text',\n text: `Unsupported result media modality: ${media.kind} (${media.mimeType})`,\n })\n continue\n }\n const byteLen = await media.byteLength().catch(() => undefined)\n content.push({\n type: 'text',\n text: `[media: ${media.filename}, ${media.mimeType}, ${byteLen ?? 'unknown'} bytes]`,\n })\n }\n return { content, isError: anyUnsupported }\n}\n\nconst renderOutboundResult = async (input: {\n raw: string | Uint8Array | SpooledArtifact | Media | Media[]\n callId: string\n inline: boolean\n spoolStore: SpoolStore\n unsupportedResultMediaPolicy: UnsupportedMediaPolicy\n}): Promise<{ content: OutboundContentBlock[]; isError: boolean }> => {\n const { raw, callId, inline } = input\n\n if (Media.isMedia(raw)) {\n return renderMediaListAsOutbound([raw], input.unsupportedResultMediaPolicy)\n }\n if (Array.isArray(raw) && raw.length > 0 && raw.every((m) => Media.isMedia(m))) {\n return renderMediaListAsOutbound(raw, input.unsupportedResultMediaPolicy)\n }\n if (looksLikeSpooledArtifact(raw)) {\n const artifact = raw as SpooledArtifact\n if (inline === false) {\n let byteLength = 0\n let lineCount = 0\n try {\n byteLength = await artifact.byteLength()\n } catch {\n byteLength = 0\n }\n try {\n lineCount = await artifact.lineCount()\n } catch {\n lineCount = 0\n }\n const body = renderArtifactHandleBody({ callId, artifact, byteLength, lineCount })\n return { content: [{ type: 'text', text: body }], isError: false }\n }\n const text = await artifact.asString()\n return { content: [{ type: 'text', text }], isError: false }\n }\n if (typeof raw === 'string') {\n return { content: [{ type: 'text', text: raw }], isError: false }\n }\n if (isInstanceOf(raw, 'Uint8Array', Uint8Array)) {\n await input.spoolStore.write(callId, raw)\n return {\n content: [{ type: 'text', text: '[binary tool result — see history for details]' }],\n isError: false,\n }\n }\n return { content: [{ type: 'text', text: String(raw) }], isError: false }\n}\n\n// ─── the adapter ────────────────────────────────────────────────────────────\n\n/**\n * Opinionated CLI-harness LLM adapter that drives the Claude Code CLI as a `DispatchExecutorFn`\n * destination.\n *\n * @remarks\n * Construction validates options eagerly via {@link validateOptions} and throws\n * {@link @nhtio/adk/batteries/llm/claude_code_cli!E_INVALID_CLAUDE_CODE_CLI_OPTIONS} on failure\n * (including the POSIX-only platform guard and the `apiKey`/`authToken` XOR check). The returned\n * instance is reusable: call {@link ClaudeCodeCliAdapter.executor} once per `DispatchRunner`\n * configuration.\n */\nexport class ClaudeCodeCliAdapter {\n /** Customary key for per-iteration overrides on `ctx.stash`. */\n public static readonly STASH_KEY = 'claudeCodeCli' as const\n\n readonly #baseline: ClaudeCodeCliAdapterOptions\n\n /**\n * @param options - Constructor-baseline options. Re-validated on every iteration after\n * per-dispatch and per-iteration overrides are layered in.\n * @throws {@link @nhtio/adk/batteries/llm/claude_code_cli!E_INVALID_CLAUDE_CODE_CLI_OPTIONS} when\n * `options` does not satisfy `claudeCodeCliOptionsSchema`.\n */\n constructor(options: unknown) {\n this.#baseline = validateOptions(options)\n }\n\n /**\n * Returns a {@link @nhtio/adk!DispatchExecutorFn} bound to this adapter's baseline plus optional\n * executor-scope overrides.\n */\n executor(overrides?: Partial<ClaudeCodeCliAdapterOptions>): DispatchExecutorFn {\n const baseline = this.#baseline\n const adapterClass = ClaudeCodeCliAdapter\n\n return async (ctx: DispatchContext, helpers: DispatchExecutorHelpers): Promise<void> => {\n const localWarn = (msg: string): void => {\n helpers.log.warn({ kind: 'helper-warning', message: msg })\n }\n\n // ── Step 1: merge & validate ──────────────────────────────────────────\n const stashRaw = ctx.stash.get(adapterClass.STASH_KEY, {}) as unknown\n const stashOverrides =\n stashRaw && typeof stashRaw === 'object'\n ? (stashRaw as Partial<ClaudeCodeCliAdapterOptions>)\n : {}\n const merged = validateOptions(mergeOptions(baseline, overrides, stashOverrides))\n\n if (merged.tokenEncoding !== null && merged.contextWindow === undefined) {\n throw new E_INVALID_CLAUDE_CODE_CLI_OPTIONS([\n 'tokenEncoding is non-null but contextWindow is undefined',\n ])\n }\n\n // ── Step 2: resolve helpers ───────────────────────────────────────────\n const resolvedHelpers = resolveHelpers(merged.helpers)\n\n // ── Step 3: resolve execa + wrapper path ──────────────────────────────\n let execaFn: ExecaLike\n try {\n execaFn = await resolveExeca(merged.execa)\n } catch (err) {\n ctx.nack(isError(err) ? err : new Error(String(err)))\n return\n }\n const wrapperPath = merged.wrapperPath ?? resolveDefaultWrapperPath()\n const claudeBin = merged.claudeBin ?? 'claude'\n\n // ── Step 5: pre-render inbound tool-call results (for history) ────────\n // Key by primitive identity, not id: repeated vendor/request ids must not cross-wire results.\n const renderedToolCallResults = new Map<ToolCall, string>()\n for (const tc of ctx.turnToolCalls) {\n const rendered = await resolvedHelpers.renderClaudeCodeCliToolCallResult({\n toolCall: tc,\n results: tc.results as\n | Tokenizable\n | SpooledArtifact\n | SpooledArtifact[]\n | Media\n | Media[],\n tool: ctx.tools.get(tc.tool) as Tool | undefined,\n renderUntrustedContent: resolvedHelpers.renderUntrustedContent,\n renderTrustedContent: resolvedHelpers.renderTrustedContent,\n unsupportedMediaPolicy: merged.unsupportedMediaPolicy ?? 'throw',\n warn: localWarn,\n })\n renderedToolCallResults.set(tc, rendered)\n }\n\n // ── Step 6: build the -p prompt ────────────────────────────────────────\n const { prompt, reasoningPayloads } = await resolvedHelpers.buildClaudeCodeCliPrompt({\n systemPrompt: ctx.systemPrompt,\n renderCtx: ctx,\n standingInstructions: ctx.standingInstructions,\n memories: ctx.turnMemories,\n retrievables: ctx.turnRetrievables,\n messages: ctx.turnMessages,\n thoughts: ctx.turnThoughts,\n toolCalls: ctx.turnToolCalls,\n tools: ctx.tools,\n renderedToolCallResults,\n bucketOrder: merged.bucketOrder ?? [\n 'standingInstructions',\n 'memories',\n 'retrievables',\n 'timeline',\n ],\n selfIdentity: merged.selfIdentity ?? 'assistant',\n thoughtSurfacing: merged.thoughtSurfacing ?? 'all-self',\n replayCompatibility: merged.replayCompatibility ?? [],\n unsupportedMediaPolicy: merged.unsupportedMediaPolicy ?? 'throw',\n renderChatCompletionsSystemPrompt: resolvedHelpers.renderChatCompletionsSystemPrompt,\n renderStandingInstructions: resolvedHelpers.renderStandingInstructions,\n renderMemories: resolvedHelpers.renderMemories,\n renderRetrievables: resolvedHelpers.renderRetrievables,\n renderRetrievableSafetyDirective: resolvedHelpers.renderRetrievableSafetyDirective,\n renderFirstPartyRetrievables: resolvedHelpers.renderFirstPartyRetrievables,\n renderThirdPartyPublicRetrievables: resolvedHelpers.renderThirdPartyPublicRetrievables,\n renderThirdPartyPrivateRetrievables: resolvedHelpers.renderThirdPartyPrivateRetrievables,\n renderRetrievableHandleBody: resolvedHelpers.renderRetrievableHandleBody,\n renderClaudeCodeCliTimelineMessage: resolvedHelpers.renderClaudeCodeCliTimelineMessage,\n renderClaudeCodeCliToolCallResult: resolvedHelpers.renderClaudeCodeCliToolCallResult,\n renderThought: resolvedHelpers.renderThought,\n filterThoughts: resolvedHelpers.filterThoughts,\n renderUntrustedContent: resolvedHelpers.renderUntrustedContent,\n renderTrustedContent: resolvedHelpers.renderTrustedContent,\n warn: localWarn,\n })\n\n // A `-p` prompt string has no side channel for an opaque, vendor-specific reasoning payload\n // the way Ollama/OpenAI's JSON request bodies do (`_adk_reasoning_payloads`) — there is\n // nowhere in this wire to forward one. Surface that loss as a diagnostic rather than\n // silently dropping it, matching the honesty standard applied to every other documented v1\n // limitation of this battery (text-only media, subagent text).\n if (reasoningPayloads.length > 0) {\n helpers.log.debug({\n kind: 'reasoning-payload-dropped',\n message: `${reasoningPayloads.length} opaque reasoning payload(s) matched replayCompatibility but have no destination on the Claude Code CLI wire (no side channel exists for a '-p' prompt) and were dropped.`,\n })\n }\n\n // ── Step 7: build the bridged-tools set (excluding disallowedTools) ───\n const disallowed = new Set(merged.disallowedTools ?? [])\n const visibleTools = ctx.tools.visible().filter((t) => !disallowed.has(t.name))\n const bridgedTools: WrapperBridgedTool[] = visibleTools.map((t) => {\n const described = t.describe()\n const inputSchema = resolvedHelpers.descriptionToChatCompletionsJsonSchema(\n described.inputSchema as never\n )\n return {\n name: described.name,\n description: described.description,\n inputSchema:\n inputSchema && Object.keys(inputSchema).length > 0\n ? (inputSchema as Record<string, unknown>)\n : { type: 'object', properties: {} },\n }\n })\n\n // ── Step 8: context window enforcement ────────────────────────────────\n if (merged.tokenEncoding !== null && merged.contextWindow !== undefined) {\n const encoding = merged.tokenEncoding as TokenEncoding\n // The rendered prompt is the actual `-p` wire value. Measure it directly rather than\n // re-summing its source buckets: renderers add envelopes, provenance, and ordering.\n const promptTokens = await estimateTokensOf(new Tokenizable(prompt), encoding)\n const appendSystemPromptTokens = merged.appendSystemPrompt\n ? await estimateTokensOf(new Tokenizable(merged.appendSystemPrompt), encoding)\n : 0\n\n // Keep source-bucket diagnostics for middleware deciding what to shed. They are not part\n // of the authoritative total above, since their content is already represented by prompt.\n const rawSystemPrompt = await estimateTokensOf(ctx.systemPrompt, encoding)\n let rawStandingInstructions = 0\n for (const value of ctx.standingInstructions)\n rawStandingInstructions += await estimateTokensOf(value, encoding)\n let rawMemories = 0\n for (const value of ctx.turnMemories as Set<Memory>)\n rawMemories += await estimateTokensOf(value.content, encoding)\n let rawRetrievables = 0\n for (const r of ctx.turnRetrievables) {\n rawRetrievables +=\n !r.inline && SpooledArtifact.isSpooledArtifact(r.content) && r.content.hasSizeHints()\n ? r.content.estimateHandleTokens(\n r.id,\n encoding,\n resolvedHelpers.renderRetrievableHandleBody\n )\n : await estimateTokensOf(r.content, encoding)\n }\n let rawTimeline = 0\n for (const msg of ctx.turnMessages)\n if (msg.content !== undefined)\n rawTimeline += await estimateTokensOf(msg.content, encoding)\n for (const thought of ctx.turnThoughts)\n rawTimeline += await estimateTokensOf(thought.content, encoding)\n for (const rendered of renderedToolCallResults.values())\n rawTimeline += await estimateTokensOf(new Tokenizable(rendered), encoding)\n // Claude Code receives declarations through MCP, not a wire `tools` array. This stable\n // serialization is an honest floor: JSON declarations plus the CLI-visible names.\n const toolSerialization = `${JSON.stringify(bridgedTools)}|${bridgedTools\n .map((t) => `mcp__adk_bridge__${t.name}`)\n .join(',')}`\n const tools = await estimateTokensOf(new Tokenizable(toolSerialization), encoding)\n const perBucket = {\n prompt: promptTokens,\n appendSystemPrompt: appendSystemPromptTokens,\n tools,\n raw: {\n systemPrompt: rawSystemPrompt,\n standingInstructions: rawStandingInstructions,\n memories: rawMemories,\n retrievables: rawRetrievables,\n timeline: rawTimeline,\n },\n }\n const total = promptTokens + appendSystemPromptTokens + tools\n helpers.log.debug({\n kind: 'context-window-usage',\n message: `Context window usage: ${total}/${merged.contextWindow} tokens`,\n payload: { total, limit: merged.contextWindow, encoding, perBucket },\n })\n if (total > merged.contextWindow)\n throw new E_CLAUDE_CODE_CLI_CONTEXT_OVERFLOW([\n total,\n merged.contextWindow,\n encoding,\n JSON.stringify(perBucket),\n ])\n }\n\n // ── Step 9: spawn the wrapper ──────────────────────────────────────────\n const spoolStore = merged.spoolStore ?? new InMemorySpoolStore()\n let child: ReturnType<ExecaLike>\n try {\n child = execaFn(process.execPath, [wrapperPath], { cleanup: true })\n } catch (err) {\n ctx.nack(\n new E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR([isError(err) ? err.message : String(err)])\n )\n return\n }\n\n const startupTimeoutMs = merged.startupTimeoutMs ?? 45_000\n const streamIdleTimeoutMs = merged.streamIdleTimeoutMs ?? 60_000\n const disposeGraceMs = merged.disposeGraceMs ?? 2_000\n\n let sawReady = false\n let sawInit = false\n // Set SYNCHRONOUSLY the instant a terminal `result`/`error` event is observed — before any\n // `await` (e.g. `sealCurrentMessage()`) runs. The wrapper closing stdout immediately after\n // writing its terminal line is a real, observed race: without this flag, `stdout`'s `'end'`\n // handler can fire and call `settleOnce` (nacking the turn as an unexpected exit) while the\n // `result` handler is still awaiting `sealCurrentMessage()`, even though `settleOnce` itself\n // is idempotent-guarded — the guard only helps once one of the two paths has actually run.\n let sawTerminalEvent = false\n let startupTimer: ReturnType<typeof setTimeout> | undefined\n let idleTimer: ReturnType<typeof setTimeout> | undefined\n let settled = false\n // Set once the outer `await new Promise<void>(...)` below is constructed. The startup/idle\n // timers are armed BEFORE that promise exists, so their settleOnce() callbacks must resolve\n // it through this indirection rather than a `finish` closure defined only inside it — without\n // this, a startup or stream-idle timeout would settle ctx (nack) but never resolve the outer\n // promise, hanging the executor forever.\n let resolveIteration: (() => void) | undefined\n let currentMessageId: string | undefined\n let currentMessageBuffer = ''\n let sealedMessage = false\n\n const clearStartupTimer = (): void => {\n if (startupTimer) clearTimeout(startupTimer)\n startupTimer = undefined\n }\n const clearIdleTimer = (): void => {\n if (idleTimer) clearTimeout(idleTimer)\n idleTimer = undefined\n }\n const maybeClearStartupTimer = (): void => {\n if (sawReady && sawInit) clearStartupTimer()\n }\n\n const writeCommand = (command: WrapperCommand): void => {\n try {\n child.stdin?.write(encodeWrapperCommand(command))\n } catch {\n /* the wrapper's stdin may already be gone */\n }\n }\n\n const gracefulShutdown = async (): Promise<void> => {\n writeCommand({ type: 'shutdown' })\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, disposeGraceMs)\n void Promise.resolve(child).finally(() => {\n clearTimeout(timer)\n resolve()\n })\n })\n try {\n child.kill('SIGTERM')\n } catch {\n /* already exited */\n }\n }\n\n const abortListener = (): void => {\n void gracefulShutdown()\n }\n ctx.abortSignal.addEventListener('abort', abortListener, { once: true })\n const detachAbortListener = (): void =>\n ctx.abortSignal.removeEventListener('abort', abortListener)\n\n const settleOnce = (fn: () => void): void => {\n if (settled) return\n settled = true\n clearStartupTimer()\n clearIdleTimer()\n detachAbortListener()\n fn()\n }\n\n startupTimer = setTimeout(() => {\n settleOnce(() => {\n resolveIteration?.()\n void gracefulShutdown()\n ctx.nack(new E_CLAUDE_CODE_CLI_STARTUP_TIMEOUT([startupTimeoutMs]))\n })\n }, startupTimeoutMs)\n\n const armIdleTimer = (): void => {\n if (!sawReady || !sawInit) return\n clearIdleTimer()\n idleTimer = setTimeout(() => {\n settleOnce(() => {\n resolveIteration?.()\n void gracefulShutdown()\n ctx.nack(new E_CLAUDE_CODE_CLI_STREAM_STALLED([streamIdleTimeoutMs]))\n })\n }, streamIdleTimeoutMs)\n }\n\n const sealCurrentMessage = async (): Promise<void> => {\n if (sealedMessage || currentMessageId === undefined) return\n sealedMessage = true\n await ctx.storeMessage(\n new Message({\n id: currentMessageId,\n role: 'assistant',\n content: currentMessageBuffer,\n identity: merged.selfIdentity ?? 'assistant',\n createdAt: nowIso(),\n updatedAt: nowIso(),\n })\n )\n }\n\n const handleToolCallRequest = async (\n requestId: string,\n toolName: string,\n rawArgs: unknown\n ): Promise<void> => {\n const tool = ctx.tools.get(toolName)\n if (!tool) {\n writeCommand({\n type: 'tool_call_response',\n requestId,\n results: {\n content: [{ type: 'text', text: `Tool not found: ${toolName}` }],\n isError: true,\n },\n })\n return\n }\n // MCP's own JSON-RPC CallTool wire always sends `arguments` as an object; a non-object\n // here would indicate a malformed request from the bridge, not a legitimate call — defend\n // the same way the Ollama battery does for its own non-object case.\n const args: string | Record<string, unknown> = isObject(rawArgs) ? rawArgs : {}\n helpers.reportToolCall(requestId, { tool: tool.name, args })\n const isArtifactTool = ArtifactTool.isArtifactTool(tool)\n let results: Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[] =\n new Tokenizable('')\n let toolHadError = false\n try {\n const raw = await tool.executor(ctx)(args)\n if (isArtifactTool) {\n if (Tokenizable.isTokenizable(raw)) {\n results = raw\n } else if (typeof raw === 'string') {\n results = new Tokenizable(raw)\n } else {\n throw new Error(\n `ArtifactTool \"${tool.name}\" returned a non-string/non-Tokenizable value`\n )\n }\n } else if (Media.isMedia(raw)) {\n results = raw\n } else if (Array.isArray(raw) && raw.length > 0 && raw.every((m) => Media.isMedia(m))) {\n results = raw as Media[]\n } else if (looksLikeSpooledArtifact(raw)) {\n results = raw as SpooledArtifact\n } else if (typeof raw === 'string' || isInstanceOf(raw, 'Uint8Array', Uint8Array)) {\n const reader = await spoolStore.write(requestId, raw)\n const ArtifactCtor = (tool as Tool).artifactConstructor?.() ?? SpooledArtifact\n results = new ArtifactCtor(reader)\n } else {\n const reader = await spoolStore.write(requestId, String(raw))\n const ArtifactCtor = (tool as Tool).artifactConstructor?.() ?? SpooledArtifact\n results = new ArtifactCtor(reader)\n }\n } catch (err) {\n toolHadError = true\n results = new Tokenizable(isError(err) ? err.message : String(err))\n }\n helpers.reportToolCall(requestId, { results, isError: toolHadError, isComplete: true })\n const completedAt = nowIso()\n await ctx.storeToolCall(\n new ToolCall({\n id: requestId,\n tool: tool.name,\n args,\n checksum: computeChecksum(tool.name, args),\n isComplete: true,\n isError: toolHadError,\n results,\n fromArtifactTool: isArtifactTool,\n inline: isArtifactTool,\n createdAt: completedAt,\n updatedAt: completedAt,\n completedAt,\n })\n )\n\n let rendered: { content: OutboundContentBlock[]; isError: boolean }\n try {\n rendered = await renderOutboundResult({\n raw: results as string | Uint8Array | SpooledArtifact | Media | Media[],\n callId: requestId,\n inline: isArtifactTool,\n spoolStore,\n unsupportedResultMediaPolicy:\n merged.unsupportedResultMediaPolicy ?? merged.unsupportedMediaPolicy ?? 'throw',\n })\n } catch (err) {\n rendered = {\n content: [{ type: 'text', text: isError(err) ? err.message : String(err) }],\n isError: true,\n }\n }\n writeCommand({\n type: 'tool_call_response',\n requestId,\n results: { content: rendered.content, isError: toolHadError || rendered.isError },\n })\n }\n\n await new Promise<void>((resolve) => {\n const finish = (): void => resolve()\n resolveIteration = finish\n\n const onEvent = async (event: WrapperEvent): Promise<void> => {\n if (event.type === 'ready') {\n sawReady = true\n maybeClearStartupTimer()\n const runCommand: WrapperCommand = {\n type: 'run',\n prompt,\n appendSystemPrompt: merged.appendSystemPrompt,\n model: merged.model,\n cwd: merged.cwd,\n addDir: merged.addDir,\n allowedTools: bridgedTools.map((t) => t.name),\n maxBudgetUsd: merged.maxBudgetUsd,\n fallbackModel: merged.fallbackModel,\n auth: {\n apiKey: merged.apiKey,\n authToken: merged.authToken,\n baseUrl: merged.baseURL,\n },\n disableTelemetry: merged.disableTelemetry,\n disableErrorReporting: merged.disableErrorReporting,\n disableNonessentialTraffic: merged.disableNonessentialTraffic,\n mcpToolIdleTimeoutMs: merged.mcpToolIdleTimeoutMs,\n claudeBin,\n forwardSubagentText: merged.forwardSubagentText,\n unsupportedResultMediaPolicy: String(\n merged.unsupportedResultMediaPolicy ?? merged.unsupportedMediaPolicy ?? 'throw'\n ),\n bridgedTools,\n extraArgs: merged.extraArgs,\n }\n writeCommand(runCommand)\n armIdleTimer()\n return\n }\n if (event.type === 'init') {\n sawInit = true\n maybeClearStartupTimer()\n helpers.log.info({\n kind: 'claude-init',\n message: 'Claude Code CLI initialized.',\n payload: event as unknown as Record<string, unknown>,\n })\n if (event.mcpServerErrors && event.mcpServerErrors.length > 0) {\n settleOnce(() => {\n finish()\n void gracefulShutdown()\n ctx.nack(\n new E_CLAUDE_CODE_CLI_MCP_BRIDGE_STARTUP_FAILED([\n event.mcpServerErrors!.join(', '),\n ])\n )\n })\n }\n return\n }\n if (event.type === 'retry') {\n helpers.log.warn({\n kind: 'claude-retry',\n message: `Claude API retry, attempt ${event.attempt}`,\n payload: event as unknown as Record<string, unknown>,\n })\n return\n }\n if (event.type === 'message_delta') {\n currentMessageId = event.id\n currentMessageBuffer += event.delta\n helpers.reportMessage(event.id, event.delta, { isComplete: event.isComplete })\n if (event.isComplete) {\n await sealCurrentMessage()\n }\n return\n }\n if (event.type === 'thought_delta') {\n helpers.reportThought(event.id, event.delta, { isComplete: event.isComplete })\n return\n }\n if (event.type === 'tool_call_request') {\n await handleToolCallRequest(event.requestId, event.tool, event.args)\n return\n }\n if (event.type === 'result') {\n sawTerminalEvent = true\n await sealCurrentMessage()\n settleOnce(() => {\n if (event.isError && event.subtype !== 'error_max_turns') {\n ctx.nack(\n new E_CLAUDE_CODE_CLI_TURN_FAILED([\n event.stopReason ?? 'unknown',\n event.resultText ?? '',\n ])\n )\n return\n }\n if (event.isError && event.subtype === 'error_max_turns') {\n helpers.log.debug({\n kind: 'claude-max-turns-reached',\n message:\n 'Claude reached the fixed single-turn limit; treating it as normal completion.',\n payload: { subtype: event.subtype },\n })\n }\n helpers.reportGenerationStats({\n provider: 'claude_code_cli',\n model: merged.model,\n raw: event.raw as Record<string, unknown> | undefined,\n })\n if (merged.autoAck) ctx.ack()\n })\n // The wrapper, not the adapter, initiates its own shutdown on this path (Decision D\n // step 5) — a terminal NDJSON line proves the wrapper WROTE it, not that the OS\n // process has actually exited yet. Await the wrapper's real exit before resolving so\n // the executor doesn't return while the wrapper (and its `claude` grandchild) are\n // still tearing down.\n await Promise.resolve(child).catch(() => undefined)\n finish()\n return\n }\n if (event.type === 'error') {\n settleOnce(() => {\n finish()\n void gracefulShutdown()\n ctx.nack(new E_CLAUDE_CODE_CLI_WRAPPER_CRASHED([event.message]))\n })\n return\n }\n if (event.type === 'log') {\n helpers.log[event.level]({\n kind: event.kind,\n message: event.message,\n payload: event.payload as Record<string, unknown> | undefined,\n })\n return\n }\n // 'shutdown_complete' — nothing further to do; the wrapper is exiting on its own.\n }\n\n const eventReader = createNdjsonLineReader<WrapperEvent>((raw) => {\n let event: WrapperEvent\n try {\n event = JSON.parse(raw) as WrapperEvent\n } catch {\n helpers.log.trace({\n kind: 'malformed-wrapper-event',\n message: 'Failed to parse wrapper event line; skipping.',\n payload: { linePreview: raw.slice(0, 256) },\n })\n return undefined\n }\n void onEvent(event)\n return event\n })\n\n child.stdout?.on('data', (chunk: Uint8Array) => {\n // Parse BEFORE arming: `armIdleTimer()` is gated on `sawReady && sawInit`, and the very\n // chunk that carries the `init` event is what flips `sawInit` — parsing first lets that\n // same chunk's processing arm the timer immediately, rather than requiring a chunk AFTER\n // init to ever arrive (which, on a genuinely idle stream, never happens).\n eventReader.push(chunk)\n armIdleTimer()\n })\n child.stdout?.on('end', () => {\n // A terminal `result`/`error` event was already observed and its own handler is (or will\n // shortly be) in the middle of its own `settleOnce` — defer to it rather than racing it\n // with a wrong \"stdout ended without a terminal event\" nack for what was actually a\n // successful turn. `sawTerminalEvent` is set synchronously by that handler before any\n // `await`, so it is already true here whenever this really is that race.\n if (sawTerminalEvent) return\n settleOnce(() => {\n finish()\n ctx.nack(\n new E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO([\n 0,\n 'stdout ended without a terminal event',\n ])\n )\n })\n })\n\n void Promise.resolve(child)\n .then((result: unknown) => {\n // Same race as the `stdout.on('end')` guard above: the `result` handler may still be\n // awaiting `sealCurrentMessage()`/the child's own exit when the wrapper process itself\n // settles — defer to the terminal-event path rather than nacking a successful turn.\n if (sawTerminalEvent) return\n const exitCode =\n isObject(result) && 'exitCode' in result\n ? ((result as { exitCode: number | null }).exitCode ?? -1)\n : -1\n settleOnce(() => {\n finish()\n ctx.nack(\n new E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO([\n exitCode,\n 'wrapper process exited with no terminal event observed',\n ])\n )\n })\n })\n .catch(() => {\n if (sawTerminalEvent) return\n settleOnce(() => {\n finish()\n ctx.nack(new E_CLAUDE_CODE_CLI_WRAPPER_CRASHED(['wrapper process rejected']))\n })\n })\n })\n }\n }\n\n /**\n * Returns `true` when `value` is a {@link ClaudeCodeCliAdapter} instance.\n */\n public static isClaudeCodeCliAdapter(value: unknown): value is ClaudeCodeCliAdapter {\n return isInstanceOf(value, 'ClaudeCodeCliAdapter', ClaudeCodeCliAdapter)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+FA,IAAa,kCAA0C;CAKrD,IAAI,OAAA,cAAmB,cAAc,OAAA,UAAe,YAAY,YAC9D,OAAA,UAAe,QAAQ,sCAAsC;CAY/D,OAAO,mBACL,IAAA,IAAA,wCAAA,KAAA,OAAA,KAAA,GAAA,EAAiE,QACnE;AACF;AAIA,IAAM,eAAe,OAAO,aAA4D;CACtF,IAAI,QACF,mBAAmB,OAAO;CAC5B,IAAI,OAAO,UAAU,cAAc,EAAE,UAAW,QAC9C,IAAI;EACF,QAAQ,MAAO,MAAwB;CACzC,SAAS,KAAK;EAEZ,MAAM,IAAI,sCAAsC,CAC9C,0BAFa,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG,EAEnB,mEACnC,CAAC;CACH;CAEF,IAAI,SAAS,KAAK,KAAK,WAAW,OAChC,QAAS,MAA6B;CAExC,IAAI,OAAO,UAAU,YACnB,MAAM,IAAI,sCAAsC,CAC9C,8CACF,CAAC;CAEH,OAAO;AACT;AAIA,IAAM,eACJ,WACkB;CAClB,IAAI;CACJ,KAAK,MAAM,SAAS,QAAQ;EAC1B,IAAI,CAAC,OA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xB,QAAQ;MACN,QAAQ,IAAI,MAAM;OAChB,MAAM;OACN,SAAS;OACT,SAAS,EAAE,aAAa,IAAI,MAAM,GAAG,GAAG,EAAE;MAC5C,CAAC;MACD;KACF;KACA,QAAa,KAAK;KAClB,OAAO;IACT,CAAC;IAED,MAAM,QAAQ,GAAG,SAAS,UAAsB;KAK9C,YAAY,KAAK,KAAK;KACtB,aAAa;IACf,CAAC;IACD,MAAM,QAAQ,GAAG,aAAa;KAM5B,IAAI,kBAAkB;KACtB,iBAAiB;MACf,OAAO;MACP,IAAI,KACF,IAAI,yCAAyC,CAC3C,GACA,uCACF,CAAC,CACH;KACF,CAAC;IACH,CAAC;IAED,QAAa,QAAQ,KAAK,EACvB,MAAM,WAAoB;KAIzB,IAAI,kBAAkB;KACtB,MAAM,WACJ,SAAS,MAAM,KAAK,cAAc,SAC5B,OAAuC,YAAY,KACrD;KACN,iBAAiB;MACf,OAAO;MACP,IAAI,KACF,IAAI,yCAAyC,CAC3C,UACA,wDACF,CAAC,CACH;KACF,CAAC;IACH,CAAC,EACA,YAAY;KACX,IAAI,kBAAkB;KACtB,iBAAiB;MACf,OAAO;MACP,IAAI,KAAK,IAAI,kCAAkC,CAAC,0BAA0B,CAAC,CAAC;KAC9E,CAAC;IACH,CAAC;GACL,CAAC;EACH;CACF;;;;CAKA,OAAc,uBAAuB,OAA+C;EAClF,OAAO,aAAa,OAAO,wBAAwB,oBAAoB;CACzE;AACF"}
1
+ {"version":3,"file":"adapter.mjs","names":["#baseline"],"sources":["../../../../src/batteries/llm/claude_code_cli/adapter.ts"],"sourcesContent":["/**\n * Cross-environment executor adapter that wraps the Claude Code CLI as a `DispatchExecutorFn`\n * destination.\n *\n * @module @nhtio/adk/batteries/llm/claude_code_cli/adapter\n *\n * @remarks\n * The first battery in the \"CLI harness\" family: rather than a direct wire-format provider, this\n * adapter drives an external coding-agent CLI binary that is itself a complete agent loop. Since a\n * subprocess must be spawned anyway, ALL Claude-Code-specific complexity — spawning the real\n * `claude` binary, hosting an MCP bridge server, translating its stream-json — lives in a\n * dedicated wrapper process (`wrapper.ts`, shipped as a sibling dist asset); this adapter only\n * ever spawns and drives that wrapper over the small, harness-agnostic protocol in `./wire`.\n *\n * Every dispatch iteration is stateless and self-contained: the full accumulated history renders\n * into one `-p` prompt string (`buildClaudeCodeCliPrompt`), a fresh wrapper is spawned, and real\n * ADK tools are bridged into the CLI's own tool loop via MCP — but actual execution always happens\n * on the ADK side, through `tool.executor(ctx)(args)`, exactly like every other LLM battery.\n */\n\nimport { sha256 } from 'js-sha256'\nimport { validateOptions } from './validation'\nimport { isError, isObject, isInstanceOf } from '@nhtio/adk/guards'\nimport { createNdjsonLineReader, encodeWrapperCommand } from './wire'\nimport { canonicalStringify } from '../../../lib/utils/canonical_json'\nimport { InMemorySpoolStore } from '@nhtio/adk/batteries/storage/in_memory'\nimport {\n Tokenizable,\n ToolCall,\n Memory,\n Message,\n Media,\n ArtifactTool,\n SpooledArtifact,\n} from '@nhtio/adk/common'\nimport {\n E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR,\n E_CLAUDE_CODE_CLI_WRAPPER_CRASHED,\n E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO,\n E_CLAUDE_CODE_CLI_STREAM_STALLED,\n E_CLAUDE_CODE_CLI_STARTUP_TIMEOUT,\n E_CLAUDE_CODE_CLI_MCP_BRIDGE_STARTUP_FAILED,\n E_CLAUDE_CODE_CLI_TURN_FAILED,\n E_INVALID_CLAUDE_CODE_CLI_OPTIONS,\n E_CLAUDE_CODE_CLI_CONTEXT_OVERFLOW,\n} from './exceptions'\nimport {\n defaultDescriptionToChatCompletionsJsonSchema,\n defaultRenderUntrustedContent,\n defaultRenderTrustedContent,\n defaultRenderStandingInstructions,\n defaultRenderMemories,\n defaultRenderRetrievables,\n defaultRenderRetrievableHandleBody,\n defaultRenderRetrievableSafetyDirective,\n defaultRenderFirstPartyRetrievables,\n defaultRenderThirdPartyPublicRetrievables,\n defaultRenderThirdPartyPrivateRetrievables,\n defaultRenderThought,\n defaultFilterThoughts,\n defaultToolsToChatCompletionsTools,\n defaultRenderChatCompletionsSystemPrompt,\n defaultRenderClaudeCodeCliTimelineMessage,\n defaultRenderClaudeCodeCliToolCallResult,\n defaultBuildClaudeCodeCliPrompt,\n renderArtifactHandleBody,\n looksLikeSpooledArtifact,\n} from './helpers'\nimport type { Tool } from '@nhtio/adk/common'\nimport type { SpoolStore } from '@nhtio/adk/common'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type { TokenEncoding, TokenEncodingId } from '@nhtio/adk/types'\nimport type { WrapperEvent, WrapperCommand, WrapperBridgedTool } from './wire'\nimport type { DispatchExecutorFn, DispatchExecutorHelpers } from '@nhtio/adk/dispatch_runner'\nimport type {\n ClaudeCodeCliAdapterOptions,\n ClaudeCodeCliHelpers,\n ExecaLike,\n ExecaResolver,\n UnsupportedMediaPolicy,\n} from './types'\n\ntype OutboundContentBlock =\n | { type: 'text'; text: string }\n | { type: 'image'; data: string; mimeType: string }\n\n// ─── wrapper path resolution (Decision C) ──────────────────────────────────────\n\n/**\n * Resolve the built wrapper asset's on-disk path relative to this module's own compiled location.\n * `adapter.ts` carries its own `@module` tag (per the per-file tagging convention every other\n * multi-file battery uses), so it compiles to `dist/batteries/llm/claude_code_cli/adapter.mjs` —\n * three directories below the package root, where the wrapper (an explicit, un-tagged\n * `vite.config.mts` entry key) compiles to `dist/claude-code-cli-wrapper.mjs`.\n */\nexport const resolveDefaultWrapperPath = (): string => {\n // `typeof require === 'function'` alone is not a safe CJS-vs-ESM discriminator: rolldown's ESM\n // output wraps `require` in a shim/Proxy (falling back to itself when the real `require` is\n // absent) that still reports `typeof === 'function'`, but whose `.resolve` is not itself a\n // function — calling it throws instead of falling through to the URL-based ESM branch below.\n if (typeof require === 'function' && typeof require.resolve === 'function') {\n return require.resolve('../../../claude-code-cli-wrapper.cjs')\n }\n // `URL.pathname` is percent-encoded — a real install path containing a space, unicode, or any\n // other URL-reserved character would produce a non-existent argv path (e.g. `%20` instead of a\n // literal space) once handed to `execaFn`/`spawn` below. `decodeURIComponent` undoes that percent\n // encoding to recover the native filesystem path — equivalent to `node:url`'s `fileURLToPath` for\n // a POSIX path (verified directly), which this module avoids importing at module scope: this\n // file is transitively pulled into the browser test project via `src/batteries`'s barrel (e.g.\n // `tests/unit/batteries/index.cross.spec.ts`), and Vite externalizes `node:url` there, throwing\n // on any access to `fileURLToPath` at import time. This battery is POSIX-only in v1 anyway\n // (validated at options-construction time), so a POSIX-only decode is exactly the right amount\n // of `node:url` behavior to reimplement without importing it.\n return decodeURIComponent(\n new URL('../../../claude-code-cli-wrapper.mjs', import.meta.url).pathname\n )\n}\n\n// ─── execa resolution (mirrors execa_executor.ts's lazy-resolver pattern) ──────\n\nconst resolveExeca = async (supplied: ExecaResolver | undefined): Promise<ExecaLike> => {\n let value: unknown =\n supplied ?? (() => import('execa') as unknown as Promise<{ execa: ExecaLike }>)\n if (typeof value === 'function' && !('exec' in (value as object))) {\n try {\n value = await (value as () => unknown)()\n } catch (err) {\n const detail = isError(err) ? err.message : String(err)\n throw new E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR([\n `execa resolver failed: ${detail} — install the optional peer dependency \"execa\" or supply your own`,\n ])\n }\n }\n if (isObject(value) && 'execa' in value) {\n value = (value as { execa: unknown }).execa\n }\n if (typeof value !== 'function') {\n throw new E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR([\n 'execa resolver did not resolve to a function',\n ])\n }\n return value as ExecaLike\n}\n\n// ─── option merging ─────────────────────────────────────────────────────────\n\nconst mergeRecord = <T extends Record<string, unknown>>(\n layers: ReadonlyArray<T | undefined>\n): T | undefined => {\n let merged: T | undefined\n for (const layer of layers) {\n if (!layer) continue\n merged = { ...(merged ?? ({} as T)), ...layer }\n }\n return merged\n}\n\nconst mergeOptions = (\n baseline: ClaudeCodeCliAdapterOptions,\n exec: Partial<ClaudeCodeCliAdapterOptions> | undefined,\n stash: Partial<ClaudeCodeCliAdapterOptions> | undefined\n): Partial<ClaudeCodeCliAdapterOptions> => {\n const layers = [baseline as Partial<ClaudeCodeCliAdapterOptions>, exec ?? {}, stash ?? {}]\n const out: Record<string, unknown> = {}\n for (const layer of layers) {\n for (const [k, v] of Object.entries(layer)) {\n if (v === undefined) continue\n if (k === 'helpers') continue\n out[k] = v\n }\n }\n const helpers = mergeRecord(layers.map((l) => l.helpers as Record<string, unknown> | undefined))\n if (helpers !== undefined) out.helpers = helpers\n return out as Partial<ClaudeCodeCliAdapterOptions>\n}\n\nconst resolveHelpers = (\n overrides: Partial<ClaudeCodeCliHelpers> | undefined\n): ClaudeCodeCliHelpers => {\n const src = overrides ?? {}\n return {\n descriptionToChatCompletionsJsonSchema:\n src.descriptionToChatCompletionsJsonSchema ?? defaultDescriptionToChatCompletionsJsonSchema,\n renderUntrustedContent: src.renderUntrustedContent ?? defaultRenderUntrustedContent,\n renderTrustedContent: src.renderTrustedContent ?? defaultRenderTrustedContent,\n renderStandingInstructions: src.renderStandingInstructions ?? defaultRenderStandingInstructions,\n renderMemories: src.renderMemories ?? defaultRenderMemories,\n renderRetrievables: src.renderRetrievables ?? defaultRenderRetrievables,\n renderRetrievableHandleBody:\n src.renderRetrievableHandleBody ?? defaultRenderRetrievableHandleBody,\n renderRetrievableSafetyDirective:\n src.renderRetrievableSafetyDirective ?? defaultRenderRetrievableSafetyDirective,\n renderFirstPartyRetrievables:\n src.renderFirstPartyRetrievables ?? defaultRenderFirstPartyRetrievables,\n renderThirdPartyPublicRetrievables:\n src.renderThirdPartyPublicRetrievables ?? defaultRenderThirdPartyPublicRetrievables,\n renderThirdPartyPrivateRetrievables:\n src.renderThirdPartyPrivateRetrievables ?? defaultRenderThirdPartyPrivateRetrievables,\n renderThought: src.renderThought ?? defaultRenderThought,\n filterThoughts: src.filterThoughts ?? defaultFilterThoughts,\n toolsToChatCompletionsTools:\n src.toolsToChatCompletionsTools ?? defaultToolsToChatCompletionsTools,\n renderChatCompletionsSystemPrompt:\n src.renderChatCompletionsSystemPrompt ?? defaultRenderChatCompletionsSystemPrompt,\n renderClaudeCodeCliTimelineMessage:\n src.renderClaudeCodeCliTimelineMessage ?? defaultRenderClaudeCodeCliTimelineMessage,\n renderClaudeCodeCliToolCallResult:\n src.renderClaudeCodeCliToolCallResult ?? defaultRenderClaudeCodeCliToolCallResult,\n buildClaudeCodeCliPrompt: src.buildClaudeCodeCliPrompt ?? defaultBuildClaudeCodeCliPrompt,\n }\n}\n\nconst estimateTokensOf = async (\n value: { estimateTokens: (encoding: TokenEncoding) => number | Promise<number> },\n encoding: TokenEncodingId\n): Promise<number> => Promise.resolve(value.estimateTokens(encoding as TokenEncoding))\n\n// ─── time / checksum helpers ────────────────────────────────────────────────\n\nconst nowIso = (): string => new Date().toISOString()\n\n/**\n * Integrity checksum over `tool`/`args` — matches every other LLM battery's convention\n * (`sha256(canonicalStringify({tool, args}))`, see `ollama/adapter.ts`'s `computeChecksum`), NOT\n * the per-call `requestId`. Identical repeat calls must share this checksum: it feeds\n * `DispatchContext`'s own `#toolCallChecksums` loop-detection counter and cross-bus correlation,\n * neither of which can see a repeat if every call gets a unique value.\n */\nconst computeChecksum = (tool: string, args: unknown): string =>\n sha256(canonicalStringify({ tool, args }))\n\n// ─── outbound tool-result rendering (decision 8) ───────────────────────────────\n\nconst renderMediaListAsOutbound = async (\n mediaList: Media[],\n unsupportedResultMediaPolicy: UnsupportedMediaPolicy\n): Promise<{ content: OutboundContentBlock[]; isError: boolean }> => {\n const content: OutboundContentBlock[] = []\n let anyUnsupported = false\n for (const media of mediaList) {\n if (media.kind === 'image') {\n content.push({ type: 'image', data: await media.asBase64(), mimeType: media.mimeType })\n continue\n }\n // Every non-image modality is unsupported on the outbound MCP wire (only text/image content\n // blocks exist there) — routed through the SAME policy family the inbound direction uses\n // (decision 8), rather than an unconditional hardcoded error.\n if (unsupportedResultMediaPolicy === 'throw') {\n anyUnsupported = true\n content.push({\n type: 'text',\n text: `Unsupported result media modality: ${media.kind} (${media.mimeType})`,\n })\n continue\n }\n const byteLen = await media.byteLength().catch(() => undefined)\n content.push({\n type: 'text',\n text: `[media: ${media.filename}, ${media.mimeType}, ${byteLen ?? 'unknown'} bytes]`,\n })\n }\n return { content, isError: anyUnsupported }\n}\n\nconst renderOutboundResult = async (input: {\n raw: string | Uint8Array | SpooledArtifact | Media | Media[]\n callId: string\n inline: boolean\n spoolStore: SpoolStore\n unsupportedResultMediaPolicy: UnsupportedMediaPolicy\n}): Promise<{ content: OutboundContentBlock[]; isError: boolean }> => {\n const { raw, callId, inline } = input\n\n if (Media.isMedia(raw)) {\n return renderMediaListAsOutbound([raw], input.unsupportedResultMediaPolicy)\n }\n if (Array.isArray(raw) && raw.length > 0 && raw.every((m) => Media.isMedia(m))) {\n return renderMediaListAsOutbound(raw, input.unsupportedResultMediaPolicy)\n }\n if (looksLikeSpooledArtifact(raw)) {\n const artifact = raw as SpooledArtifact\n if (inline === false) {\n let byteLength = 0\n let lineCount = 0\n try {\n byteLength = await artifact.byteLength()\n } catch {\n byteLength = 0\n }\n try {\n lineCount = await artifact.lineCount()\n } catch {\n lineCount = 0\n }\n const body = renderArtifactHandleBody({ callId, artifact, byteLength, lineCount })\n return { content: [{ type: 'text', text: body }], isError: false }\n }\n const text = await artifact.asString()\n return { content: [{ type: 'text', text }], isError: false }\n }\n if (typeof raw === 'string') {\n return { content: [{ type: 'text', text: raw }], isError: false }\n }\n if (isInstanceOf(raw, 'Uint8Array', Uint8Array)) {\n await input.spoolStore.write(callId, raw)\n return {\n content: [{ type: 'text', text: '[binary tool result — see history for details]' }],\n isError: false,\n }\n }\n return { content: [{ type: 'text', text: String(raw) }], isError: false }\n}\n\n// ─── the adapter ────────────────────────────────────────────────────────────\n\n/**\n * Opinionated CLI-harness LLM adapter that drives the Claude Code CLI as a `DispatchExecutorFn`\n * destination.\n *\n * @remarks\n * Construction validates options eagerly via {@link validateOptions} and throws\n * {@link @nhtio/adk/batteries/llm/claude_code_cli!E_INVALID_CLAUDE_CODE_CLI_OPTIONS} on failure\n * (including the POSIX-only platform guard and the `apiKey`/`authToken` XOR check). The returned\n * instance is reusable: call {@link ClaudeCodeCliAdapter.executor} once per `DispatchRunner`\n * configuration.\n */\nexport class ClaudeCodeCliAdapter {\n /** Customary key for per-iteration overrides on `ctx.stash`. */\n public static readonly STASH_KEY = 'claudeCodeCli' as const\n\n readonly #baseline: ClaudeCodeCliAdapterOptions\n\n /**\n * @param options - Constructor-baseline options. Re-validated on every iteration after\n * per-dispatch and per-iteration overrides are layered in.\n * @throws {@link @nhtio/adk/batteries/llm/claude_code_cli!E_INVALID_CLAUDE_CODE_CLI_OPTIONS} when\n * `options` does not satisfy `claudeCodeCliOptionsSchema`.\n */\n constructor(options: unknown) {\n this.#baseline = validateOptions(options)\n }\n\n /**\n * Returns a {@link @nhtio/adk!DispatchExecutorFn} bound to this adapter's baseline plus optional\n * executor-scope overrides.\n */\n executor(overrides?: Partial<ClaudeCodeCliAdapterOptions>): DispatchExecutorFn {\n const baseline = this.#baseline\n const adapterClass = ClaudeCodeCliAdapter\n\n return async (ctx: DispatchContext, helpers: DispatchExecutorHelpers): Promise<void> => {\n const localWarn = (msg: string): void => {\n helpers.log.warn({ kind: 'helper-warning', message: msg })\n }\n\n // ── Step 1: merge & validate ──────────────────────────────────────────\n const stashRaw = ctx.stash.get(adapterClass.STASH_KEY, {}) as unknown\n const stashOverrides =\n stashRaw && typeof stashRaw === 'object'\n ? (stashRaw as Partial<ClaudeCodeCliAdapterOptions>)\n : {}\n const merged = validateOptions(mergeOptions(baseline, overrides, stashOverrides))\n\n if (merged.tokenEncoding !== null && merged.contextWindow === undefined) {\n throw new E_INVALID_CLAUDE_CODE_CLI_OPTIONS([\n 'tokenEncoding is non-null but contextWindow is undefined',\n ])\n }\n\n // ── Step 2: resolve helpers ───────────────────────────────────────────\n const resolvedHelpers = resolveHelpers(merged.helpers)\n\n // ── Step 3: resolve execa + wrapper path ──────────────────────────────\n let execaFn: ExecaLike\n try {\n execaFn = await resolveExeca(merged.execa)\n } catch (err) {\n ctx.nack(isError(err) ? err : new Error(String(err)))\n return\n }\n const wrapperPath = merged.wrapperPath ?? resolveDefaultWrapperPath()\n const claudeBin = merged.claudeBin ?? 'claude'\n\n // ── Step 5: pre-render inbound tool-call results (for history) ────────\n // Key by primitive identity, not id: repeated vendor/request ids must not cross-wire results.\n const renderedToolCallResults = new Map<ToolCall, string>()\n for (const tc of ctx.turnToolCalls) {\n const rendered = await resolvedHelpers.renderClaudeCodeCliToolCallResult({\n toolCall: tc,\n results: tc.results as\n | Tokenizable\n | SpooledArtifact\n | SpooledArtifact[]\n | Media\n | Media[],\n tool: ctx.tools.get(tc.tool) as Tool | undefined,\n renderUntrustedContent: resolvedHelpers.renderUntrustedContent,\n renderTrustedContent: resolvedHelpers.renderTrustedContent,\n unsupportedMediaPolicy: merged.unsupportedMediaPolicy ?? 'throw',\n warn: localWarn,\n })\n renderedToolCallResults.set(tc, rendered)\n }\n\n // ── Step 6: build the -p prompt ────────────────────────────────────────\n const { prompt, reasoningPayloads } = await resolvedHelpers.buildClaudeCodeCliPrompt({\n systemPrompt: ctx.systemPrompt,\n renderCtx: ctx,\n standingInstructions: ctx.standingInstructions,\n memories: ctx.turnMemories,\n retrievables: ctx.turnRetrievables,\n messages: ctx.turnMessages,\n thoughts: ctx.turnThoughts,\n toolCalls: ctx.turnToolCalls,\n tools: ctx.tools,\n renderedToolCallResults,\n bucketOrder: merged.bucketOrder ?? [\n 'standingInstructions',\n 'memories',\n 'retrievables',\n 'timeline',\n ],\n selfIdentity: merged.selfIdentity ?? 'assistant',\n thoughtSurfacing: merged.thoughtSurfacing ?? 'all-self',\n replayCompatibility: merged.replayCompatibility ?? [],\n unsupportedMediaPolicy: merged.unsupportedMediaPolicy ?? 'throw',\n renderChatCompletionsSystemPrompt: resolvedHelpers.renderChatCompletionsSystemPrompt,\n renderStandingInstructions: resolvedHelpers.renderStandingInstructions,\n renderMemories: resolvedHelpers.renderMemories,\n renderRetrievables: resolvedHelpers.renderRetrievables,\n renderRetrievableSafetyDirective: resolvedHelpers.renderRetrievableSafetyDirective,\n renderFirstPartyRetrievables: resolvedHelpers.renderFirstPartyRetrievables,\n renderThirdPartyPublicRetrievables: resolvedHelpers.renderThirdPartyPublicRetrievables,\n renderThirdPartyPrivateRetrievables: resolvedHelpers.renderThirdPartyPrivateRetrievables,\n renderRetrievableHandleBody: resolvedHelpers.renderRetrievableHandleBody,\n renderClaudeCodeCliTimelineMessage: resolvedHelpers.renderClaudeCodeCliTimelineMessage,\n renderClaudeCodeCliToolCallResult: resolvedHelpers.renderClaudeCodeCliToolCallResult,\n renderThought: resolvedHelpers.renderThought,\n filterThoughts: resolvedHelpers.filterThoughts,\n renderUntrustedContent: resolvedHelpers.renderUntrustedContent,\n renderTrustedContent: resolvedHelpers.renderTrustedContent,\n warn: localWarn,\n })\n\n // A `-p` prompt string has no side channel for an opaque, vendor-specific reasoning payload\n // the way Ollama/OpenAI's JSON request bodies do (`_adk_reasoning_payloads`) — there is\n // nowhere in this wire to forward one. Surface that loss as a diagnostic rather than\n // silently dropping it, matching the honesty standard applied to every other documented v1\n // limitation of this battery (text-only media, subagent text).\n if (reasoningPayloads.length > 0) {\n helpers.log.debug({\n kind: 'reasoning-payload-dropped',\n message: `${reasoningPayloads.length} opaque reasoning payload(s) matched replayCompatibility but have no destination on the Claude Code CLI wire (no side channel exists for a '-p' prompt) and were dropped.`,\n })\n }\n\n // ── Step 7: build the bridged-tools set (excluding disallowedTools) ───\n const disallowed = new Set(merged.disallowedTools ?? [])\n const visibleTools = ctx.tools.visible().filter((t) => !disallowed.has(t.name))\n const bridgedTools: WrapperBridgedTool[] = visibleTools.map((t) => {\n const described = t.describe()\n const inputSchema = resolvedHelpers.descriptionToChatCompletionsJsonSchema(\n described.inputSchema as never\n )\n return {\n name: described.name,\n description: described.description,\n inputSchema:\n inputSchema && Object.keys(inputSchema).length > 0\n ? (inputSchema as Record<string, unknown>)\n : { type: 'object', properties: {} },\n }\n })\n\n // ── Step 8: context window enforcement ────────────────────────────────\n if (merged.tokenEncoding !== null && merged.contextWindow !== undefined) {\n const encoding = merged.tokenEncoding as TokenEncodingId\n // The rendered prompt is the actual `-p` wire value. Measure it directly rather than\n // re-summing its source buckets: renderers add envelopes, provenance, and ordering.\n const promptTokens = await estimateTokensOf(new Tokenizable(prompt), encoding)\n const appendSystemPromptTokens = merged.appendSystemPrompt\n ? await estimateTokensOf(new Tokenizable(merged.appendSystemPrompt), encoding)\n : 0\n\n // Keep source-bucket diagnostics for middleware deciding what to shed. They are not part\n // of the authoritative total above, since their content is already represented by prompt.\n const rawSystemPrompt = await estimateTokensOf(ctx.systemPrompt, encoding)\n let rawStandingInstructions = 0\n for (const value of ctx.standingInstructions)\n rawStandingInstructions += await estimateTokensOf(value, encoding)\n let rawMemories = 0\n for (const value of ctx.turnMemories as Set<Memory>)\n rawMemories += await estimateTokensOf(value.content, encoding)\n let rawRetrievables = 0\n for (const r of ctx.turnRetrievables) {\n rawRetrievables +=\n !r.inline && SpooledArtifact.isSpooledArtifact(r.content) && r.content.hasSizeHints()\n ? r.content.estimateHandleTokens(\n r.id,\n encoding as TokenEncoding,\n resolvedHelpers.renderRetrievableHandleBody\n )\n : await estimateTokensOf(r.content, encoding)\n }\n let rawTimeline = 0\n for (const msg of ctx.turnMessages)\n if (msg.content !== undefined)\n rawTimeline += await estimateTokensOf(msg.content, encoding)\n for (const thought of ctx.turnThoughts)\n rawTimeline += await estimateTokensOf(thought.content, encoding)\n for (const rendered of renderedToolCallResults.values())\n rawTimeline += await estimateTokensOf(new Tokenizable(rendered), encoding)\n // Claude Code receives declarations through MCP, not a wire `tools` array. This stable\n // serialization is an honest floor: JSON declarations plus the CLI-visible names.\n const toolSerialization = `${JSON.stringify(bridgedTools)}|${bridgedTools\n .map((t) => `mcp__adk_bridge__${t.name}`)\n .join(',')}`\n const tools = await estimateTokensOf(new Tokenizable(toolSerialization), encoding)\n const perBucket = {\n prompt: promptTokens,\n appendSystemPrompt: appendSystemPromptTokens,\n tools,\n raw: {\n systemPrompt: rawSystemPrompt,\n standingInstructions: rawStandingInstructions,\n memories: rawMemories,\n retrievables: rawRetrievables,\n timeline: rawTimeline,\n },\n }\n const total = promptTokens + appendSystemPromptTokens + tools\n helpers.log.debug({\n kind: 'context-window-usage',\n message: `Context window usage: ${total}/${merged.contextWindow} tokens`,\n payload: { total, limit: merged.contextWindow, encoding, perBucket },\n })\n if (total > merged.contextWindow)\n throw new E_CLAUDE_CODE_CLI_CONTEXT_OVERFLOW([\n total,\n merged.contextWindow,\n encoding,\n JSON.stringify(perBucket),\n ])\n }\n\n // ── Step 9: spawn the wrapper ──────────────────────────────────────────\n const spoolStore = merged.spoolStore ?? new InMemorySpoolStore()\n let child: ReturnType<ExecaLike>\n try {\n child = execaFn(process.execPath, [wrapperPath], { cleanup: true })\n } catch (err) {\n ctx.nack(\n new E_CLAUDE_CODE_CLI_WRAPPER_SPAWN_ERROR([isError(err) ? err.message : String(err)])\n )\n return\n }\n\n const startupTimeoutMs = merged.startupTimeoutMs ?? 45_000\n const streamIdleTimeoutMs = merged.streamIdleTimeoutMs ?? 60_000\n const disposeGraceMs = merged.disposeGraceMs ?? 2_000\n\n let sawReady = false\n let sawInit = false\n // Set SYNCHRONOUSLY the instant a terminal `result`/`error` event is observed — before any\n // `await` (e.g. `sealCurrentMessage()`) runs. The wrapper closing stdout immediately after\n // writing its terminal line is a real, observed race: without this flag, `stdout`'s `'end'`\n // handler can fire and call `settleOnce` (nacking the turn as an unexpected exit) while the\n // `result` handler is still awaiting `sealCurrentMessage()`, even though `settleOnce` itself\n // is idempotent-guarded — the guard only helps once one of the two paths has actually run.\n let sawTerminalEvent = false\n let startupTimer: ReturnType<typeof setTimeout> | undefined\n let idleTimer: ReturnType<typeof setTimeout> | undefined\n let settled = false\n // Set once the outer `await new Promise<void>(...)` below is constructed. The startup/idle\n // timers are armed BEFORE that promise exists, so their settleOnce() callbacks must resolve\n // it through this indirection rather than a `finish` closure defined only inside it — without\n // this, a startup or stream-idle timeout would settle ctx (nack) but never resolve the outer\n // promise, hanging the executor forever.\n let resolveIteration: (() => void) | undefined\n let currentMessageId: string | undefined\n let currentMessageBuffer = ''\n let sealedMessage = false\n\n const clearStartupTimer = (): void => {\n if (startupTimer) clearTimeout(startupTimer)\n startupTimer = undefined\n }\n const clearIdleTimer = (): void => {\n if (idleTimer) clearTimeout(idleTimer)\n idleTimer = undefined\n }\n const maybeClearStartupTimer = (): void => {\n if (sawReady && sawInit) clearStartupTimer()\n }\n\n const writeCommand = (command: WrapperCommand): void => {\n try {\n child.stdin?.write(encodeWrapperCommand(command))\n } catch {\n /* the wrapper's stdin may already be gone */\n }\n }\n\n const gracefulShutdown = async (): Promise<void> => {\n writeCommand({ type: 'shutdown' })\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, disposeGraceMs)\n void Promise.resolve(child).finally(() => {\n clearTimeout(timer)\n resolve()\n })\n })\n try {\n child.kill('SIGTERM')\n } catch {\n /* already exited */\n }\n }\n\n const abortListener = (): void => {\n void gracefulShutdown()\n }\n ctx.abortSignal.addEventListener('abort', abortListener, { once: true })\n const detachAbortListener = (): void =>\n ctx.abortSignal.removeEventListener('abort', abortListener)\n\n const settleOnce = (fn: () => void): void => {\n if (settled) return\n settled = true\n clearStartupTimer()\n clearIdleTimer()\n detachAbortListener()\n fn()\n }\n\n startupTimer = setTimeout(() => {\n settleOnce(() => {\n resolveIteration?.()\n void gracefulShutdown()\n ctx.nack(new E_CLAUDE_CODE_CLI_STARTUP_TIMEOUT([startupTimeoutMs]))\n })\n }, startupTimeoutMs)\n\n const armIdleTimer = (): void => {\n if (!sawReady || !sawInit) return\n clearIdleTimer()\n idleTimer = setTimeout(() => {\n settleOnce(() => {\n resolveIteration?.()\n void gracefulShutdown()\n ctx.nack(new E_CLAUDE_CODE_CLI_STREAM_STALLED([streamIdleTimeoutMs]))\n })\n }, streamIdleTimeoutMs)\n }\n\n const sealCurrentMessage = async (): Promise<void> => {\n if (sealedMessage || currentMessageId === undefined) return\n sealedMessage = true\n await ctx.storeMessage(\n new Message({\n id: currentMessageId,\n role: 'assistant',\n content: currentMessageBuffer,\n identity: merged.selfIdentity ?? 'assistant',\n createdAt: nowIso(),\n updatedAt: nowIso(),\n })\n )\n }\n\n const handleToolCallRequest = async (\n requestId: string,\n toolName: string,\n rawArgs: unknown\n ): Promise<void> => {\n const tool = ctx.tools.get(toolName)\n if (!tool) {\n writeCommand({\n type: 'tool_call_response',\n requestId,\n results: {\n content: [{ type: 'text', text: `Tool not found: ${toolName}` }],\n isError: true,\n },\n })\n return\n }\n // MCP's own JSON-RPC CallTool wire always sends `arguments` as an object; a non-object\n // here would indicate a malformed request from the bridge, not a legitimate call — defend\n // the same way the Ollama battery does for its own non-object case.\n const args: string | Record<string, unknown> = isObject(rawArgs) ? rawArgs : {}\n helpers.reportToolCall(requestId, { tool: tool.name, args })\n const isArtifactTool = ArtifactTool.isArtifactTool(tool)\n let results: Tokenizable | SpooledArtifact | SpooledArtifact[] | Media | Media[] =\n new Tokenizable('')\n let toolHadError = false\n try {\n const raw = await tool.executor(ctx)(args)\n if (isArtifactTool) {\n if (Tokenizable.isTokenizable(raw)) {\n results = raw\n } else if (typeof raw === 'string') {\n results = new Tokenizable(raw)\n } else {\n throw new Error(\n `ArtifactTool \"${tool.name}\" returned a non-string/non-Tokenizable value`\n )\n }\n } else if (Media.isMedia(raw)) {\n results = raw\n } else if (Array.isArray(raw) && raw.length > 0 && raw.every((m) => Media.isMedia(m))) {\n results = raw as Media[]\n } else if (looksLikeSpooledArtifact(raw)) {\n results = raw as SpooledArtifact\n } else if (typeof raw === 'string' || isInstanceOf(raw, 'Uint8Array', Uint8Array)) {\n const reader = await spoolStore.write(requestId, raw)\n const ArtifactCtor = (tool as Tool).artifactConstructor?.() ?? SpooledArtifact\n results = new ArtifactCtor(reader)\n } else {\n const reader = await spoolStore.write(requestId, String(raw))\n const ArtifactCtor = (tool as Tool).artifactConstructor?.() ?? SpooledArtifact\n results = new ArtifactCtor(reader)\n }\n } catch (err) {\n toolHadError = true\n results = new Tokenizable(isError(err) ? err.message : String(err))\n }\n helpers.reportToolCall(requestId, { results, isError: toolHadError, isComplete: true })\n const completedAt = nowIso()\n await ctx.storeToolCall(\n new ToolCall({\n id: requestId,\n tool: tool.name,\n args,\n checksum: computeChecksum(tool.name, args),\n isComplete: true,\n isError: toolHadError,\n results,\n fromArtifactTool: isArtifactTool,\n inline: isArtifactTool,\n createdAt: completedAt,\n updatedAt: completedAt,\n completedAt,\n })\n )\n\n let rendered: { content: OutboundContentBlock[]; isError: boolean }\n try {\n rendered = await renderOutboundResult({\n raw: results as string | Uint8Array | SpooledArtifact | Media | Media[],\n callId: requestId,\n inline: isArtifactTool,\n spoolStore,\n unsupportedResultMediaPolicy:\n merged.unsupportedResultMediaPolicy ?? merged.unsupportedMediaPolicy ?? 'throw',\n })\n } catch (err) {\n rendered = {\n content: [{ type: 'text', text: isError(err) ? err.message : String(err) }],\n isError: true,\n }\n }\n writeCommand({\n type: 'tool_call_response',\n requestId,\n results: { content: rendered.content, isError: toolHadError || rendered.isError },\n })\n }\n\n await new Promise<void>((resolve) => {\n const finish = (): void => resolve()\n resolveIteration = finish\n\n const onEvent = async (event: WrapperEvent): Promise<void> => {\n if (event.type === 'ready') {\n sawReady = true\n maybeClearStartupTimer()\n const runCommand: WrapperCommand = {\n type: 'run',\n prompt,\n appendSystemPrompt: merged.appendSystemPrompt,\n model: merged.model,\n cwd: merged.cwd,\n addDir: merged.addDir,\n allowedTools: bridgedTools.map((t) => t.name),\n maxBudgetUsd: merged.maxBudgetUsd,\n fallbackModel: merged.fallbackModel,\n auth: {\n apiKey: merged.apiKey,\n authToken: merged.authToken,\n baseUrl: merged.baseURL,\n },\n disableTelemetry: merged.disableTelemetry,\n disableErrorReporting: merged.disableErrorReporting,\n disableNonessentialTraffic: merged.disableNonessentialTraffic,\n mcpToolIdleTimeoutMs: merged.mcpToolIdleTimeoutMs,\n claudeBin,\n forwardSubagentText: merged.forwardSubagentText,\n unsupportedResultMediaPolicy: String(\n merged.unsupportedResultMediaPolicy ?? merged.unsupportedMediaPolicy ?? 'throw'\n ),\n bridgedTools,\n extraArgs: merged.extraArgs,\n }\n writeCommand(runCommand)\n armIdleTimer()\n return\n }\n if (event.type === 'init') {\n sawInit = true\n maybeClearStartupTimer()\n helpers.log.info({\n kind: 'claude-init',\n message: 'Claude Code CLI initialized.',\n payload: event as unknown as Record<string, unknown>,\n })\n if (event.mcpServerErrors && event.mcpServerErrors.length > 0) {\n settleOnce(() => {\n finish()\n void gracefulShutdown()\n ctx.nack(\n new E_CLAUDE_CODE_CLI_MCP_BRIDGE_STARTUP_FAILED([\n event.mcpServerErrors!.join(', '),\n ])\n )\n })\n }\n return\n }\n if (event.type === 'retry') {\n helpers.log.warn({\n kind: 'claude-retry',\n message: `Claude API retry, attempt ${event.attempt}`,\n payload: event as unknown as Record<string, unknown>,\n })\n return\n }\n if (event.type === 'message_delta') {\n currentMessageId = event.id\n currentMessageBuffer += event.delta\n helpers.reportMessage(event.id, event.delta, { isComplete: event.isComplete })\n if (event.isComplete) {\n await sealCurrentMessage()\n }\n return\n }\n if (event.type === 'thought_delta') {\n helpers.reportThought(event.id, event.delta, { isComplete: event.isComplete })\n return\n }\n if (event.type === 'tool_call_request') {\n await handleToolCallRequest(event.requestId, event.tool, event.args)\n return\n }\n if (event.type === 'result') {\n sawTerminalEvent = true\n await sealCurrentMessage()\n settleOnce(() => {\n if (event.isError && event.subtype !== 'error_max_turns') {\n ctx.nack(\n new E_CLAUDE_CODE_CLI_TURN_FAILED([\n event.stopReason ?? 'unknown',\n event.resultText ?? '',\n ])\n )\n return\n }\n if (event.isError && event.subtype === 'error_max_turns') {\n helpers.log.debug({\n kind: 'claude-max-turns-reached',\n message:\n 'Claude reached the fixed single-turn limit; treating it as normal completion.',\n payload: { subtype: event.subtype },\n })\n }\n helpers.reportGenerationStats({\n provider: 'claude_code_cli',\n model: merged.model,\n raw: event.raw as Record<string, unknown> | undefined,\n })\n if (merged.autoAck) ctx.ack()\n })\n // The wrapper, not the adapter, initiates its own shutdown on this path (Decision D\n // step 5) — a terminal NDJSON line proves the wrapper WROTE it, not that the OS\n // process has actually exited yet. Await the wrapper's real exit before resolving so\n // the executor doesn't return while the wrapper (and its `claude` grandchild) are\n // still tearing down.\n await Promise.resolve(child).catch(() => undefined)\n finish()\n return\n }\n if (event.type === 'error') {\n settleOnce(() => {\n finish()\n void gracefulShutdown()\n ctx.nack(new E_CLAUDE_CODE_CLI_WRAPPER_CRASHED([event.message]))\n })\n return\n }\n if (event.type === 'log') {\n helpers.log[event.level]({\n kind: event.kind,\n message: event.message,\n payload: event.payload as Record<string, unknown> | undefined,\n })\n return\n }\n // 'shutdown_complete' — nothing further to do; the wrapper is exiting on its own.\n }\n\n const eventReader = createNdjsonLineReader<WrapperEvent>((raw) => {\n let event: WrapperEvent\n try {\n event = JSON.parse(raw) as WrapperEvent\n } catch {\n helpers.log.trace({\n kind: 'malformed-wrapper-event',\n message: 'Failed to parse wrapper event line; skipping.',\n payload: { linePreview: raw.slice(0, 256) },\n })\n return undefined\n }\n void onEvent(event)\n return event\n })\n\n child.stdout?.on('data', (chunk: Uint8Array) => {\n // Parse BEFORE arming: `armIdleTimer()` is gated on `sawReady && sawInit`, and the very\n // chunk that carries the `init` event is what flips `sawInit` — parsing first lets that\n // same chunk's processing arm the timer immediately, rather than requiring a chunk AFTER\n // init to ever arrive (which, on a genuinely idle stream, never happens).\n eventReader.push(chunk)\n armIdleTimer()\n })\n child.stdout?.on('end', () => {\n // A terminal `result`/`error` event was already observed and its own handler is (or will\n // shortly be) in the middle of its own `settleOnce` — defer to it rather than racing it\n // with a wrong \"stdout ended without a terminal event\" nack for what was actually a\n // successful turn. `sawTerminalEvent` is set synchronously by that handler before any\n // `await`, so it is already true here whenever this really is that race.\n if (sawTerminalEvent) return\n settleOnce(() => {\n finish()\n ctx.nack(\n new E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO([\n 0,\n 'stdout ended without a terminal event',\n ])\n )\n })\n })\n\n void Promise.resolve(child)\n .then((result: unknown) => {\n // Same race as the `stdout.on('end')` guard above: the `result` handler may still be\n // awaiting `sealCurrentMessage()`/the child's own exit when the wrapper process itself\n // settles — defer to the terminal-event path rather than nacking a successful turn.\n if (sawTerminalEvent) return\n const exitCode =\n isObject(result) && 'exitCode' in result\n ? ((result as { exitCode: number | null }).exitCode ?? -1)\n : -1\n settleOnce(() => {\n finish()\n ctx.nack(\n new E_CLAUDE_CODE_CLI_PROCESS_EXITED_NONZERO([\n exitCode,\n 'wrapper process exited with no terminal event observed',\n ])\n )\n })\n })\n .catch(() => {\n if (sawTerminalEvent) return\n settleOnce(() => {\n finish()\n ctx.nack(new E_CLAUDE_CODE_CLI_WRAPPER_CRASHED(['wrapper process rejected']))\n })\n })\n })\n }\n }\n\n /**\n * Returns `true` when `value` is a {@link ClaudeCodeCliAdapter} instance.\n */\n public static isClaudeCodeCliAdapter(value: unknown): value is ClaudeCodeCliAdapter {\n return isInstanceOf(value, 'ClaudeCodeCliAdapter', ClaudeCodeCliAdapter)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+FA,IAAa,kCAA0C;CAKrD,IAAI,OAAA,cAAmB,cAAc,OAAA,UAAe,YAAY,YAC9D,OAAA,UAAe,QAAQ,sCAAsC;CAY/D,OAAO,mBACL,IAAA,IAAA,wCAAA,KAAA,OAAA,KAAA,GAAA,EAAiE,QACnE;AACF;AAIA,IAAM,eAAe,OAAO,aAA4D;CACtF,IAAI,QACF,mBAAmB,OAAO;CAC5B,IAAI,OAAO,UAAU,cAAc,EAAE,UAAW,QAC9C,IAAI;EACF,QAAQ,MAAO,MAAwB;CACzC,SAAS,KAAK;EAEZ,MAAM,IAAI,sCAAsC,CAC9C,0BAFa,QAAQ,GAAG,IAAI,IAAI,UAAU,OAAO,GAAG,EAEnB,mEACnC,CAAC;CACH;CAEF,IAAI,SAA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