@nhtio/adk 1.20260924.0 → 1.20260928.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (317) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/artifact_methods-Cg0go7Q4.mjs +1 -0
  3. package/artifact_methods-CxeKTocm.cjs +1 -0
  4. package/batteries/artifacts/ecmascript.cjs +1 -1
  5. package/batteries/artifacts/ecmascript.mjs +1 -1
  6. package/batteries/artifacts/toon.cjs +1 -1
  7. package/batteries/artifacts/toon.mjs +1 -1
  8. package/batteries/artifacts/xml.cjs +1 -1
  9. package/batteries/artifacts/xml.mjs +1 -1
  10. package/batteries/artifacts/yaml.cjs +1 -1
  11. package/batteries/artifacts/yaml.mjs +1 -1
  12. package/batteries/artifacts.cjs +4 -4
  13. package/batteries/artifacts.mjs +4 -4
  14. package/batteries/dev-tools/forge.cjs +3 -3
  15. package/batteries/dev-tools/forge.mjs +3 -3
  16. package/batteries/dev-tools.cjs +3 -3
  17. package/batteries/dev-tools.mjs +3 -3
  18. package/batteries/encoding.cjs +7 -7
  19. package/batteries/encoding.mjs +7 -7
  20. package/batteries/generation/gemini/adapter.cjs +1 -1
  21. package/batteries/generation/gemini/adapter.mjs +1 -1
  22. package/batteries/generation/local_diffusion/adapter.cjs +1 -1
  23. package/batteries/generation/local_diffusion/adapter.mjs +1 -1
  24. package/batteries/generation/openai/adapter.cjs +1 -1
  25. package/batteries/generation/openai/adapter.mjs +1 -1
  26. package/batteries/llm/anthropic_messages/adapter.cjs +6 -6
  27. package/batteries/llm/anthropic_messages/adapter.mjs +6 -6
  28. package/batteries/llm/anthropic_messages/count_tokens.cjs +1 -1
  29. package/batteries/llm/anthropic_messages/count_tokens.mjs +1 -1
  30. package/batteries/llm/anthropic_messages/helpers.cjs +3 -3
  31. package/batteries/llm/anthropic_messages/helpers.mjs +3 -3
  32. package/batteries/llm/anthropic_messages/validation.cjs +2 -2
  33. package/batteries/llm/anthropic_messages/validation.mjs +2 -2
  34. package/batteries/llm/anthropic_messages.cjs +2 -2
  35. package/batteries/llm/anthropic_messages.mjs +2 -2
  36. package/batteries/llm/bedrock_converse/adapter.cjs +162 -21
  37. package/batteries/llm/bedrock_converse/adapter.cjs.map +1 -1
  38. package/batteries/llm/bedrock_converse/adapter.mjs +162 -21
  39. package/batteries/llm/bedrock_converse/adapter.mjs.map +1 -1
  40. package/batteries/llm/bedrock_converse/helpers.cjs +1 -1
  41. package/batteries/llm/bedrock_converse/helpers.mjs +1 -1
  42. package/batteries/llm/bedrock_converse/validation.cjs +2 -2
  43. package/batteries/llm/bedrock_converse/validation.mjs +2 -2
  44. package/batteries/llm/bedrock_converse.cjs +2 -2
  45. package/batteries/llm/bedrock_converse.mjs +2 -2
  46. package/batteries/llm/claude_code_cli/adapter.cjs +66 -25
  47. package/batteries/llm/claude_code_cli/adapter.cjs.map +1 -1
  48. package/batteries/llm/claude_code_cli/adapter.mjs +66 -25
  49. package/batteries/llm/claude_code_cli/adapter.mjs.map +1 -1
  50. package/batteries/llm/claude_code_cli/helpers.cjs +3 -3
  51. package/batteries/llm/claude_code_cli/helpers.mjs +3 -3
  52. package/batteries/llm/claude_code_cli/line_queue.d.ts +39 -0
  53. package/batteries/llm/claude_code_cli/message_id_state.d.ts +48 -0
  54. package/batteries/llm/claude_code_cli/types.d.ts +76 -0
  55. package/batteries/llm/claude_code_cli/validation.cjs +5 -2
  56. package/batteries/llm/claude_code_cli/validation.cjs.map +1 -1
  57. package/batteries/llm/claude_code_cli/validation.mjs +5 -2
  58. package/batteries/llm/claude_code_cli/validation.mjs.map +1 -1
  59. package/batteries/llm/claude_code_cli/wire.cjs.map +1 -1
  60. package/batteries/llm/claude_code_cli/wire.d.ts +45 -1
  61. package/batteries/llm/claude_code_cli/wire.mjs.map +1 -1
  62. package/batteries/llm/claude_code_cli/wrapper.d.ts +5 -4
  63. package/batteries/llm/claude_code_cli.cjs +2 -2
  64. package/batteries/llm/claude_code_cli.mjs +2 -2
  65. package/batteries/llm/gemini_generate_content/adapter.cjs +160 -19
  66. package/batteries/llm/gemini_generate_content/adapter.cjs.map +1 -1
  67. package/batteries/llm/gemini_generate_content/adapter.mjs +160 -19
  68. package/batteries/llm/gemini_generate_content/adapter.mjs.map +1 -1
  69. package/batteries/llm/gemini_generate_content/helpers.cjs +1 -1
  70. package/batteries/llm/gemini_generate_content/helpers.mjs +1 -1
  71. package/batteries/llm/gemini_generate_content/validation.cjs +2 -2
  72. package/batteries/llm/gemini_generate_content/validation.mjs +2 -2
  73. package/batteries/llm/gemini_generate_content.cjs +1 -1
  74. package/batteries/llm/gemini_generate_content.mjs +1 -1
  75. package/batteries/llm/litert_lm/adapter.cjs +6 -6
  76. package/batteries/llm/litert_lm/adapter.mjs +6 -6
  77. package/batteries/llm/litert_lm/helpers.cjs +3 -3
  78. package/batteries/llm/litert_lm/helpers.mjs +3 -3
  79. package/batteries/llm/litert_lm/validation.cjs +2 -2
  80. package/batteries/llm/litert_lm/validation.mjs +2 -2
  81. package/batteries/llm/litert_lm.cjs +1 -1
  82. package/batteries/llm/litert_lm.mjs +1 -1
  83. package/batteries/llm/ollama/adapter.cjs +6 -6
  84. package/batteries/llm/ollama/adapter.mjs +6 -6
  85. package/batteries/llm/ollama/helpers.cjs +4 -4
  86. package/batteries/llm/ollama/helpers.mjs +4 -4
  87. package/batteries/llm/ollama/validation.cjs +2 -2
  88. package/batteries/llm/ollama/validation.mjs +2 -2
  89. package/batteries/llm/ollama.cjs +2 -2
  90. package/batteries/llm/ollama.mjs +2 -2
  91. package/batteries/llm/openai_chat_completions/adapter.cjs +6 -6
  92. package/batteries/llm/openai_chat_completions/adapter.mjs +6 -6
  93. package/batteries/llm/openai_chat_completions/helpers.cjs +4 -4
  94. package/batteries/llm/openai_chat_completions/helpers.mjs +4 -4
  95. package/batteries/llm/openai_chat_completions/validation.cjs +2 -2
  96. package/batteries/llm/openai_chat_completions/validation.mjs +2 -2
  97. package/batteries/llm/openai_chat_completions.cjs +2 -2
  98. package/batteries/llm/openai_chat_completions.mjs +2 -2
  99. package/batteries/llm/openai_responses/adapter.cjs +6 -6
  100. package/batteries/llm/openai_responses/adapter.mjs +6 -6
  101. package/batteries/llm/openai_responses/helpers.cjs +3 -3
  102. package/batteries/llm/openai_responses/helpers.mjs +3 -3
  103. package/batteries/llm/openai_responses/validation.cjs +2 -2
  104. package/batteries/llm/openai_responses/validation.mjs +2 -2
  105. package/batteries/llm/openai_responses.cjs +2 -2
  106. package/batteries/llm/openai_responses.mjs +2 -2
  107. package/batteries/llm/transformers_js/adapter.cjs +6 -6
  108. package/batteries/llm/transformers_js/adapter.mjs +6 -6
  109. package/batteries/llm/transformers_js/helpers.cjs +3 -3
  110. package/batteries/llm/transformers_js/helpers.mjs +3 -3
  111. package/batteries/llm/transformers_js/validation.cjs +2 -2
  112. package/batteries/llm/transformers_js/validation.mjs +2 -2
  113. package/batteries/llm/transformers_js.cjs +1 -1
  114. package/batteries/llm/transformers_js.mjs +1 -1
  115. package/batteries/llm/webllm_chat_completions/adapter.cjs +6 -6
  116. package/batteries/llm/webllm_chat_completions/adapter.mjs +6 -6
  117. package/batteries/llm/webllm_chat_completions/helpers.cjs +1 -1
  118. package/batteries/llm/webllm_chat_completions/helpers.mjs +1 -1
  119. package/batteries/llm/webllm_chat_completions/validation.cjs +2 -2
  120. package/batteries/llm/webllm_chat_completions/validation.mjs +2 -2
  121. package/batteries/llm/webllm_chat_completions.cjs +2 -2
  122. package/batteries/llm/webllm_chat_completions.mjs +2 -2
  123. package/batteries/llm.cjs +2 -2
  124. package/batteries/llm.mjs +2 -2
  125. package/batteries/media/forge.cjs +4 -4
  126. package/batteries/media/forge.mjs +4 -4
  127. package/batteries/media/lint.cjs +1 -1
  128. package/batteries/media/lint.mjs +1 -1
  129. package/batteries/orchestration/dispatch_reasoner.cjs +4 -4
  130. package/batteries/orchestration/dispatch_reasoner.mjs +4 -4
  131. package/batteries/orchestration/executor.cjs +2 -2
  132. package/batteries/orchestration/executor.mjs +2 -2
  133. package/batteries/orchestration/forge.cjs +4 -4
  134. package/batteries/orchestration/forge.mjs +4 -4
  135. package/batteries/orchestration/validation.cjs +2 -2
  136. package/batteries/orchestration/validation.mjs +2 -2
  137. package/batteries/orchestration.cjs +4 -4
  138. package/batteries/orchestration.mjs +4 -4
  139. package/batteries/sandbox/js.cjs +1 -1
  140. package/batteries/sandbox/js.mjs +1 -1
  141. package/batteries/sandbox/tools.cjs +1 -1
  142. package/batteries/sandbox/tools.mjs +1 -1
  143. package/batteries/sandbox.cjs +3 -3
  144. package/batteries/sandbox.mjs +3 -3
  145. package/batteries/skills.cjs +9 -9
  146. package/batteries/skills.mjs +9 -9
  147. package/batteries/tools/_shared.cjs +1 -1
  148. package/batteries/tools/_shared.mjs +1 -1
  149. package/batteries/tools/color.cjs +2 -2
  150. package/batteries/tools/color.mjs +2 -2
  151. package/batteries/tools/comparison.cjs +2 -2
  152. package/batteries/tools/comparison.mjs +2 -2
  153. package/batteries/tools/data_structure.cjs +2 -2
  154. package/batteries/tools/data_structure.mjs +2 -2
  155. package/batteries/tools/datetime_extended.cjs +3 -3
  156. package/batteries/tools/datetime_extended.mjs +3 -3
  157. package/batteries/tools/datetime_math.cjs +3 -3
  158. package/batteries/tools/datetime_math.mjs +3 -3
  159. package/batteries/tools/encoding.cjs +2 -2
  160. package/batteries/tools/encoding.mjs +2 -2
  161. package/batteries/tools/formatting.cjs +2 -2
  162. package/batteries/tools/formatting.mjs +2 -2
  163. package/batteries/tools/geo_basics.cjs +2 -2
  164. package/batteries/tools/geo_basics.mjs +2 -2
  165. package/batteries/tools/math.cjs +2 -2
  166. package/batteries/tools/math.mjs +2 -2
  167. package/batteries/tools/memory.cjs +5 -5
  168. package/batteries/tools/memory.mjs +5 -5
  169. package/batteries/tools/parsing.cjs +3 -3
  170. package/batteries/tools/parsing.mjs +3 -3
  171. package/batteries/tools/retrievables.cjs +5 -5
  172. package/batteries/tools/retrievables.mjs +5 -5
  173. package/batteries/tools/scrapper.cjs +1 -1
  174. package/batteries/tools/scrapper.mjs +1 -1
  175. package/batteries/tools/searxng.cjs +1 -1
  176. package/batteries/tools/searxng.mjs +1 -1
  177. package/batteries/tools/standing_instructions.cjs +3 -3
  178. package/batteries/tools/standing_instructions.mjs +3 -3
  179. package/batteries/tools/statistics.cjs +3 -3
  180. package/batteries/tools/statistics.mjs +3 -3
  181. package/batteries/tools/string_processing.cjs +2 -2
  182. package/batteries/tools/string_processing.mjs +2 -2
  183. package/batteries/tools/structured_data.cjs +2 -2
  184. package/batteries/tools/structured_data.mjs +2 -2
  185. package/batteries/tools/text_analysis.cjs +3 -3
  186. package/batteries/tools/text_analysis.mjs +3 -3
  187. package/batteries/tools/text_comparison.cjs +2 -2
  188. package/batteries/tools/text_comparison.mjs +2 -2
  189. package/batteries/tools/time.cjs +3 -3
  190. package/batteries/tools/time.mjs +3 -3
  191. package/batteries/tools/unit_conversion.cjs +2 -2
  192. package/batteries/tools/unit_conversion.mjs +2 -2
  193. package/batteries/tools.cjs +2 -2
  194. package/batteries/tools.mjs +2 -2
  195. package/batteries/validation.cjs +4 -4
  196. package/batteries/validation.mjs +4 -4
  197. package/batteries/vector/conformance.cjs +59 -0
  198. package/batteries/vector/conformance.cjs.map +1 -1
  199. package/batteries/vector/conformance.mjs +59 -0
  200. package/batteries/vector/conformance.mjs.map +1 -1
  201. package/batteries/vector/lancedb.cjs +1 -1
  202. package/batteries/vector/lancedb.cjs.map +1 -1
  203. package/batteries/vector/lancedb.mjs +1 -1
  204. package/batteries/vector/lancedb.mjs.map +1 -1
  205. package/batteries/vector/retrievable.cjs +1 -1
  206. package/batteries/vector/retrievable.mjs +1 -1
  207. package/batteries/vector/sqlite_vec/index.d.ts +1 -1
  208. package/batteries/vector/sqlite_vec.cjs +19 -30
  209. package/batteries/vector/sqlite_vec.cjs.map +1 -1
  210. package/batteries/vector/sqlite_vec.mjs +20 -31
  211. package/batteries/vector/sqlite_vec.mjs.map +1 -1
  212. package/batteries.cjs +4 -4
  213. package/batteries.mjs +4 -4
  214. package/{chat_common-B7fvGTKv.cjs → chat_common-CNayzS1V.cjs} +2 -2
  215. package/{chat_common-B7fvGTKv.cjs.map → chat_common-CNayzS1V.cjs.map} +1 -1
  216. package/{chat_common-CeoHwSsz.mjs → chat_common-DKw8FDol.mjs} +2 -2
  217. package/{chat_common-CeoHwSsz.mjs.map → chat_common-DKw8FDol.mjs.map} +1 -1
  218. package/claude-code-cli-wrapper.cjs +104 -22
  219. package/claude-code-cli-wrapper.cjs.map +1 -1
  220. package/claude-code-cli-wrapper.mjs +104 -22
  221. package/claude-code-cli-wrapper.mjs.map +1 -1
  222. package/{common-7gCR3zQu.cjs → common-CqetsItm.cjs} +7 -7
  223. package/{common-7gCR3zQu.cjs.map → common-CqetsItm.cjs.map} +1 -1
  224. package/{common-B5maOoF_.mjs → common-oI1niK9Z.mjs} +7 -7
  225. package/{common-B5maOoF_.mjs.map → common-oI1niK9Z.mjs.map} +1 -1
  226. package/common.cjs +7 -7
  227. package/common.mjs +7 -7
  228. package/{dispatch_runner-DO7jo_gl.mjs → dispatch_runner-BZDXUe0G.mjs} +5 -5
  229. package/{dispatch_runner-DO7jo_gl.mjs.map → dispatch_runner-BZDXUe0G.mjs.map} +1 -1
  230. package/{dispatch_runner-FlriTyoq.cjs → dispatch_runner-DDUxXJC3.cjs} +5 -5
  231. package/{dispatch_runner-FlriTyoq.cjs.map → dispatch_runner-DDUxXJC3.cjs.map} +1 -1
  232. package/dispatch_runner.cjs +1 -1
  233. package/dispatch_runner.mjs +1 -1
  234. package/{ecmascript-bgwVyZG1.mjs → ecmascript-B9Z2C24U.mjs} +3 -3
  235. package/{ecmascript-bgwVyZG1.mjs.map → ecmascript-B9Z2C24U.mjs.map} +1 -1
  236. package/{ecmascript-BydSB03Y.cjs → ecmascript-BYfmjg7y.cjs} +3 -3
  237. package/{ecmascript-BydSB03Y.cjs.map → ecmascript-BYfmjg7y.cjs.map} +1 -1
  238. package/eslint/rules.cjs +1 -1
  239. package/eslint/rules.mjs +1 -1
  240. package/eslint.cjs +2 -2
  241. package/eslint.mjs +2 -2
  242. package/exceptions.cjs +1 -1
  243. package/exceptions.mjs +1 -1
  244. package/forge.cjs +2 -2
  245. package/forge.mjs +2 -2
  246. package/guards.cjs +7 -7
  247. package/guards.mjs +7 -7
  248. package/{helpers-Dcp4CrOz.cjs → helpers-DPlh_7Bn.cjs} +3 -3
  249. package/{helpers-Dcp4CrOz.cjs.map → helpers-DPlh_7Bn.cjs.map} +1 -1
  250. package/{helpers-C1T0DV8Q.mjs → helpers-mbn_EsDV.mjs} +3 -3
  251. package/{helpers-C1T0DV8Q.mjs.map → helpers-mbn_EsDV.mjs.map} +1 -1
  252. package/index.cjs +11 -11
  253. package/index.mjs +11 -11
  254. package/mcp/adk-docs-corpus.json +2 -2
  255. package/package.json +425 -425
  256. package/{retrievable-BBwiACtw.cjs → retrievable-Bq-O3k6r.cjs} +3 -3
  257. package/{retrievable-BBwiACtw.cjs.map → retrievable-Bq-O3k6r.cjs.map} +1 -1
  258. package/{retrievable-CrGKx4sc.mjs → retrievable-CXTAUuuv.mjs} +3 -3
  259. package/{retrievable-CrGKx4sc.mjs.map → retrievable-CXTAUuuv.mjs.map} +1 -1
  260. package/{scrapper-BibKj8qE.cjs → scrapper-B8xG9lTD.cjs} +4 -4
  261. package/{scrapper-BibKj8qE.cjs.map → scrapper-B8xG9lTD.cjs.map} +1 -1
  262. package/{scrapper-_JzgbLG5.mjs → scrapper-DiQ5FfDL.mjs} +4 -4
  263. package/{scrapper-_JzgbLG5.mjs.map → scrapper-DiQ5FfDL.mjs.map} +1 -1
  264. package/{searxng-D-nA2gEI.mjs → searxng-BFTJ6rTE.mjs} +4 -4
  265. package/{searxng-D-nA2gEI.mjs.map → searxng-BFTJ6rTE.mjs.map} +1 -1
  266. package/{searxng-C6xrLW-v.cjs → searxng-EJhWRnIE.cjs} +4 -4
  267. package/{searxng-C6xrLW-v.cjs.map → searxng-EJhWRnIE.cjs.map} +1 -1
  268. package/server.json +2 -2
  269. package/skills/adk-assembly/SKILL.md +2 -2
  270. package/{spooled_artifact-BLgbGT8b.cjs → spooled_artifact---DmicFW.cjs} +384 -384
  271. package/spooled_artifact---DmicFW.cjs.map +1 -0
  272. package/{spooled_artifact-BkOe4-j-.mjs → spooled_artifact-Bw_7swIp.mjs} +385 -385
  273. package/spooled_artifact-Bw_7swIp.mjs.map +1 -0
  274. package/spooled_artifact.cjs +2 -2
  275. package/spooled_artifact.mjs +2 -2
  276. package/{spooled_markdown_artifact-8zdejfcJ.cjs → spooled_markdown_artifact-Rjzj-kyh.cjs} +3 -3
  277. package/{spooled_markdown_artifact-8zdejfcJ.cjs.map → spooled_markdown_artifact-Rjzj-kyh.cjs.map} +1 -1
  278. package/{spooled_markdown_artifact-Dnl-lCGv.mjs → spooled_markdown_artifact-vd6eNtIP.mjs} +3 -3
  279. package/{spooled_markdown_artifact-Dnl-lCGv.mjs.map → spooled_markdown_artifact-vd6eNtIP.mjs.map} +1 -1
  280. package/{thought-BrQt6HAb.mjs → thought-CxSaF6Xf.mjs} +3 -3
  281. package/{thought-BrQt6HAb.mjs.map → thought-CxSaF6Xf.mjs.map} +1 -1
  282. package/{thought-COeZTQ-B.cjs → thought-Dp3sMWW6.cjs} +3 -3
  283. package/{thought-COeZTQ-B.cjs.map → thought-Dp3sMWW6.cjs.map} +1 -1
  284. package/{tokenizable-DDIdXbJN.cjs → tokenizable-BcodRtoW.cjs} +29 -29
  285. package/{tokenizable-DDIdXbJN.cjs.map → tokenizable-BcodRtoW.cjs.map} +1 -1
  286. package/{tokenizable-xPXj1AQX.mjs → tokenizable-VB4Av8GF.mjs} +30 -30
  287. package/{tokenizable-xPXj1AQX.mjs.map → tokenizable-VB4Av8GF.mjs.map} +1 -1
  288. package/{tool_call-JbjeUpRK.cjs → tool_call-B9px4W9k.cjs} +4 -4
  289. package/{tool_call-JbjeUpRK.cjs.map → tool_call-B9px4W9k.cjs.map} +1 -1
  290. package/{tool_call-8crmZsO8.mjs → tool_call-Cfaj-6zK.mjs} +4 -4
  291. package/{tool_call-8crmZsO8.mjs.map → tool_call-Cfaj-6zK.mjs.map} +1 -1
  292. package/{tools-BC4NJqZD.mjs → tools-D0MBDh2R.mjs} +6 -6
  293. package/{tools-BC4NJqZD.mjs.map → tools-D0MBDh2R.mjs.map} +1 -1
  294. package/{tools-D4mdzi0a.cjs → tools-aNbi6JyA.cjs} +6 -6
  295. package/{tools-D4mdzi0a.cjs.map → tools-aNbi6JyA.cjs.map} +1 -1
  296. package/{toon-BA9Q7NHG.mjs → toon-BSTQnHed.mjs} +5 -5
  297. package/{toon-BA9Q7NHG.mjs.map → toon-BSTQnHed.mjs.map} +1 -1
  298. package/{toon-b-0pFKZ8.cjs → toon-DmLwZ6H1.cjs} +5 -5
  299. package/{toon-b-0pFKZ8.cjs.map → toon-DmLwZ6H1.cjs.map} +1 -1
  300. package/{turn_runner-BmVXcBZ2.mjs → turn_runner-BHHD6h77.mjs} +5 -5
  301. package/{turn_runner-BmVXcBZ2.mjs.map → turn_runner-BHHD6h77.mjs.map} +1 -1
  302. package/{turn_runner-DX-3s3ih.cjs → turn_runner-Dj7JsUTQ.cjs} +5 -5
  303. package/{turn_runner-DX-3s3ih.cjs.map → turn_runner-Dj7JsUTQ.cjs.map} +1 -1
  304. package/turn_runner.cjs +1 -1
  305. package/turn_runner.mjs +1 -1
  306. package/{xml-B1JIGLpU.mjs → xml-CYseDztH.mjs} +5 -5
  307. package/{xml-B1JIGLpU.mjs.map → xml-CYseDztH.mjs.map} +1 -1
  308. package/{xml-fvwTsoRv.cjs → xml-zJul8jMQ.cjs} +5 -5
  309. package/{xml-fvwTsoRv.cjs.map → xml-zJul8jMQ.cjs.map} +1 -1
  310. package/{yaml-1mP4uxdf.mjs → yaml-BPBoiOjx.mjs} +5 -5
  311. package/{yaml-1mP4uxdf.mjs.map → yaml-BPBoiOjx.mjs.map} +1 -1
  312. package/{yaml-DPUTumla.cjs → yaml-D0PzoRAr.cjs} +5 -5
  313. package/{yaml-DPUTumla.cjs.map → yaml-D0PzoRAr.cjs.map} +1 -1
  314. package/artifact_methods-7KatxCSd.cjs +0 -1
  315. package/artifact_methods-q52ETLwI.mjs +0 -1
  316. package/spooled_artifact-BLgbGT8b.cjs.map +0 -1
  317. package/spooled_artifact-BkOe4-j-.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"claude-code-cli-wrapper.mjs","names":["#body","#init","crypto","Http2ServerRequest2","h2constants"],"sources":["../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.23/node_modules/@hono/node-server/dist/index.mjs","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js","../src/batteries/llm/claude_code_cli/mcp_bridge.ts","../src/batteries/llm/claude_code_cli/cli_protocol.ts","../src/batteries/llm/claude_code_cli/wrapper.ts"],"sourcesContent":["// src/server.ts\nimport { createServer as createServerHTTP } from \"http\";\n\n// src/listener.ts\nimport { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from \"http2\";\n\n// src/request.ts\nimport { Http2ServerRequest } from \"http2\";\nimport { Readable } from \"stream\";\nvar RequestError = class extends Error {\n constructor(message, options) {\n super(message, options);\n this.name = \"RequestError\";\n }\n};\nvar toRequestError = (e) => {\n if (e instanceof RequestError) {\n return e;\n }\n return new RequestError(e.message, { cause: e });\n};\nvar GlobalRequest = global.Request;\nvar Request = class extends GlobalRequest {\n constructor(input, options) {\n if (typeof input === \"object\" && getRequestCache in input) {\n input = input[getRequestCache]();\n }\n if (typeof options?.body?.getReader !== \"undefined\") {\n ;\n options.duplex ??= \"half\";\n }\n super(input, options);\n }\n};\nvar newHeadersFromIncoming = (incoming) => {\n const headerRecord = [];\n const rawHeaders = incoming.rawHeaders;\n for (let i = 0; i < rawHeaders.length; i += 2) {\n const { [i]: key, [i + 1]: value } = rawHeaders;\n if (key.charCodeAt(0) !== /*:*/\n 58) {\n headerRecord.push([key, value]);\n }\n }\n return new Headers(headerRecord);\n};\nvar wrapBodyStream = Symbol(\"wrapBodyStream\");\nvar newRequestFromIncoming = (method, url, headers, incoming, abortController) => {\n const init = {\n method,\n headers,\n signal: abortController.signal\n };\n if (method === \"TRACE\") {\n init.method = \"GET\";\n const req = new Request(url, init);\n Object.defineProperty(req, \"method\", {\n get() {\n return \"TRACE\";\n }\n });\n return req;\n }\n if (!(method === \"GET\" || method === \"HEAD\")) {\n if (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) {\n init.body = new ReadableStream({\n start(controller) {\n controller.enqueue(incoming.rawBody);\n controller.close();\n }\n });\n } else if (incoming[wrapBodyStream]) {\n let reader;\n init.body = new ReadableStream({\n async pull(controller) {\n try {\n reader ||= Readable.toWeb(incoming).getReader();\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n });\n } else {\n init.body = Readable.toWeb(incoming);\n }\n }\n return new Request(url, init);\n};\nvar getRequestCache = Symbol(\"getRequestCache\");\nvar requestCache = Symbol(\"requestCache\");\nvar incomingKey = Symbol(\"incomingKey\");\nvar urlKey = Symbol(\"urlKey\");\nvar headersKey = Symbol(\"headersKey\");\nvar abortControllerKey = Symbol(\"abortControllerKey\");\nvar getAbortController = Symbol(\"getAbortController\");\nvar requestPrototype = {\n get method() {\n return this[incomingKey].method || \"GET\";\n },\n get url() {\n return this[urlKey];\n },\n get headers() {\n return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);\n },\n [getAbortController]() {\n this[getRequestCache]();\n return this[abortControllerKey];\n },\n [getRequestCache]() {\n this[abortControllerKey] ||= new AbortController();\n return this[requestCache] ||= newRequestFromIncoming(\n this.method,\n this[urlKey],\n this.headers,\n this[incomingKey],\n this[abortControllerKey]\n );\n }\n};\n[\n \"body\",\n \"bodyUsed\",\n \"cache\",\n \"credentials\",\n \"destination\",\n \"integrity\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"keepalive\"\n].forEach((k) => {\n Object.defineProperty(requestPrototype, k, {\n get() {\n return this[getRequestCache]()[k];\n }\n });\n});\n[\"arrayBuffer\", \"blob\", \"clone\", \"formData\", \"json\", \"text\"].forEach((k) => {\n Object.defineProperty(requestPrototype, k, {\n value: function() {\n return this[getRequestCache]()[k]();\n }\n });\n});\nObject.defineProperty(requestPrototype, Symbol.for(\"nodejs.util.inspect.custom\"), {\n value: function(depth, options, inspectFn) {\n const props = {\n method: this.method,\n url: this.url,\n headers: this.headers,\n nativeRequest: this[requestCache]\n };\n return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;\n }\n});\nObject.setPrototypeOf(requestPrototype, Request.prototype);\nvar newRequest = (incoming, defaultHostname) => {\n const req = Object.create(requestPrototype);\n req[incomingKey] = incoming;\n const incomingUrl = incoming.url || \"\";\n if (incomingUrl[0] !== \"/\" && // short-circuit for performance. most requests are relative URL.\n (incomingUrl.startsWith(\"http://\") || incomingUrl.startsWith(\"https://\"))) {\n if (incoming instanceof Http2ServerRequest) {\n throw new RequestError(\"Absolute URL for :path is not allowed in HTTP/2\");\n }\n try {\n const url2 = new URL(incomingUrl);\n req[urlKey] = url2.href;\n } catch (e) {\n throw new RequestError(\"Invalid absolute URL\", { cause: e });\n }\n return req;\n }\n const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;\n if (!host) {\n throw new RequestError(\"Missing host header\");\n }\n let scheme;\n if (incoming instanceof Http2ServerRequest) {\n scheme = incoming.scheme;\n if (!(scheme === \"http\" || scheme === \"https\")) {\n throw new RequestError(\"Unsupported scheme\");\n }\n } else {\n scheme = incoming.socket && incoming.socket.encrypted ? \"https\" : \"http\";\n }\n const url = new URL(`${scheme}://${host}${incomingUrl}`);\n if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\\d+$/, \"\")) {\n throw new RequestError(\"Invalid host header\");\n }\n req[urlKey] = url.href;\n return req;\n};\n\n// src/response.ts\nvar responseCache = Symbol(\"responseCache\");\nvar getResponseCache = Symbol(\"getResponseCache\");\nvar cacheKey = Symbol(\"cache\");\nvar GlobalResponse = global.Response;\nvar Response2 = class _Response {\n #body;\n #init;\n [getResponseCache]() {\n delete this[cacheKey];\n return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);\n }\n constructor(body, init) {\n let headers;\n this.#body = body;\n if (init instanceof _Response) {\n const cachedGlobalResponse = init[responseCache];\n if (cachedGlobalResponse) {\n this.#init = cachedGlobalResponse;\n this[getResponseCache]();\n return;\n } else {\n this.#init = init.#init;\n headers = new Headers(init.#init.headers);\n }\n } else {\n this.#init = init;\n }\n if (typeof body === \"string\" || typeof body?.getReader !== \"undefined\" || body instanceof Blob || body instanceof Uint8Array) {\n ;\n this[cacheKey] = [init?.status || 200, body, headers || init?.headers];\n }\n }\n get headers() {\n const cache = this[cacheKey];\n if (cache) {\n if (!(cache[2] instanceof Headers)) {\n cache[2] = new Headers(\n cache[2] || { \"content-type\": \"text/plain; charset=UTF-8\" }\n );\n }\n return cache[2];\n }\n return this[getResponseCache]().headers;\n }\n get status() {\n return this[cacheKey]?.[0] ?? this[getResponseCache]().status;\n }\n get ok() {\n const status = this.status;\n return status >= 200 && status < 300;\n }\n};\n[\"body\", \"bodyUsed\", \"redirected\", \"statusText\", \"trailers\", \"type\", \"url\"].forEach((k) => {\n Object.defineProperty(Response2.prototype, k, {\n get() {\n return this[getResponseCache]()[k];\n }\n });\n});\n[\"arrayBuffer\", \"blob\", \"clone\", \"formData\", \"json\", \"text\"].forEach((k) => {\n Object.defineProperty(Response2.prototype, k, {\n value: function() {\n return this[getResponseCache]()[k]();\n }\n });\n});\nObject.defineProperty(Response2.prototype, Symbol.for(\"nodejs.util.inspect.custom\"), {\n value: function(depth, options, inspectFn) {\n const props = {\n status: this.status,\n headers: this.headers,\n ok: this.ok,\n nativeResponse: this[responseCache]\n };\n return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;\n }\n});\nObject.setPrototypeOf(Response2, GlobalResponse);\nObject.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);\n\n// src/utils.ts\nasync function readWithoutBlocking(readPromise) {\n return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);\n}\nfunction writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {\n const cancel = (error) => {\n reader.cancel(error).catch(() => {\n });\n };\n writable.on(\"close\", cancel);\n writable.on(\"error\", cancel);\n (currentReadPromise ?? reader.read()).then(flow, handleStreamError);\n return reader.closed.finally(() => {\n writable.off(\"close\", cancel);\n writable.off(\"error\", cancel);\n });\n function handleStreamError(error) {\n if (error) {\n writable.destroy(error);\n }\n }\n function onDrain() {\n reader.read().then(flow, handleStreamError);\n }\n function flow({ done, value }) {\n try {\n if (done) {\n writable.end();\n } else if (!writable.write(value)) {\n writable.once(\"drain\", onDrain);\n } else {\n return reader.read().then(flow, handleStreamError);\n }\n } catch (e) {\n handleStreamError(e);\n }\n }\n}\nfunction writeFromReadableStream(stream, writable) {\n if (stream.locked) {\n throw new TypeError(\"ReadableStream is locked.\");\n } else if (writable.destroyed) {\n return;\n }\n return writeFromReadableStreamDefaultReader(stream.getReader(), writable);\n}\nvar buildOutgoingHttpHeaders = (headers) => {\n const res = {};\n if (!(headers instanceof Headers)) {\n headers = new Headers(headers ?? void 0);\n }\n const cookies = [];\n for (const [k, v] of headers) {\n if (k === \"set-cookie\") {\n cookies.push(v);\n } else {\n res[k] = v;\n }\n }\n if (cookies.length > 0) {\n res[\"set-cookie\"] = cookies;\n }\n res[\"content-type\"] ??= \"text/plain; charset=UTF-8\";\n return res;\n};\n\n// src/utils/response/constants.ts\nvar X_ALREADY_SENT = \"x-hono-already-sent\";\n\n// src/globals.ts\nimport crypto from \"crypto\";\nif (typeof global.crypto === \"undefined\") {\n global.crypto = crypto;\n}\n\n// src/listener.ts\nvar outgoingEnded = Symbol(\"outgoingEnded\");\nvar incomingDraining = Symbol(\"incomingDraining\");\nvar DRAIN_TIMEOUT_MS = 500;\nvar MAX_DRAIN_BYTES = 64 * 1024 * 1024;\nvar drainIncoming = (incoming) => {\n const incomingWithDrainState = incoming;\n if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {\n return;\n }\n incomingWithDrainState[incomingDraining] = true;\n if (incoming instanceof Http2ServerRequest2) {\n try {\n ;\n incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);\n } catch {\n }\n return;\n }\n let bytesRead = 0;\n const cleanup = () => {\n clearTimeout(timer);\n incoming.off(\"data\", onData);\n incoming.off(\"end\", cleanup);\n incoming.off(\"error\", cleanup);\n };\n const forceClose = () => {\n cleanup();\n const socket = incoming.socket;\n if (socket && !socket.destroyed) {\n socket.destroySoon();\n }\n };\n const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);\n timer.unref?.();\n const onData = (chunk) => {\n bytesRead += chunk.length;\n if (bytesRead > MAX_DRAIN_BYTES) {\n forceClose();\n }\n };\n incoming.on(\"data\", onData);\n incoming.on(\"end\", cleanup);\n incoming.on(\"error\", cleanup);\n incoming.resume();\n};\nvar handleRequestError = () => new Response(null, {\n status: 400\n});\nvar handleFetchError = (e) => new Response(null, {\n status: e instanceof Error && (e.name === \"TimeoutError\" || e.constructor.name === \"TimeoutError\") ? 504 : 500\n});\nvar handleResponseError = (e, outgoing) => {\n const err = e instanceof Error ? e : new Error(\"unknown error\", { cause: e });\n if (err.code === \"ERR_STREAM_PREMATURE_CLOSE\") {\n console.info(\"The user aborted a request.\");\n } else {\n console.error(e);\n if (!outgoing.headersSent) {\n outgoing.writeHead(500, { \"Content-Type\": \"text/plain\" });\n }\n outgoing.end(`Error: ${err.message}`);\n outgoing.destroy(err);\n }\n};\nvar flushHeaders = (outgoing) => {\n if (\"flushHeaders\" in outgoing && outgoing.writable) {\n outgoing.flushHeaders();\n }\n};\nvar responseViaCache = async (res, outgoing) => {\n let [status, body, header] = res[cacheKey];\n let hasContentLength = false;\n if (!header) {\n header = { \"content-type\": \"text/plain; charset=UTF-8\" };\n } else if (header instanceof Headers) {\n hasContentLength = header.has(\"content-length\");\n header = buildOutgoingHttpHeaders(header);\n } else if (Array.isArray(header)) {\n const headerObj = new Headers(header);\n hasContentLength = headerObj.has(\"content-length\");\n header = buildOutgoingHttpHeaders(headerObj);\n } else {\n for (const key in header) {\n if (key.length === 14 && key.toLowerCase() === \"content-length\") {\n hasContentLength = true;\n break;\n }\n }\n }\n if (!hasContentLength) {\n if (typeof body === \"string\") {\n header[\"Content-Length\"] = Buffer.byteLength(body);\n } else if (body instanceof Uint8Array) {\n header[\"Content-Length\"] = body.byteLength;\n } else if (body instanceof Blob) {\n header[\"Content-Length\"] = body.size;\n }\n }\n outgoing.writeHead(status, header);\n if (typeof body === \"string\" || body instanceof Uint8Array) {\n outgoing.end(body);\n } else if (body instanceof Blob) {\n outgoing.end(new Uint8Array(await body.arrayBuffer()));\n } else {\n flushHeaders(outgoing);\n await writeFromReadableStream(body, outgoing)?.catch(\n (e) => handleResponseError(e, outgoing)\n );\n }\n ;\n outgoing[outgoingEnded]?.();\n};\nvar isPromise = (res) => typeof res.then === \"function\";\nvar responseViaResponseObject = async (res, outgoing, options = {}) => {\n if (isPromise(res)) {\n if (options.errorHandler) {\n try {\n res = await res;\n } catch (err) {\n const errRes = await options.errorHandler(err);\n if (!errRes) {\n return;\n }\n res = errRes;\n }\n } else {\n res = await res.catch(handleFetchError);\n }\n }\n if (cacheKey in res) {\n return responseViaCache(res, outgoing);\n }\n const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);\n if (res.body) {\n const reader = res.body.getReader();\n const values = [];\n let done = false;\n let currentReadPromise = void 0;\n if (resHeaderRecord[\"transfer-encoding\"] !== \"chunked\") {\n let maxReadCount = 2;\n for (let i = 0; i < maxReadCount; i++) {\n currentReadPromise ||= reader.read();\n const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {\n console.error(e);\n done = true;\n });\n if (!chunk) {\n if (i === 1) {\n await new Promise((resolve) => setTimeout(resolve));\n maxReadCount = 3;\n continue;\n }\n break;\n }\n currentReadPromise = void 0;\n if (chunk.value) {\n values.push(chunk.value);\n }\n if (chunk.done) {\n done = true;\n break;\n }\n }\n if (done && !(\"content-length\" in resHeaderRecord)) {\n resHeaderRecord[\"content-length\"] = values.reduce((acc, value) => acc + value.length, 0);\n }\n }\n outgoing.writeHead(res.status, resHeaderRecord);\n values.forEach((value) => {\n ;\n outgoing.write(value);\n });\n if (done) {\n outgoing.end();\n } else {\n if (values.length === 0) {\n flushHeaders(outgoing);\n }\n await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);\n }\n } else if (resHeaderRecord[X_ALREADY_SENT]) {\n } else {\n outgoing.writeHead(res.status, resHeaderRecord);\n outgoing.end();\n }\n ;\n outgoing[outgoingEnded]?.();\n};\nvar getRequestListener = (fetchCallback, options = {}) => {\n const autoCleanupIncoming = options.autoCleanupIncoming ?? true;\n if (options.overrideGlobalObjects !== false && global.Request !== Request) {\n Object.defineProperty(global, \"Request\", {\n value: Request\n });\n Object.defineProperty(global, \"Response\", {\n value: Response2\n });\n }\n return async (incoming, outgoing) => {\n let res, req;\n try {\n req = newRequest(incoming, options.hostname);\n let incomingEnded = !autoCleanupIncoming || incoming.method === \"GET\" || incoming.method === \"HEAD\";\n if (!incomingEnded) {\n ;\n incoming[wrapBodyStream] = true;\n incoming.on(\"end\", () => {\n incomingEnded = true;\n });\n if (incoming instanceof Http2ServerRequest2) {\n ;\n outgoing[outgoingEnded] = () => {\n if (!incomingEnded) {\n setTimeout(() => {\n if (!incomingEnded) {\n setTimeout(() => {\n drainIncoming(incoming);\n });\n }\n });\n }\n };\n }\n outgoing.on(\"finish\", () => {\n if (!incomingEnded) {\n drainIncoming(incoming);\n }\n });\n }\n outgoing.on(\"close\", () => {\n const abortController = req[abortControllerKey];\n if (abortController) {\n if (incoming.errored) {\n req[abortControllerKey].abort(incoming.errored.toString());\n } else if (!outgoing.writableFinished) {\n req[abortControllerKey].abort(\"Client connection prematurely closed.\");\n }\n }\n if (!incomingEnded) {\n setTimeout(() => {\n if (!incomingEnded) {\n setTimeout(() => {\n drainIncoming(incoming);\n });\n }\n });\n }\n });\n res = fetchCallback(req, { incoming, outgoing });\n if (cacheKey in res) {\n return responseViaCache(res, outgoing);\n }\n } catch (e) {\n if (!res) {\n if (options.errorHandler) {\n res = await options.errorHandler(req ? e : toRequestError(e));\n if (!res) {\n return;\n }\n } else if (!req) {\n res = handleRequestError();\n } else {\n res = handleFetchError(e);\n }\n } else {\n return handleResponseError(e, outgoing);\n }\n }\n try {\n return await responseViaResponseObject(res, outgoing, options);\n } catch (e) {\n return handleResponseError(e, outgoing);\n }\n };\n};\n\n// src/server.ts\nvar createAdaptorServer = (options) => {\n const fetchCallback = options.fetch;\n const requestListener = getRequestListener(fetchCallback, {\n hostname: options.hostname,\n overrideGlobalObjects: options.overrideGlobalObjects,\n autoCleanupIncoming: options.autoCleanupIncoming\n });\n const createServer = options.createServer || createServerHTTP;\n const server = createServer(options.serverOptions || {}, requestListener);\n return server;\n};\nvar serve = (options, listeningListener) => {\n const server = createAdaptorServer(options);\n server.listen(options?.port ?? 3e3, options.hostname, () => {\n const serverInfo = server.address();\n listeningListener && listeningListener(serverInfo);\n });\n return server;\n};\nexport {\n RequestError,\n createAdaptorServer,\n getRequestListener,\n serve\n};\n","/**\n * Web Standards Streamable HTTP Server Transport\n *\n * This is the core transport implementation using Web Standard APIs (Request, Response, ReadableStream).\n * It can run on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc.\n *\n * For Node.js Express/HTTP compatibility, use `StreamableHTTPServerTransport` which wraps this transport.\n */\nimport { isInitializeRequest, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema, SUPPORTED_PROTOCOL_VERSIONS, DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from '../types.js';\n/**\n * Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification\n * using Web Standard APIs (Request, Response, ReadableStream).\n *\n * This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc.\n *\n * Usage example:\n *\n * ```typescript\n * // Stateful mode - server sets the session ID\n * const statefulTransport = new WebStandardStreamableHTTPServerTransport({\n * sessionIdGenerator: () => crypto.randomUUID(),\n * });\n *\n * // Stateless mode - explicitly set session ID to undefined\n * const statelessTransport = new WebStandardStreamableHTTPServerTransport({\n * sessionIdGenerator: undefined,\n * });\n *\n * // Hono.js usage\n * app.all('/mcp', async (c) => {\n * return transport.handleRequest(c.req.raw);\n * });\n *\n * // Cloudflare Workers usage\n * export default {\n * async fetch(request: Request): Promise<Response> {\n * return transport.handleRequest(request);\n * }\n * };\n * ```\n *\n * In stateful mode:\n * - Session ID is generated and included in response headers\n * - Session ID is always included in initialization responses\n * - Requests with invalid session IDs are rejected with 404 Not Found\n * - Non-initialization requests without a session ID are rejected with 400 Bad Request\n * - State is maintained in-memory (connections, message history)\n *\n * In stateless mode:\n * - No Session ID is included in any responses\n * - No session validation is performed\n */\nexport class WebStandardStreamableHTTPServerTransport {\n constructor(options = {}) {\n this._started = false;\n this._hasHandledRequest = false;\n this._streamMapping = new Map();\n this._requestToStreamMapping = new Map();\n this._requestResponseMap = new Map();\n this._initialized = false;\n this._enableJsonResponse = false;\n this._standaloneSseStreamId = '_GET_stream';\n this.sessionIdGenerator = options.sessionIdGenerator;\n this._enableJsonResponse = options.enableJsonResponse ?? false;\n this._eventStore = options.eventStore;\n this._onsessioninitialized = options.onsessioninitialized;\n this._onsessionclosed = options.onsessionclosed;\n this._allowedHosts = options.allowedHosts;\n this._allowedOrigins = options.allowedOrigins;\n this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false;\n this._retryInterval = options.retryInterval;\n }\n /**\n * Starts the transport. This is required by the Transport interface but is a no-op\n * for the Streamable HTTP transport as connections are managed per-request.\n */\n async start() {\n if (this._started) {\n throw new Error('Transport already started');\n }\n this._started = true;\n }\n /**\n * Helper to create a JSON error response\n */\n createJsonErrorResponse(status, code, message, options) {\n const error = { code, message };\n if (options?.data !== undefined) {\n error.data = options.data;\n }\n return new Response(JSON.stringify({\n jsonrpc: '2.0',\n error,\n id: null\n }), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n ...options?.headers\n }\n });\n }\n /**\n * Validates request headers for DNS rebinding protection.\n * @returns Error response if validation fails, undefined if validation passes.\n */\n validateRequestHeaders(req) {\n // Skip validation if protection is not enabled\n if (!this._enableDnsRebindingProtection) {\n return undefined;\n }\n // Validate Host header if allowedHosts is configured\n if (this._allowedHosts && this._allowedHosts.length > 0) {\n const hostHeader = req.headers.get('host');\n if (!hostHeader || !this._allowedHosts.includes(hostHeader)) {\n const error = `Invalid Host header: ${hostHeader}`;\n this.onerror?.(new Error(error));\n return this.createJsonErrorResponse(403, -32000, error);\n }\n }\n // Validate Origin header if allowedOrigins is configured\n if (this._allowedOrigins && this._allowedOrigins.length > 0) {\n const originHeader = req.headers.get('origin');\n if (originHeader && !this._allowedOrigins.includes(originHeader)) {\n const error = `Invalid Origin header: ${originHeader}`;\n this.onerror?.(new Error(error));\n return this.createJsonErrorResponse(403, -32000, error);\n }\n }\n return undefined;\n }\n /**\n * Handles an incoming HTTP request, whether GET, POST, or DELETE\n * Returns a Response object (Web Standard)\n */\n async handleRequest(req, options) {\n // In stateless mode (no sessionIdGenerator), each request must use a fresh transport.\n // Reusing a stateless transport causes message ID collisions between clients.\n if (!this.sessionIdGenerator && this._hasHandledRequest) {\n throw new Error('Stateless transport cannot be reused across requests. Create a new transport per request.');\n }\n this._hasHandledRequest = true;\n // Validate request headers for DNS rebinding protection\n const validationError = this.validateRequestHeaders(req);\n if (validationError) {\n return validationError;\n }\n switch (req.method) {\n case 'POST':\n return this.handlePostRequest(req, options);\n case 'GET':\n return this.handleGetRequest(req);\n case 'DELETE':\n return this.handleDeleteRequest(req);\n default:\n return this.handleUnsupportedRequest();\n }\n }\n /**\n * Writes a priming event to establish resumption capability.\n * Only sends if eventStore is configured (opt-in for resumability) and\n * the client's protocol version supports empty SSE data (>= 2025-11-25).\n */\n async writePrimingEvent(controller, encoder, streamId, protocolVersion) {\n if (!this._eventStore) {\n return;\n }\n // Priming events have empty data which older clients cannot handle.\n // Only send priming events to clients with protocol version >= 2025-11-25\n // which includes the fix for handling empty SSE data.\n if (protocolVersion < '2025-11-25') {\n return;\n }\n const primingEventId = await this._eventStore.storeEvent(streamId, {});\n let primingEvent = `id: ${primingEventId}\\ndata: \\n\\n`;\n if (this._retryInterval !== undefined) {\n primingEvent = `id: ${primingEventId}\\nretry: ${this._retryInterval}\\ndata: \\n\\n`;\n }\n controller.enqueue(encoder.encode(primingEvent));\n }\n /**\n * Handles GET requests for SSE stream\n */\n async handleGetRequest(req) {\n // The client MUST include an Accept header, listing text/event-stream as a supported content type.\n const acceptHeader = req.headers.get('accept');\n if (!acceptHeader?.includes('text/event-stream')) {\n this.onerror?.(new Error('Not Acceptable: Client must accept text/event-stream'));\n return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept text/event-stream');\n }\n // If an Mcp-Session-Id is returned by the server during initialization,\n // clients using the Streamable HTTP transport MUST include it\n // in the Mcp-Session-Id header on all of their subsequent HTTP requests.\n const sessionError = this.validateSession(req);\n if (sessionError) {\n return sessionError;\n }\n const protocolError = this.validateProtocolVersion(req);\n if (protocolError) {\n return protocolError;\n }\n // Handle resumability: check for Last-Event-ID header\n if (this._eventStore) {\n const lastEventId = req.headers.get('last-event-id');\n if (lastEventId) {\n return this.replayEvents(lastEventId);\n }\n }\n // Check if there's already an active standalone SSE stream for this session\n if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) {\n // Only one GET SSE stream is allowed per session\n this.onerror?.(new Error('Conflict: Only one SSE stream is allowed per session'));\n return this.createJsonErrorResponse(409, -32000, 'Conflict: Only one SSE stream is allowed per session');\n }\n const encoder = new TextEncoder();\n let streamController;\n // Create a ReadableStream with a controller we can use to push SSE events\n const readable = new ReadableStream({\n start: controller => {\n streamController = controller;\n },\n cancel: () => {\n // Stream was cancelled by client\n this._streamMapping.delete(this._standaloneSseStreamId);\n }\n });\n const headers = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive'\n };\n // After initialization, always include the session ID if we have one\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n // Store the stream mapping with the controller for pushing data\n this._streamMapping.set(this._standaloneSseStreamId, {\n controller: streamController,\n encoder,\n cleanup: () => {\n this._streamMapping.delete(this._standaloneSseStreamId);\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n });\n return new Response(readable, { headers });\n }\n /**\n * Replays events that would have been sent after the specified event ID\n * Only used when resumability is enabled\n */\n async replayEvents(lastEventId) {\n if (!this._eventStore) {\n this.onerror?.(new Error('Event store not configured'));\n return this.createJsonErrorResponse(400, -32000, 'Event store not configured');\n }\n try {\n // If getStreamIdForEventId is available, use it for conflict checking\n let streamId;\n if (this._eventStore.getStreamIdForEventId) {\n streamId = await this._eventStore.getStreamIdForEventId(lastEventId);\n if (!streamId) {\n this.onerror?.(new Error('Invalid event ID format'));\n return this.createJsonErrorResponse(400, -32000, 'Invalid event ID format');\n }\n // Check conflict with the SAME streamId we'll use for mapping\n if (this._streamMapping.get(streamId) !== undefined) {\n this.onerror?.(new Error('Conflict: Stream already has an active connection'));\n return this.createJsonErrorResponse(409, -32000, 'Conflict: Stream already has an active connection');\n }\n }\n const headers = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive'\n };\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n // Create a ReadableStream with controller for SSE\n const encoder = new TextEncoder();\n let streamController;\n const readable = new ReadableStream({\n start: controller => {\n streamController = controller;\n },\n cancel: () => {\n // Stream was cancelled by client\n // Cleanup will be handled by the mapping\n }\n });\n // Replay events - returns the streamId for backwards compatibility\n const replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, {\n send: async (eventId, message) => {\n const success = this.writeSSEEvent(streamController, encoder, message, eventId);\n if (!success) {\n this.onerror?.(new Error('Failed replay events'));\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n }\n });\n this._streamMapping.set(replayedStreamId, {\n controller: streamController,\n encoder,\n cleanup: () => {\n this._streamMapping.delete(replayedStreamId);\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n });\n return new Response(readable, { headers });\n }\n catch (error) {\n this.onerror?.(error);\n return this.createJsonErrorResponse(500, -32000, 'Error replaying events');\n }\n }\n /**\n * Writes an event to an SSE stream via controller with proper formatting\n */\n writeSSEEvent(controller, encoder, message, eventId) {\n try {\n let eventData = `event: message\\n`;\n // Include event ID if provided - this is important for resumability\n if (eventId) {\n eventData += `id: ${eventId}\\n`;\n }\n eventData += `data: ${JSON.stringify(message)}\\n\\n`;\n controller.enqueue(encoder.encode(eventData));\n return true;\n }\n catch (error) {\n this.onerror?.(error);\n return false;\n }\n }\n /**\n * Handles unsupported requests (PUT, PATCH, etc.)\n */\n handleUnsupportedRequest() {\n this.onerror?.(new Error('Method not allowed.'));\n return new Response(JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32000,\n message: 'Method not allowed.'\n },\n id: null\n }), {\n status: 405,\n headers: {\n Allow: 'GET, POST, DELETE',\n 'Content-Type': 'application/json'\n }\n });\n }\n /**\n * Handles POST requests containing JSON-RPC messages\n */\n async handlePostRequest(req, options) {\n try {\n // Validate the Accept header\n const acceptHeader = req.headers.get('accept');\n // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types.\n if (!acceptHeader?.includes('application/json') || !acceptHeader.includes('text/event-stream')) {\n this.onerror?.(new Error('Not Acceptable: Client must accept both application/json and text/event-stream'));\n return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept both application/json and text/event-stream');\n }\n const ct = req.headers.get('content-type');\n if (!ct || !ct.includes('application/json')) {\n this.onerror?.(new Error('Unsupported Media Type: Content-Type must be application/json'));\n return this.createJsonErrorResponse(415, -32000, 'Unsupported Media Type: Content-Type must be application/json');\n }\n // Build request info from headers and URL\n const requestInfo = {\n headers: Object.fromEntries(req.headers.entries()),\n url: new URL(req.url)\n };\n let rawMessage;\n if (options?.parsedBody !== undefined) {\n rawMessage = options.parsedBody;\n }\n else {\n try {\n rawMessage = await req.json();\n }\n catch {\n this.onerror?.(new Error('Parse error: Invalid JSON'));\n return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON');\n }\n }\n let messages;\n // handle batch and single messages\n try {\n if (Array.isArray(rawMessage)) {\n messages = rawMessage.map(msg => JSONRPCMessageSchema.parse(msg));\n }\n else {\n messages = [JSONRPCMessageSchema.parse(rawMessage)];\n }\n }\n catch {\n this.onerror?.(new Error('Parse error: Invalid JSON-RPC message'));\n return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON-RPC message');\n }\n // Check if this is an initialization request\n // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/\n const isInitializationRequest = messages.some(isInitializeRequest);\n if (isInitializationRequest) {\n // If it's a server with session management and the session ID is already set we should reject the request\n // to avoid re-initialization.\n if (this._initialized && this.sessionId !== undefined) {\n this.onerror?.(new Error('Invalid Request: Server already initialized'));\n return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Server already initialized');\n }\n if (messages.length > 1) {\n this.onerror?.(new Error('Invalid Request: Only one initialization request is allowed'));\n return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Only one initialization request is allowed');\n }\n this.sessionId = this.sessionIdGenerator?.();\n this._initialized = true;\n // If we have a session ID and an onsessioninitialized handler, call it immediately\n // This is needed in cases where the server needs to keep track of multiple sessions\n if (this.sessionId && this._onsessioninitialized) {\n await Promise.resolve(this._onsessioninitialized(this.sessionId));\n }\n }\n if (!isInitializationRequest) {\n // If an Mcp-Session-Id is returned by the server during initialization,\n // clients using the Streamable HTTP transport MUST include it\n // in the Mcp-Session-Id header on all of their subsequent HTTP requests.\n const sessionError = this.validateSession(req);\n if (sessionError) {\n return sessionError;\n }\n // Mcp-Protocol-Version header is required for all requests after initialization.\n const protocolError = this.validateProtocolVersion(req);\n if (protocolError) {\n return protocolError;\n }\n }\n // check if it contains requests\n const hasRequests = messages.some(isJSONRPCRequest);\n if (!hasRequests) {\n // if it only contains notifications or responses, return 202\n for (const message of messages) {\n this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo });\n }\n return new Response(null, { status: 202 });\n }\n // The default behavior is to use SSE streaming\n // but in some cases server will return JSON responses\n const streamId = crypto.randomUUID();\n // Extract protocol version for priming event decision.\n // For initialize requests, get from request params.\n // For other requests, get from header (already validated).\n const initRequest = messages.find(m => isInitializeRequest(m));\n const clientProtocolVersion = initRequest\n ? initRequest.params.protocolVersion\n : (req.headers.get('mcp-protocol-version') ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION);\n if (this._enableJsonResponse) {\n // For JSON response mode, return a Promise that resolves when all responses are ready\n return new Promise(resolve => {\n this._streamMapping.set(streamId, {\n resolveJson: resolve,\n cleanup: () => {\n this._streamMapping.delete(streamId);\n }\n });\n for (const message of messages) {\n if (isJSONRPCRequest(message)) {\n this._requestToStreamMapping.set(message.id, streamId);\n }\n }\n for (const message of messages) {\n this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo });\n }\n });\n }\n // SSE streaming mode - use ReadableStream with controller for more reliable data pushing\n const encoder = new TextEncoder();\n let streamController;\n const readable = new ReadableStream({\n start: controller => {\n streamController = controller;\n },\n cancel: () => {\n // Stream was cancelled by client\n this._streamMapping.delete(streamId);\n }\n });\n const headers = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive'\n };\n // After initialization, always include the session ID if we have one\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n // Store the response for this request to send messages back through this connection\n // We need to track by request ID to maintain the connection\n for (const message of messages) {\n if (isJSONRPCRequest(message)) {\n this._streamMapping.set(streamId, {\n controller: streamController,\n encoder,\n cleanup: () => {\n this._streamMapping.delete(streamId);\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n });\n this._requestToStreamMapping.set(message.id, streamId);\n }\n }\n // Write priming event if event store is configured (after mapping is set up)\n await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion);\n // handle each message\n for (const message of messages) {\n // Build closeSSEStream callback for requests when eventStore is configured\n // AND client supports resumability (protocol version >= 2025-11-25).\n // Old clients can't resume if the stream is closed early because they\n // didn't receive a priming event with an event ID.\n let closeSSEStream;\n let closeStandaloneSSEStream;\n if (isJSONRPCRequest(message) && this._eventStore && clientProtocolVersion >= '2025-11-25') {\n closeSSEStream = () => {\n this.closeSSEStream(message.id);\n };\n closeStandaloneSSEStream = () => {\n this.closeStandaloneSSEStream();\n };\n }\n this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo, closeSSEStream, closeStandaloneSSEStream });\n }\n // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses\n // This will be handled by the send() method when responses are ready\n return new Response(readable, { status: 200, headers });\n }\n catch (error) {\n // return JSON-RPC formatted error\n this.onerror?.(error);\n return this.createJsonErrorResponse(400, -32700, 'Parse error', { data: String(error) });\n }\n }\n /**\n * Handles DELETE requests to terminate sessions\n */\n async handleDeleteRequest(req) {\n const sessionError = this.validateSession(req);\n if (sessionError) {\n return sessionError;\n }\n const protocolError = this.validateProtocolVersion(req);\n if (protocolError) {\n return protocolError;\n }\n await Promise.resolve(this._onsessionclosed?.(this.sessionId));\n await this.close();\n return new Response(null, { status: 200 });\n }\n /**\n * Validates session ID for non-initialization requests.\n * Returns Response error if invalid, undefined otherwise\n */\n validateSession(req) {\n if (this.sessionIdGenerator === undefined) {\n // If the sessionIdGenerator ID is not set, the session management is disabled\n // and we don't need to validate the session ID\n return undefined;\n }\n if (!this._initialized) {\n // If the server has not been initialized yet, reject all requests\n this.onerror?.(new Error('Bad Request: Server not initialized'));\n return this.createJsonErrorResponse(400, -32000, 'Bad Request: Server not initialized');\n }\n const sessionId = req.headers.get('mcp-session-id');\n if (!sessionId) {\n // Non-initialization requests without a session ID should return 400 Bad Request\n this.onerror?.(new Error('Bad Request: Mcp-Session-Id header is required'));\n return this.createJsonErrorResponse(400, -32000, 'Bad Request: Mcp-Session-Id header is required');\n }\n if (sessionId !== this.sessionId) {\n // Reject requests with invalid session ID with 404 Not Found\n this.onerror?.(new Error('Session not found'));\n return this.createJsonErrorResponse(404, -32001, 'Session not found');\n }\n return undefined;\n }\n /**\n * Validates the MCP-Protocol-Version header on incoming requests.\n *\n * For initialization: Version negotiation handles unknown versions gracefully\n * (server responds with its supported version).\n *\n * For subsequent requests with MCP-Protocol-Version header:\n * - Accept if in supported list\n * - 400 if unsupported\n *\n * For HTTP requests without the MCP-Protocol-Version header:\n * - Accept and default to the version negotiated at initialization\n */\n validateProtocolVersion(req) {\n const protocolVersion = req.headers.get('mcp-protocol-version');\n if (protocolVersion !== null && !SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) {\n this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${protocolVersion}` +\n ` (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})`));\n return this.createJsonErrorResponse(400, -32000, `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})`);\n }\n return undefined;\n }\n async close() {\n // Close all SSE connections\n this._streamMapping.forEach(({ cleanup }) => {\n cleanup();\n });\n this._streamMapping.clear();\n // Clear any pending responses\n this._requestResponseMap.clear();\n this.onclose?.();\n }\n /**\n * Close an SSE stream for a specific request, triggering client reconnection.\n * Use this to implement polling behavior during long-running operations -\n * client will reconnect after the retry interval specified in the priming event.\n */\n closeSSEStream(requestId) {\n const streamId = this._requestToStreamMapping.get(requestId);\n if (!streamId)\n return;\n const stream = this._streamMapping.get(streamId);\n if (stream) {\n stream.cleanup();\n }\n }\n /**\n * Close the standalone GET SSE stream, triggering client reconnection.\n * Use this to implement polling behavior for server-initiated notifications.\n */\n closeStandaloneSSEStream() {\n const stream = this._streamMapping.get(this._standaloneSseStreamId);\n if (stream) {\n stream.cleanup();\n }\n }\n async send(message, options) {\n let requestId = options?.relatedRequestId;\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n // If the message is a response, use the request ID from the message\n requestId = message.id;\n }\n // Check if this message should be sent on the standalone SSE stream (no request ID)\n // Ignore notifications from tools (which have relatedRequestId set)\n // Those will be sent via dedicated response SSE streams\n if (requestId === undefined) {\n // For standalone SSE streams, we can only send requests and notifications\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request');\n }\n // Generate and store event ID if event store is provided\n // Store even if stream is disconnected so events can be replayed on reconnect\n let eventId;\n if (this._eventStore) {\n // Stores the event and gets the generated event ID\n eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message);\n }\n const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId);\n if (standaloneSse === undefined) {\n // Stream is disconnected - event is stored for replay, nothing more to do\n return;\n }\n // Send the message to the standalone SSE stream\n if (standaloneSse.controller && standaloneSse.encoder) {\n this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId);\n }\n return;\n }\n // Get the response for this request\n const streamId = this._requestToStreamMapping.get(requestId);\n if (!streamId) {\n throw new Error(`No connection established for request ID: ${String(requestId)}`);\n }\n const stream = this._streamMapping.get(streamId);\n if (!this._enableJsonResponse && stream?.controller && stream?.encoder) {\n // For SSE responses, generate event ID if event store is provided\n let eventId;\n if (this._eventStore) {\n eventId = await this._eventStore.storeEvent(streamId, message);\n }\n // Write the event to the response stream\n this.writeSSEEvent(stream.controller, stream.encoder, message, eventId);\n }\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n this._requestResponseMap.set(requestId, message);\n const relatedIds = Array.from(this._requestToStreamMapping.entries())\n .filter(([_, sid]) => sid === streamId)\n .map(([id]) => id);\n // Check if we have responses for all requests using this connection\n const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id));\n if (allResponsesReady) {\n if (!stream) {\n throw new Error(`No connection established for request ID: ${String(requestId)}`);\n }\n if (this._enableJsonResponse && stream.resolveJson) {\n // All responses ready, send as JSON\n const headers = {\n 'Content-Type': 'application/json'\n };\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n const responses = relatedIds.map(id => this._requestResponseMap.get(id));\n if (responses.length === 1) {\n stream.resolveJson(new Response(JSON.stringify(responses[0]), { status: 200, headers }));\n }\n else {\n stream.resolveJson(new Response(JSON.stringify(responses), { status: 200, headers }));\n }\n }\n else {\n // End the SSE stream\n stream.cleanup();\n }\n // Clean up\n for (const id of relatedIds) {\n this._requestResponseMap.delete(id);\n this._requestToStreamMapping.delete(id);\n }\n }\n }\n }\n}\n//# sourceMappingURL=webStandardStreamableHttp.js.map","/**\n * Node.js HTTP Streamable HTTP Server Transport\n *\n * This is a thin wrapper around `WebStandardStreamableHTTPServerTransport` that provides\n * compatibility with Node.js HTTP server (IncomingMessage/ServerResponse).\n *\n * For web-standard environments (Cloudflare Workers, Deno, Bun), use `WebStandardStreamableHTTPServerTransport` directly.\n */\nimport { getRequestListener } from '@hono/node-server';\nimport { WebStandardStreamableHTTPServerTransport } from './webStandardStreamableHttp.js';\n/**\n * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.\n * It supports both SSE streaming and direct HTTP responses.\n *\n * This is a wrapper around `WebStandardStreamableHTTPServerTransport` that provides Node.js HTTP compatibility.\n * It uses the `@hono/node-server` library to convert between Node.js HTTP and Web Standard APIs.\n *\n * Usage example:\n *\n * ```typescript\n * // Stateful mode - server sets the session ID\n * const statefulTransport = new StreamableHTTPServerTransport({\n * sessionIdGenerator: () => randomUUID(),\n * });\n *\n * // Stateless mode - explicitly set session ID to undefined\n * const statelessTransport = new StreamableHTTPServerTransport({\n * sessionIdGenerator: undefined,\n * });\n *\n * // Using with pre-parsed request body\n * app.post('/mcp', (req, res) => {\n * transport.handleRequest(req, res, req.body);\n * });\n * ```\n *\n * In stateful mode:\n * - Session ID is generated and included in response headers\n * - Session ID is always included in initialization responses\n * - Requests with invalid session IDs are rejected with 404 Not Found\n * - Non-initialization requests without a session ID are rejected with 400 Bad Request\n * - State is maintained in-memory (connections, message history)\n *\n * In stateless mode:\n * - No Session ID is included in any responses\n * - No session validation is performed\n */\nexport class StreamableHTTPServerTransport {\n constructor(options = {}) {\n // Store auth and parsedBody per request for passing through to handleRequest\n this._requestContext = new WeakMap();\n this._webStandardTransport = new WebStandardStreamableHTTPServerTransport(options);\n // Create a request listener that wraps the web standard transport\n // getRequestListener converts Node.js HTTP to Web Standard and properly handles SSE streaming\n // overrideGlobalObjects: false prevents Hono from overwriting global Response, which would\n // break frameworks like Next.js whose response classes extend the native Response\n this._requestListener = getRequestListener(async (webRequest) => {\n // Get context if available (set during handleRequest)\n const context = this._requestContext.get(webRequest);\n return this._webStandardTransport.handleRequest(webRequest, {\n authInfo: context?.authInfo,\n parsedBody: context?.parsedBody\n });\n }, { overrideGlobalObjects: false });\n }\n /**\n * Gets the session ID for this transport instance.\n */\n get sessionId() {\n return this._webStandardTransport.sessionId;\n }\n /**\n * Sets callback for when the transport is closed.\n */\n set onclose(handler) {\n this._webStandardTransport.onclose = handler;\n }\n get onclose() {\n return this._webStandardTransport.onclose;\n }\n /**\n * Sets callback for transport errors.\n */\n set onerror(handler) {\n this._webStandardTransport.onerror = handler;\n }\n get onerror() {\n return this._webStandardTransport.onerror;\n }\n /**\n * Sets callback for incoming messages.\n */\n set onmessage(handler) {\n this._webStandardTransport.onmessage = handler;\n }\n get onmessage() {\n return this._webStandardTransport.onmessage;\n }\n /**\n * Starts the transport. This is required by the Transport interface but is a no-op\n * for the Streamable HTTP transport as connections are managed per-request.\n */\n async start() {\n return this._webStandardTransport.start();\n }\n /**\n * Closes the transport and all active connections.\n */\n async close() {\n return this._webStandardTransport.close();\n }\n /**\n * Sends a JSON-RPC message through the transport.\n */\n async send(message, options) {\n return this._webStandardTransport.send(message, options);\n }\n /**\n * Handles an incoming HTTP request, whether GET or POST.\n *\n * This method converts Node.js HTTP objects to Web Standard Request/Response\n * and delegates to the underlying WebStandardStreamableHTTPServerTransport.\n *\n * @param req - Node.js IncomingMessage, optionally with auth property from middleware\n * @param res - Node.js ServerResponse\n * @param parsedBody - Optional pre-parsed body from body-parser middleware\n */\n async handleRequest(req, res, parsedBody) {\n // Store context for this request to pass through auth and parsedBody\n // We need to intercept the request creation to attach this context\n const authInfo = req.auth;\n // Create a custom handler that includes our context\n // overrideGlobalObjects: false prevents Hono from overwriting global Response, which would\n // break frameworks like Next.js whose response classes extend the native Response\n const handler = getRequestListener(async (webRequest) => {\n return this._webStandardTransport.handleRequest(webRequest, {\n authInfo,\n parsedBody\n });\n }, { overrideGlobalObjects: false });\n // Delegate to the request listener which handles all the Node.js <-> Web Standard conversion\n // including proper SSE streaming support\n await handler(req, res);\n }\n /**\n * Close an SSE stream for a specific request, triggering client reconnection.\n * Use this to implement polling behavior during long-running operations -\n * client will reconnect after the retry interval specified in the priming event.\n */\n closeSSEStream(requestId) {\n this._webStandardTransport.closeSSEStream(requestId);\n }\n /**\n * Close the standalone GET SSE stream, triggering client reconnection.\n * Use this to implement polling behavior for server-initiated notifications.\n */\n closeStandaloneSSEStream() {\n this._webStandardTransport.closeStandaloneSSEStream();\n }\n}\n//# sourceMappingURL=streamableHttp.js.map","/**\n * The wrapper's local HTTP MCP server — real-tool bridging plus the actual enforcement of which\n * bridged tools are callable. Wrapper-only — never imported by `adapter.ts`.\n *\n * @remarks\n * Built on the LOW-LEVEL `Server` class from `@modelcontextprotocol/sdk/server`, never\n * `McpServer.registerTool()` (which requires Zod-shaped schemas — incompatible with ADK's\n * Joi-based tools, already rendered to plain JSON Schema by the adapter before this module ever\n * sees them). The low-level `Server` takes MCP *protocol* schemas (`ListToolsRequestSchema`/\n * `CallToolRequestSchema`), not per-tool argument schemas, so no Zod object is authored anywhere\n * in this file — the only Zod footprint is the two pre-built protocol-schema tokens imported from\n * the SDK itself.\n *\n * `--allowedTools` is kept in the CLI invocation only as a defense-in-depth, human-readable\n * statement of intent (see `wrapper.ts`'s argv construction) — it CANNOT be the real enforcement\n * mechanism, because `--dangerously-skip-permissions` removes the permission engine that an\n * allow-RULE feeds. The real enforcement happens here, twice over: `bridgedTools` arrives from the\n * adapter already pre-filtered to exclude `disallowedTools`, so a disallowed name is never even\n * listed; and the `CallTool` handler independently re-checks the requested name against that same\n * already-filtered list before ever emitting a `tool_call_request` to the adapter.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { createServer as createHttpServer } from 'node:http'\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js'\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'\nimport { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'\nimport type { WrapperBridgedTool } from './wire'\nimport type { Server as HttpServer } from 'node:http'\n\n/** A pending `CallTool` request awaiting a `tool_call_response` from the adapter. */\ninterface PendingCall {\n resolve: (result: { content: Array<Record<string, unknown>>; isError?: boolean }) => void\n}\n\n/** The running bridge: its bound port, and hooks to route calls to/from the adapter side. */\nexport interface McpBridge {\n /** The ephemeral loopback port the bridge is listening on. */\n port: number\n /**\n * Replaces the bridge's advertised tool set. The bridge starts with an EMPTY set at boot (so it\n * can bind its port and let the wrapper emit `ready` before a `run` command — carrying the real\n * tool list — has arrived); `wrapper.ts` calls this once, when `run` arrives, before spawning\n * `claude`.\n */\n setBridgedTools(tools: WrapperBridgedTool[]): void\n /**\n * Called by `wrapper.ts` when a `tool_call_response` command arrives from the adapter, to\n * settle the matching pending `CallTool` request.\n */\n resolveToolCall(\n requestId: string,\n result: { content: Array<Record<string, unknown>>; isError?: boolean }\n ): void\n /**\n * Reject every still-pending `CallTool` request with an `isError: true` result explaining the\n * bridge is shutting down. Must run BEFORE `close()` — an in-flight request is itself an active\n * HTTP connection, so settling it first is what lets `close()` (and the underlying `http.Server`\n * close callback) unblock.\n */\n rejectPending(reason: string): void\n /** Closes the MCP transport — this is what actually tears down any open SSE stream via its own `cleanup()` calls. Must run AFTER `rejectPending()` and BEFORE the HTTP listener is closed. */\n closeTransport(): Promise<void>\n /** Closes the HTTP listener. Callback-based under the hood — promisified here. Must run LAST. */\n closeHttpServer(): Promise<void>\n}\n\n/**\n * Start the bridge: bind an ephemeral loopback HTTP listener, wire a `StreamableHTTPServerTransport`\n * (session-scoped to this one wrapper-lifetime connection — see the `sessionIdGenerator` remark\n * below) to a low-level `Server` constructed with the explicit `tools` capability (required — the\n * SDK throws for `tools/list`/`tools/call` otherwise), and register the two handlers that make the\n * current `bridgedTools` set reachable over MCP.\n *\n * @remarks\n * Starts with an EMPTY tool set — the bridge must bind its port and let the wrapper emit `ready`\n * BEFORE the adapter has sent a `run` command carrying the real tool list (the adapter waits for\n * `ready` before sending `run`, so starting the bridge only after `run` arrives would deadlock\n * both sides). Call {@link McpBridge.setBridgedTools} once `run` arrives, before spawning `claude`.\n *\n * @param onToolCallRequest - Called with `(requestId, toolName, args)` for every `CallTool` the\n * bridge accepts; the caller (`wrapper.ts`) forwards this as a `tool_call_request` `WrapperEvent`\n * to the adapter and eventually calls `resolveToolCall` with the adapter's answer.\n */\nexport const startMcpBridge = async (\n onToolCallRequest: (requestId: string, toolName: string, args: unknown) => void\n): Promise<McpBridge> => {\n const pending = new Map<string, PendingCall>()\n let nextRequestId = 0\n let bridgedTools: WrapperBridgedTool[] = []\n\n const server = new Server({ name: 'adk_bridge', version: '1' }, { capabilities: { tools: {} } })\n\n server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: bridgedTools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n })),\n }))\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const name = request.params.name\n if (!bridgedTools.some((t) => t.name === name)) {\n // Defense-in-depth: this should be unreachable in practice, since `bridgedTools` was\n // already filtered by the adapter before it ever reached this process — but re-check\n // anyway rather than trusting that invariant blindly.\n return {\n content: [{ type: 'text', text: `Tool \"${name}\" is not available in this session.` }],\n isError: true,\n }\n }\n const requestId = String(nextRequestId++)\n const result = await new Promise<{\n content: Array<Record<string, unknown>>\n isError?: boolean\n }>((resolve) => {\n pending.set(requestId, { resolve })\n onToolCallRequest(requestId, name, request.params.arguments)\n })\n return result\n })\n\n // NOT `sessionIdGenerator: undefined` (\"stateless\" mode). Confirmed directly against the\n // installed SDK (@modelcontextprotocol/sdk@1.29.0): `WebStandardStreamableHTTPServerTransport`\n // throws \"Stateless transport cannot be reused across requests. Create a new transport per\n // request.\" on the SECOND request a stateless transport ever handles (source:\n // server/webStandardStreamableHttp.js's `_hasHandledRequest` guard in `handleRequest`) — every\n // `ListTools`/`CallTool` after the very first over the bridge's lifetime would 500. A single\n // wrapper-lifetime session id (scoped to one dispatch iteration, discarded with the process) is\n // what \"stateless across DISPATCHES\" (Decision D) actually requires here, not a stateless\n // transport in the SDK's own sense.\n const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID() })\n\n // Settling a pending call (`resolveToolCall`/`rejectPending`'s `entry.resolve(...)`, below) only\n // unblocks the SDK's OWN internal handler-completion Promise — the actual `transport.send()` call\n // that flushes the JSON-RPC response over the wire happens several microtask turns later, inside\n // the SDK's own `.then(handler).then(send)` chain (`shared/protocol.js`'s `_onrequest`). Confirmed\n // by direct reproduction: calling `closeTransport()` immediately after `rejectPending()` (no gap)\n // silently drops the very response `rejectPending()` just produced — the caller's `CallTool`\n // promise then never settles. Wrapping `send` here to track every in-flight call is what lets\n // `closeTransport()` (below) drain them first, a real fix rather than a fixed-delay guess.\n const inFlightSends = new Set<Promise<unknown>>()\n const originalSend = transport.send.bind(transport)\n transport.send = ((...args: Parameters<typeof originalSend>) => {\n const sent = originalSend(...args)\n inFlightSends.add(sent)\n void sent.finally(() => inFlightSends.delete(sent))\n return sent\n }) as typeof transport.send\n\n await server.connect(transport)\n\n const httpServer: HttpServer = createHttpServer((req, res) => {\n void transport.handleRequest(req, res)\n })\n\n const port = await new Promise<number>((resolve, reject) => {\n httpServer.once('error', reject)\n httpServer.listen(0, '127.0.0.1', () => {\n const address = httpServer.address()\n if (address === null || typeof address === 'string') {\n reject(new Error('MCP bridge HTTP listener did not bind to a port'))\n return\n }\n resolve(address.port)\n })\n })\n\n return {\n port,\n setBridgedTools(tools) {\n bridgedTools = tools\n },\n resolveToolCall(requestId, result) {\n const entry = pending.get(requestId)\n if (!entry) return\n pending.delete(requestId)\n entry.resolve(result)\n },\n rejectPending(reason) {\n for (const [requestId, entry] of pending) {\n pending.delete(requestId)\n entry.resolve({ content: [{ type: 'text', text: reason }], isError: true })\n }\n },\n async closeTransport() {\n // A call `resolveToolCall`/`rejectPending` just settled has NOT yet reached\n // `transport.send()` at the instant those methods return — the SDK's own handler-completion\n // chain needs at least one more event-loop turn to get there (see the `inFlightSends`\n // remark above), so `inFlightSends` can still be empty here even though a send is about to\n // start. Yield one turn first, then drain whatever is actually in flight, repeating briefly\n // in case draining itself lets a further queued send begin — bounded so a genuinely stuck\n // send can't hang shutdown forever.\n await new Promise<void>((resolve) => setImmediate(resolve))\n for (let i = 0; i < 5; i++) {\n const snapshot = Array.from(inFlightSends)\n if (snapshot.length === 0) break\n await Promise.allSettled(snapshot)\n }\n await transport.close()\n },\n async closeHttpServer() {\n await new Promise<void>((resolve, reject) => {\n httpServer.close((err) => (err ? reject(err) : resolve()))\n })\n },\n }\n}\n","/**\n * Claude Code CLI's own stream-json vocabulary types and parser. Wrapper-only — never imported by\n * `adapter.ts`.\n *\n * @remarks\n * No `@nhtio/adk/*` imports (this module runs inside the wrapper process, per Decision A/C — the\n * wrapper is self-contained with respect to the ADK). Parses the `--output-format stream-json`\n * NDJSON lines `claude` emits into a small internal shape `wrapper.ts` then translates into the\n * normalized `WrapperEvent` union from `./wire`.\n *\n * The vocabulary here converges across the official docs and two independent prior-art parsers\n * (`nhtio-agent-delegator`'s `claude_harness.ts`, `giveon-claude-max-api-proxy`'s `manager.ts`):\n * `system` (init/api_retry subtypes), `assistant`/`user` (with `parent_tool_use_id` distinguishing\n * main-conversation from subagent text), `stream_event` (partial message deltas), and a terminal\n * `result` (success/error).\n */\n\n/** A `system` event — either the one-time init handshake or a mid-turn retry notice. */\nexport interface ClaudeSystemInitLine {\n type: 'system'\n subtype: 'init'\n model?: string\n tools?: string[]\n mcp_servers?: Array<{ name: string; status?: string }>\n [key: string]: unknown\n}\n\nexport interface ClaudeSystemApiRetryLine {\n type: 'system'\n subtype: 'api_retry'\n attempt?: number\n max_retries?: number\n retry_delay_ms?: number\n error_status?: number\n error?: string\n [key: string]: unknown\n}\n\n/** An `assistant`/`user` message line. `parent_tool_use_id` distinguishes subagent from main-conversation text. */\nexport interface ClaudeMessageLine {\n type: 'assistant' | 'user'\n parent_tool_use_id?: string | null\n message?: {\n id?: string\n content?: Array<{ type: string; text?: string; [key: string]: unknown }>\n [key: string]: unknown\n }\n [key: string]: unknown\n}\n\n/** A `stream_event` line — a partial message delta under `--include-partial-messages`. */\nexport interface ClaudeStreamEventLine {\n type: 'stream_event'\n event?: {\n type?: string\n delta?: { type?: string; text?: string; [key: string]: unknown }\n [key: string]: unknown\n }\n parent_tool_use_id?: string | null\n [key: string]: unknown\n}\n\n/** The terminal `result` line — always exactly one per turn, success or error. */\nexport interface ClaudeResultLine {\n type: 'result'\n subtype?: string\n is_error?: boolean\n result?: string\n session_id?: string\n total_cost_usd?: number\n usage?: Record<string, unknown>\n stop_reason?: string\n [key: string]: unknown\n}\n\nexport type ClaudeStreamJsonLine =\n | ClaudeSystemInitLine\n | ClaudeSystemApiRetryLine\n | ClaudeMessageLine\n | ClaudeStreamEventLine\n | ClaudeResultLine\n\n/**\n * Parse one already-newline-split `claude --output-format stream-json` line. Returns `undefined`\n * for anything that fails to parse as JSON or does not match a recognized `type` — the caller\n * (`wrapper.ts`) treats an `undefined` result as a non-fatal `log` event at `trace`, never throws.\n */\nexport const parseClaudeStreamJsonLine = (raw: string): ClaudeStreamJsonLine | undefined => {\n const trimmed = raw.trim()\n if (trimmed.length === 0) return undefined\n let value: unknown\n try {\n value = JSON.parse(trimmed)\n } catch {\n return undefined\n }\n if (value === null || typeof value !== 'object') return undefined\n const obj = value as Record<string, unknown>\n const type = obj.type\n if (type === 'system' && obj.subtype === 'init') return obj as unknown as ClaudeSystemInitLine\n if (type === 'system' && obj.subtype === 'api_retry')\n return obj as unknown as ClaudeSystemApiRetryLine\n if (type === 'assistant' || type === 'user') return obj as unknown as ClaudeMessageLine\n if (type === 'stream_event') return obj as unknown as ClaudeStreamEventLine\n if (type === 'result') return obj as unknown as ClaudeResultLine\n return undefined\n}\n\n/**\n * Extract the plain-text delta from a `stream_event` line's content-block delta, or `undefined`\n * if this particular stream_event carries no text delta (e.g. a tool-call-argument delta, which\n * this battery does not surface as message text).\n */\nexport const extractStreamEventTextDelta = (line: ClaudeStreamEventLine): string | undefined => {\n const delta = line.event?.delta\n if (!delta) return undefined\n if (delta.type === 'text_delta' && typeof delta.text === 'string') return delta.text\n return undefined\n}\n\n/** Extract the concatenated plain text from a complete (non-streamed) assistant/user message line. */\nexport const extractMessageText = (line: ClaudeMessageLine): string => {\n const blocks = line.message?.content\n if (!Array.isArray(blocks)) return ''\n return blocks\n .filter((b) => b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text as string)\n .join('')\n}\n","#!/usr/bin/env node\n/**\n * Standalone Node entry point that owns all Claude-Code-specific complexity: spawning the real\n * `claude` binary, hosting the MCP bridge, and translating its stream-json into the normalized\n * adapter↔wrapper protocol.\n *\n * @remarks\n * Self-contained with respect to `@nhtio/adk/*` — no such imports anywhere in this file or its\n * three siblings (`wire.ts`, `cli_protocol.ts`, `mcp_bridge.ts`). Only `node:*` builtins,\n * `@modelcontextprotocol/sdk`, and those three battery-local modules. Ships as a sibling dist\n * asset (see Decision C in the design notes) — never imported as a library, only ever spawned by\n * file path via `execa(process.execPath, [wrapperPath])` from `adapter.ts`.\n *\n * Carries no `@module` JSDoc tag: it is invisible to the `@module`-tag scraper that builds the\n * public `exports` map, and is added to `vite.config.mts`'s `build.lib.entry` as an explicit extra\n * key instead, following the `mcp/server.ts` precedent for a non-consumer-facing standalone\n * executable.\n */\n\nimport { spawn } from 'node:child_process'\nimport { startMcpBridge } from './mcp_bridge'\nimport { createNdjsonLineReader, encodeWrapperEvent } from './wire'\nimport {\n parseClaudeStreamJsonLine,\n extractStreamEventTextDelta,\n extractMessageText,\n} from './cli_protocol'\nimport type { McpBridge } from './mcp_bridge'\nimport type { ChildProcess } from 'node:child_process'\nimport type { WrapperCommand, WrapperRunCommand, WrapperEvent, ClaudeCodeCliExtraArg } from './wire'\n\n// ─── stdout writer (every emit is an awaited, flush-confirmed write) ───────────\n\nconst writeEvent = (event: WrapperEvent): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n process.stdout.write(encodeWrapperEvent(event), (err) => (err ? reject(err) : resolve()))\n })\n\nconst log = (\n level: 'trace' | 'debug' | 'info' | 'warn' | 'error',\n kind: string,\n message: string,\n payload?: unknown\n): void => {\n void writeEvent({ type: 'log', level, kind, message, payload }).catch(() => {})\n}\n\n// ─── stdin command reader ───────────────────────────────────────────────────\n\nlet stdinDataListener: ((chunk: Uint8Array) => void) | undefined\nlet stdinEndListener: (() => void) | undefined\n\n/** Stop the stdin command reader and detach its listeners — called on every exit path. */\nconst stopStdinReader = (): void => {\n if (stdinDataListener) process.stdin.off('data', stdinDataListener)\n if (stdinEndListener) process.stdin.off('end', stdinEndListener)\n stdinDataListener = undefined\n stdinEndListener = undefined\n try {\n process.stdin.pause()\n } catch {\n /* stdin may already be gone */\n }\n}\n\n// ─── argv construction (Decision F0) ───────────────────────────────────────\n\n/** Validate one `extraArgs` entry has already been checked by the adapter; convert it to argv tokens. */\nconst extraArgToArgv = (entry: ClaudeCodeCliExtraArg): string[] => {\n if (entry.value === undefined) return [entry.flag]\n if (Array.isArray(entry.value)) return [entry.flag, ...entry.value]\n return [entry.flag, entry.value]\n}\n\n/** Build the complete, authoritative argv for the `claude` grandchild. */\nconst buildClaudeArgv = (cmd: WrapperRunCommand, bridgeUrl: string): string[] => {\n const args: string[] = [\n '--bare',\n '-p',\n '--verbose',\n '--output-format',\n 'stream-json',\n '--include-partial-messages',\n '--no-session-persistence',\n '--tools',\n '',\n '--strict-mcp-config',\n '--mcp-config',\n JSON.stringify({ mcpServers: { adk_bridge: { type: 'http', url: bridgeUrl } } }),\n '--dangerously-skip-permissions',\n ]\n // --allowedTools: OMITTED ENTIRELY when there are no bridged tools — the flag is variadic, and a\n // bare `--allowedTools` with nothing after it swallows the very next argv token (confirmed by\n // direct reproduction against the live CLI during design).\n if (cmd.allowedTools.length > 0) {\n args.push(\n '--allowedTools',\n cmd.allowedTools.map((name) => `mcp__adk_bridge__${name}`).join(',')\n )\n }\n if (cmd.appendSystemPrompt !== undefined) {\n args.push('--append-system-prompt', cmd.appendSystemPrompt)\n }\n if (cmd.model !== undefined) {\n args.push('--model', cmd.model)\n }\n if (cmd.addDir !== undefined && cmd.addDir.length > 0) {\n args.push('--add-dir', ...cmd.addDir)\n }\n if (cmd.maxBudgetUsd !== undefined) {\n args.push('--max-budget-usd', String(cmd.maxBudgetUsd))\n }\n // Fixed single-turn dispatch contract: the harness owns iteration boundaries.\n args.push('--max-turns', '1')\n if (cmd.fallbackModel !== undefined && cmd.fallbackModel.length > 0) {\n // ONE comma-joined value, never separate argv tokens — confirmed by direct reproduction: the\n // flag is singular (`--fallback-model <model>`) and documented as accepting \"a comma-separated\n // list to try each in order.\"\n args.push('--fallback-model', cmd.fallbackModel.join(','))\n }\n if (cmd.forwardSubagentText === true) {\n args.push('--forward-subagent-text')\n }\n for (const entry of cmd.extraArgs ?? []) {\n args.push(...extraArgToArgv(entry))\n }\n args.push('--', cmd.prompt)\n return args\n}\n\n/** Build the grandchild's env: start from the ambient env, then explicitly delete-then-set every credential/behavior variable this command controls. */\nconst buildClaudeEnv = (cmd: WrapperRunCommand): Record<string, string | undefined> => {\n const env: Record<string, string | undefined> = { ...process.env }\n delete env.ANTHROPIC_API_KEY\n delete env.ANTHROPIC_AUTH_TOKEN\n delete env.ANTHROPIC_BASE_URL\n delete env.DISABLE_TELEMETRY\n delete env.DISABLE_ERROR_REPORTING\n delete env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC\n delete env.CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT\n if (cmd.auth?.apiKey !== undefined) env.ANTHROPIC_API_KEY = cmd.auth.apiKey\n if (cmd.auth?.authToken !== undefined) env.ANTHROPIC_AUTH_TOKEN = cmd.auth.authToken\n if (cmd.auth?.baseUrl !== undefined) env.ANTHROPIC_BASE_URL = cmd.auth.baseUrl\n if (cmd.disableTelemetry === true) env.DISABLE_TELEMETRY = '1'\n if (cmd.disableErrorReporting === true) env.DISABLE_ERROR_REPORTING = '1'\n if (cmd.disableNonessentialTraffic === true) env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = '1'\n if (cmd.mcpToolIdleTimeoutMs !== undefined) {\n env.CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT = String(cmd.mcpToolIdleTimeoutMs)\n }\n return env\n}\n\n// ─── main ───────────────────────────────────────────────────────────────────\n\nconst main = async (): Promise<void> => {\n let bridge: McpBridge | undefined\n let grandchild: ChildProcess | undefined\n let shuttingDown = false\n let sawResult = false\n\n /** Kill the grandchild's entire detached process group. POSIX only (enforced by the adapter's own options validation before this wrapper is ever spawned). */\n const killGrandchildGroup = (signal: NodeJS.Signals): void => {\n if (!grandchild || grandchild.pid === undefined || grandchild.exitCode !== null) return\n try {\n process.kill(-grandchild.pid, signal)\n } catch {\n /* the group may already be gone */\n }\n }\n\n /** Await the grandchild's actual exit for a bounded period; fall through to a process-group kill if it hasn't exited in time. */\n const waitForGrandchildExit = async (graceMs: number): Promise<void> => {\n if (!grandchild || grandchild.exitCode !== null || grandchild.signalCode !== null) return\n const exited = await new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => resolve(false), graceMs)\n grandchild?.once('exit', () => {\n clearTimeout(timer)\n resolve(true)\n })\n })\n if (!exited) {\n killGrandchildGroup('SIGTERM')\n }\n }\n\n /**\n * The corrected shutdown sequence (Decision D step 5), shared by the normal-completion path and\n * the SIGTERM/SIGINT handler. Order matters: reject pending calls, THEN close the transport\n * (which tears down any open SSE stream), THEN close the HTTP listener (now genuinely\n * unblocked), THEN bound-wait/kill the grandchild, THEN flush `shutdown_complete`, THEN stop the\n * stdin reader.\n */\n const runShutdownSequence = async (disposeGraceMs: number): Promise<void> => {\n bridge?.rejectPending('The Claude Code CLI wrapper is shutting down.')\n if (bridge) await bridge.closeTransport()\n if (bridge) await bridge.closeHttpServer()\n await waitForGrandchildExit(disposeGraceMs)\n await writeEvent({ type: 'shutdown_complete' }).catch(() => {})\n stopStdinReader()\n }\n\n // A 5-second backstop, entirely separate from the normal-completion path: if the graceful\n // sequence above hangs, this fires, force-kills the grandchild's process group unconditionally,\n // and calls process.exit(1) — the ONE and ONLY process.exit() call on the normal-completion path.\n let backstopTimer: ReturnType<typeof setTimeout> | undefined\n const armBackstop = (): void => {\n backstopTimer = setTimeout(() => {\n killGrandchildGroup('SIGKILL')\n process.exitCode = 1\n process.exit(1)\n }, 5_000)\n }\n const disarmBackstop = (): void => {\n if (backstopTimer) clearTimeout(backstopTimer)\n backstopTimer = undefined\n }\n\n const shutdownNormally = async (disposeGraceMs: number): Promise<void> => {\n if (shuttingDown) return\n shuttingDown = true\n armBackstop()\n await runShutdownSequence(disposeGraceMs)\n disarmBackstop()\n process.exitCode = 0\n // Natural return — never process.exit() on this path, so a stdout write in flight is never\n // truncated by an immediate process termination.\n }\n\n // Idempotent SIGTERM/SIGINT handling. Registering a handler REPLACES Node's default\n // terminate-on-signal behavior, so — unlike the normal-completion path — this path explicitly\n // calls process.exit() itself once the shutdown sequence completes.\n let handlingSignal = false\n const onSignal = (): void => {\n if (handlingSignal) return\n handlingSignal = true\n void runShutdownSequence(2_000)\n .then(() => process.exit(0))\n .catch(() => process.exit(1))\n }\n process.on('SIGTERM', onSignal)\n process.on('SIGINT', onSignal)\n // Final, synchronous, best-effort safety net — cannot await anything per Node's own `exit` event\n // contract, so it is not the primary cleanup mechanism for any path above.\n process.on('exit', () => {\n killGrandchildGroup('SIGTERM')\n })\n\n let runCommand: WrapperRunCommand | undefined\n\n const handleCommand = (command: WrapperCommand): void => {\n if (command.type === 'run') {\n if (runCommand !== undefined) {\n log('error', 'duplicate-run-command', 'A run command was already accepted; ignoring.')\n return\n }\n runCommand = command\n void startTurn(command)\n return\n }\n if (command.type === 'tool_call_response') {\n bridge?.resolveToolCall(command.requestId, command.results)\n return\n }\n if (command.type === 'shutdown') {\n void shutdownNormally(runCommand ? 2_000 : 0)\n return\n }\n }\n\n const commandReader = createNdjsonLineReader<WrapperCommand>((raw) => {\n let command: WrapperCommand\n try {\n command = JSON.parse(raw) as WrapperCommand\n } catch {\n log('trace', 'malformed-command', 'Failed to parse inbound command line; skipping.', {\n linePreview: raw.slice(0, 256),\n })\n return undefined\n }\n handleCommand(command)\n return command\n })\n stdinDataListener = (chunk) => commandReader.push(chunk)\n stdinEndListener = () => commandReader.end()\n process.stdin.on('data', stdinDataListener)\n process.stdin.on('end', stdinEndListener)\n\n // The bridge starts and binds its port IMMEDIATELY at wrapper boot, with an empty tool set —\n // NOT inside `startTurn`. The adapter waits for `ready` before ever sending `run` (which is what\n // carries the real tool list), so starting the bridge only after `run` arrives would deadlock\n // both sides: the adapter waiting for `ready`, the wrapper waiting for `run`. `run`'s own\n // handling (`startTurn`, below) calls `bridge.setBridgedTools(...)` once the real list is known,\n // before spawning `claude`.\n try {\n bridge = await startMcpBridge((requestId, toolName, args) => {\n void writeEvent({ type: 'tool_call_request', requestId, tool: toolName, args })\n })\n } catch (err) {\n await writeEvent({\n type: 'error',\n message: 'Failed to start the MCP bridge.',\n // eslint-disable-next-line adk/prefer-is-error -- self-contained wrt @nhtio/adk/* (Decision A)\n detail: err instanceof Error ? err.message : String(err),\n }).catch(() => {})\n process.exitCode = 1\n return\n }\n\n await writeEvent({ type: 'ready' })\n\n const startTurn = async (command: WrapperRunCommand): Promise<void> => {\n if (!bridge) return\n bridge.setBridgedTools(command.bridgedTools)\n\n const bridgeUrl = `http://127.0.0.1:${bridge.port}/`\n const argv = buildClaudeArgv(command, bridgeUrl)\n const env = buildClaudeEnv(command)\n\n grandchild = spawn(command.claudeBin, argv, {\n cwd: command.cwd,\n env,\n detached: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n\n let partialMessageId: string | undefined\n\n const dispatchReader = createNdjsonLineReader((raw) => {\n const line = parseClaudeStreamJsonLine(raw)\n if (line === undefined) {\n log(\n 'trace',\n 'malformed-stream-json',\n 'Failed to parse Claude stream-json line; skipping.',\n {\n linePreview: raw.slice(0, 256),\n }\n )\n return undefined\n }\n void handleClaudeLine(line)\n return line\n })\n grandchild.stdout?.on('data', (chunk: Uint8Array) => {\n dispatchReader.push(chunk)\n })\n\n const handleClaudeLine = async (\n line: ReturnType<typeof parseClaudeStreamJsonLine>\n ): Promise<void> => {\n if (line === undefined) return\n if (line.type === 'system' && line.subtype === 'init') {\n const mcpServerErrors = Array.isArray(line.mcp_servers)\n ? line.mcp_servers\n .filter((s) => s.status === 'failed' && s.name === 'adk_bridge')\n .map((s) => s.name)\n : []\n await writeEvent({\n type: 'init',\n model: line.model,\n tools: line.tools,\n mcpServerErrors: mcpServerErrors.length > 0 ? mcpServerErrors : undefined,\n raw: line,\n })\n return\n }\n if (line.type === 'system' && line.subtype === 'api_retry') {\n await writeEvent({\n type: 'retry',\n attempt: line.attempt ?? 0,\n maxRetries: line.max_retries,\n retryDelayMs: line.retry_delay_ms,\n errorStatus: line.error_status,\n error: line.error,\n })\n return\n }\n if (line.type === 'stream_event') {\n if (line.parent_tool_use_id && command.forwardSubagentText !== true) return\n const delta = extractStreamEventTextDelta(line)\n if (delta !== undefined) {\n const id = partialMessageId ?? 'message'\n partialMessageId = id\n await writeEvent({ type: 'message_delta', id, delta })\n }\n return\n }\n if (line.type === 'assistant' || line.type === 'user') {\n if (line.parent_tool_use_id && command.forwardSubagentText !== true) return\n const text = extractMessageText(line)\n if (text.length > 0) {\n const id = partialMessageId ?? 'message'\n // If no prior stream_event deltas arrived for this id, the complete message carries the\n // ONLY copy of the text — send it as the delta itself, not an empty seal, or the\n // adapter's per-id accumulator (which treats the first call's deltaText as the full\n // content) would create an empty message despite real text having arrived.\n const delta = partialMessageId === undefined ? text : ''\n await writeEvent({ type: 'message_delta', id, delta, isComplete: true })\n partialMessageId = id\n }\n return\n }\n if (line.type === 'result') {\n sawResult = true\n await writeEvent({\n type: 'result',\n resultText: line.result,\n sessionId: line.session_id,\n totalCostUsd: line.total_cost_usd,\n usage: line.usage,\n isError: line.is_error === true,\n subtype: line.subtype,\n stopReason: line.stop_reason,\n raw: line,\n })\n await shutdownNormally(2_000)\n }\n }\n\n grandchild.on('error', (err) => {\n void writeEvent({\n type: 'error',\n message: 'The claude grandchild process failed to spawn.',\n detail: err.message,\n }).catch(() => {})\n })\n grandchild.on('exit', (code, signal) => {\n if (sawResult || shuttingDown) return\n void writeEvent({\n type: 'error',\n message: `claude exited (code=${String(code)}, signal=${String(signal)}) with no terminal result observed.`,\n }).catch(() => {})\n })\n }\n}\n\nmain().catch((error: unknown) => {\n // eslint-disable-next-line adk/prefer-is-error -- self-contained wrt @nhtio/adk/* (Decision A)\n const message = error instanceof Error ? error.message : String(error)\n process.stderr.write(`claude_code_cli wrapper fatal: ${message}\\n`)\n process.exitCode = 1\n})\n"],"x_google_ignoreList":[0,1,2],"mappings":";;;;;;;;;;;AASA,IAAI,eAAe,cAAc,MAAM;CACrC,YAAY,SAAS,SAAS;EAC5B,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AAC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AAW;AACrB,CAAC"}
1
+ {"version":3,"file":"claude-code-cli-wrapper.mjs","names":["#body","#init","crypto","Http2ServerRequest2","h2constants"],"sources":["../node_modules/.pnpm/@hono+node-server@1.19.14_hono@4.12.23/node_modules/@hono/node-server/dist/index.mjs","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/webStandardStreamableHttp.js","../node_modules/.pnpm/@modelcontextprotocol+sdk@1.29.0_zod@4.4.3/node_modules/@modelcontextprotocol/sdk/dist/esm/server/streamableHttp.js","../src/batteries/llm/claude_code_cli/mcp_bridge.ts","../src/batteries/llm/claude_code_cli/line_queue.ts","../src/batteries/llm/claude_code_cli/message_id_state.ts","../src/batteries/llm/claude_code_cli/cli_protocol.ts","../src/batteries/llm/claude_code_cli/wrapper.ts"],"sourcesContent":["// src/server.ts\nimport { createServer as createServerHTTP } from \"http\";\n\n// src/listener.ts\nimport { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from \"http2\";\n\n// src/request.ts\nimport { Http2ServerRequest } from \"http2\";\nimport { Readable } from \"stream\";\nvar RequestError = class extends Error {\n constructor(message, options) {\n super(message, options);\n this.name = \"RequestError\";\n }\n};\nvar toRequestError = (e) => {\n if (e instanceof RequestError) {\n return e;\n }\n return new RequestError(e.message, { cause: e });\n};\nvar GlobalRequest = global.Request;\nvar Request = class extends GlobalRequest {\n constructor(input, options) {\n if (typeof input === \"object\" && getRequestCache in input) {\n input = input[getRequestCache]();\n }\n if (typeof options?.body?.getReader !== \"undefined\") {\n ;\n options.duplex ??= \"half\";\n }\n super(input, options);\n }\n};\nvar newHeadersFromIncoming = (incoming) => {\n const headerRecord = [];\n const rawHeaders = incoming.rawHeaders;\n for (let i = 0; i < rawHeaders.length; i += 2) {\n const { [i]: key, [i + 1]: value } = rawHeaders;\n if (key.charCodeAt(0) !== /*:*/\n 58) {\n headerRecord.push([key, value]);\n }\n }\n return new Headers(headerRecord);\n};\nvar wrapBodyStream = Symbol(\"wrapBodyStream\");\nvar newRequestFromIncoming = (method, url, headers, incoming, abortController) => {\n const init = {\n method,\n headers,\n signal: abortController.signal\n };\n if (method === \"TRACE\") {\n init.method = \"GET\";\n const req = new Request(url, init);\n Object.defineProperty(req, \"method\", {\n get() {\n return \"TRACE\";\n }\n });\n return req;\n }\n if (!(method === \"GET\" || method === \"HEAD\")) {\n if (\"rawBody\" in incoming && incoming.rawBody instanceof Buffer) {\n init.body = new ReadableStream({\n start(controller) {\n controller.enqueue(incoming.rawBody);\n controller.close();\n }\n });\n } else if (incoming[wrapBodyStream]) {\n let reader;\n init.body = new ReadableStream({\n async pull(controller) {\n try {\n reader ||= Readable.toWeb(incoming).getReader();\n const { done, value } = await reader.read();\n if (done) {\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n controller.error(error);\n }\n }\n });\n } else {\n init.body = Readable.toWeb(incoming);\n }\n }\n return new Request(url, init);\n};\nvar getRequestCache = Symbol(\"getRequestCache\");\nvar requestCache = Symbol(\"requestCache\");\nvar incomingKey = Symbol(\"incomingKey\");\nvar urlKey = Symbol(\"urlKey\");\nvar headersKey = Symbol(\"headersKey\");\nvar abortControllerKey = Symbol(\"abortControllerKey\");\nvar getAbortController = Symbol(\"getAbortController\");\nvar requestPrototype = {\n get method() {\n return this[incomingKey].method || \"GET\";\n },\n get url() {\n return this[urlKey];\n },\n get headers() {\n return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);\n },\n [getAbortController]() {\n this[getRequestCache]();\n return this[abortControllerKey];\n },\n [getRequestCache]() {\n this[abortControllerKey] ||= new AbortController();\n return this[requestCache] ||= newRequestFromIncoming(\n this.method,\n this[urlKey],\n this.headers,\n this[incomingKey],\n this[abortControllerKey]\n );\n }\n};\n[\n \"body\",\n \"bodyUsed\",\n \"cache\",\n \"credentials\",\n \"destination\",\n \"integrity\",\n \"mode\",\n \"redirect\",\n \"referrer\",\n \"referrerPolicy\",\n \"signal\",\n \"keepalive\"\n].forEach((k) => {\n Object.defineProperty(requestPrototype, k, {\n get() {\n return this[getRequestCache]()[k];\n }\n });\n});\n[\"arrayBuffer\", \"blob\", \"clone\", \"formData\", \"json\", \"text\"].forEach((k) => {\n Object.defineProperty(requestPrototype, k, {\n value: function() {\n return this[getRequestCache]()[k]();\n }\n });\n});\nObject.defineProperty(requestPrototype, Symbol.for(\"nodejs.util.inspect.custom\"), {\n value: function(depth, options, inspectFn) {\n const props = {\n method: this.method,\n url: this.url,\n headers: this.headers,\n nativeRequest: this[requestCache]\n };\n return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;\n }\n});\nObject.setPrototypeOf(requestPrototype, Request.prototype);\nvar newRequest = (incoming, defaultHostname) => {\n const req = Object.create(requestPrototype);\n req[incomingKey] = incoming;\n const incomingUrl = incoming.url || \"\";\n if (incomingUrl[0] !== \"/\" && // short-circuit for performance. most requests are relative URL.\n (incomingUrl.startsWith(\"http://\") || incomingUrl.startsWith(\"https://\"))) {\n if (incoming instanceof Http2ServerRequest) {\n throw new RequestError(\"Absolute URL for :path is not allowed in HTTP/2\");\n }\n try {\n const url2 = new URL(incomingUrl);\n req[urlKey] = url2.href;\n } catch (e) {\n throw new RequestError(\"Invalid absolute URL\", { cause: e });\n }\n return req;\n }\n const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;\n if (!host) {\n throw new RequestError(\"Missing host header\");\n }\n let scheme;\n if (incoming instanceof Http2ServerRequest) {\n scheme = incoming.scheme;\n if (!(scheme === \"http\" || scheme === \"https\")) {\n throw new RequestError(\"Unsupported scheme\");\n }\n } else {\n scheme = incoming.socket && incoming.socket.encrypted ? \"https\" : \"http\";\n }\n const url = new URL(`${scheme}://${host}${incomingUrl}`);\n if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\\d+$/, \"\")) {\n throw new RequestError(\"Invalid host header\");\n }\n req[urlKey] = url.href;\n return req;\n};\n\n// src/response.ts\nvar responseCache = Symbol(\"responseCache\");\nvar getResponseCache = Symbol(\"getResponseCache\");\nvar cacheKey = Symbol(\"cache\");\nvar GlobalResponse = global.Response;\nvar Response2 = class _Response {\n #body;\n #init;\n [getResponseCache]() {\n delete this[cacheKey];\n return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);\n }\n constructor(body, init) {\n let headers;\n this.#body = body;\n if (init instanceof _Response) {\n const cachedGlobalResponse = init[responseCache];\n if (cachedGlobalResponse) {\n this.#init = cachedGlobalResponse;\n this[getResponseCache]();\n return;\n } else {\n this.#init = init.#init;\n headers = new Headers(init.#init.headers);\n }\n } else {\n this.#init = init;\n }\n if (typeof body === \"string\" || typeof body?.getReader !== \"undefined\" || body instanceof Blob || body instanceof Uint8Array) {\n ;\n this[cacheKey] = [init?.status || 200, body, headers || init?.headers];\n }\n }\n get headers() {\n const cache = this[cacheKey];\n if (cache) {\n if (!(cache[2] instanceof Headers)) {\n cache[2] = new Headers(\n cache[2] || { \"content-type\": \"text/plain; charset=UTF-8\" }\n );\n }\n return cache[2];\n }\n return this[getResponseCache]().headers;\n }\n get status() {\n return this[cacheKey]?.[0] ?? this[getResponseCache]().status;\n }\n get ok() {\n const status = this.status;\n return status >= 200 && status < 300;\n }\n};\n[\"body\", \"bodyUsed\", \"redirected\", \"statusText\", \"trailers\", \"type\", \"url\"].forEach((k) => {\n Object.defineProperty(Response2.prototype, k, {\n get() {\n return this[getResponseCache]()[k];\n }\n });\n});\n[\"arrayBuffer\", \"blob\", \"clone\", \"formData\", \"json\", \"text\"].forEach((k) => {\n Object.defineProperty(Response2.prototype, k, {\n value: function() {\n return this[getResponseCache]()[k]();\n }\n });\n});\nObject.defineProperty(Response2.prototype, Symbol.for(\"nodejs.util.inspect.custom\"), {\n value: function(depth, options, inspectFn) {\n const props = {\n status: this.status,\n headers: this.headers,\n ok: this.ok,\n nativeResponse: this[responseCache]\n };\n return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;\n }\n});\nObject.setPrototypeOf(Response2, GlobalResponse);\nObject.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);\n\n// src/utils.ts\nasync function readWithoutBlocking(readPromise) {\n return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);\n}\nfunction writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {\n const cancel = (error) => {\n reader.cancel(error).catch(() => {\n });\n };\n writable.on(\"close\", cancel);\n writable.on(\"error\", cancel);\n (currentReadPromise ?? reader.read()).then(flow, handleStreamError);\n return reader.closed.finally(() => {\n writable.off(\"close\", cancel);\n writable.off(\"error\", cancel);\n });\n function handleStreamError(error) {\n if (error) {\n writable.destroy(error);\n }\n }\n function onDrain() {\n reader.read().then(flow, handleStreamError);\n }\n function flow({ done, value }) {\n try {\n if (done) {\n writable.end();\n } else if (!writable.write(value)) {\n writable.once(\"drain\", onDrain);\n } else {\n return reader.read().then(flow, handleStreamError);\n }\n } catch (e) {\n handleStreamError(e);\n }\n }\n}\nfunction writeFromReadableStream(stream, writable) {\n if (stream.locked) {\n throw new TypeError(\"ReadableStream is locked.\");\n } else if (writable.destroyed) {\n return;\n }\n return writeFromReadableStreamDefaultReader(stream.getReader(), writable);\n}\nvar buildOutgoingHttpHeaders = (headers) => {\n const res = {};\n if (!(headers instanceof Headers)) {\n headers = new Headers(headers ?? void 0);\n }\n const cookies = [];\n for (const [k, v] of headers) {\n if (k === \"set-cookie\") {\n cookies.push(v);\n } else {\n res[k] = v;\n }\n }\n if (cookies.length > 0) {\n res[\"set-cookie\"] = cookies;\n }\n res[\"content-type\"] ??= \"text/plain; charset=UTF-8\";\n return res;\n};\n\n// src/utils/response/constants.ts\nvar X_ALREADY_SENT = \"x-hono-already-sent\";\n\n// src/globals.ts\nimport crypto from \"crypto\";\nif (typeof global.crypto === \"undefined\") {\n global.crypto = crypto;\n}\n\n// src/listener.ts\nvar outgoingEnded = Symbol(\"outgoingEnded\");\nvar incomingDraining = Symbol(\"incomingDraining\");\nvar DRAIN_TIMEOUT_MS = 500;\nvar MAX_DRAIN_BYTES = 64 * 1024 * 1024;\nvar drainIncoming = (incoming) => {\n const incomingWithDrainState = incoming;\n if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {\n return;\n }\n incomingWithDrainState[incomingDraining] = true;\n if (incoming instanceof Http2ServerRequest2) {\n try {\n ;\n incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);\n } catch {\n }\n return;\n }\n let bytesRead = 0;\n const cleanup = () => {\n clearTimeout(timer);\n incoming.off(\"data\", onData);\n incoming.off(\"end\", cleanup);\n incoming.off(\"error\", cleanup);\n };\n const forceClose = () => {\n cleanup();\n const socket = incoming.socket;\n if (socket && !socket.destroyed) {\n socket.destroySoon();\n }\n };\n const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);\n timer.unref?.();\n const onData = (chunk) => {\n bytesRead += chunk.length;\n if (bytesRead > MAX_DRAIN_BYTES) {\n forceClose();\n }\n };\n incoming.on(\"data\", onData);\n incoming.on(\"end\", cleanup);\n incoming.on(\"error\", cleanup);\n incoming.resume();\n};\nvar handleRequestError = () => new Response(null, {\n status: 400\n});\nvar handleFetchError = (e) => new Response(null, {\n status: e instanceof Error && (e.name === \"TimeoutError\" || e.constructor.name === \"TimeoutError\") ? 504 : 500\n});\nvar handleResponseError = (e, outgoing) => {\n const err = e instanceof Error ? e : new Error(\"unknown error\", { cause: e });\n if (err.code === \"ERR_STREAM_PREMATURE_CLOSE\") {\n console.info(\"The user aborted a request.\");\n } else {\n console.error(e);\n if (!outgoing.headersSent) {\n outgoing.writeHead(500, { \"Content-Type\": \"text/plain\" });\n }\n outgoing.end(`Error: ${err.message}`);\n outgoing.destroy(err);\n }\n};\nvar flushHeaders = (outgoing) => {\n if (\"flushHeaders\" in outgoing && outgoing.writable) {\n outgoing.flushHeaders();\n }\n};\nvar responseViaCache = async (res, outgoing) => {\n let [status, body, header] = res[cacheKey];\n let hasContentLength = false;\n if (!header) {\n header = { \"content-type\": \"text/plain; charset=UTF-8\" };\n } else if (header instanceof Headers) {\n hasContentLength = header.has(\"content-length\");\n header = buildOutgoingHttpHeaders(header);\n } else if (Array.isArray(header)) {\n const headerObj = new Headers(header);\n hasContentLength = headerObj.has(\"content-length\");\n header = buildOutgoingHttpHeaders(headerObj);\n } else {\n for (const key in header) {\n if (key.length === 14 && key.toLowerCase() === \"content-length\") {\n hasContentLength = true;\n break;\n }\n }\n }\n if (!hasContentLength) {\n if (typeof body === \"string\") {\n header[\"Content-Length\"] = Buffer.byteLength(body);\n } else if (body instanceof Uint8Array) {\n header[\"Content-Length\"] = body.byteLength;\n } else if (body instanceof Blob) {\n header[\"Content-Length\"] = body.size;\n }\n }\n outgoing.writeHead(status, header);\n if (typeof body === \"string\" || body instanceof Uint8Array) {\n outgoing.end(body);\n } else if (body instanceof Blob) {\n outgoing.end(new Uint8Array(await body.arrayBuffer()));\n } else {\n flushHeaders(outgoing);\n await writeFromReadableStream(body, outgoing)?.catch(\n (e) => handleResponseError(e, outgoing)\n );\n }\n ;\n outgoing[outgoingEnded]?.();\n};\nvar isPromise = (res) => typeof res.then === \"function\";\nvar responseViaResponseObject = async (res, outgoing, options = {}) => {\n if (isPromise(res)) {\n if (options.errorHandler) {\n try {\n res = await res;\n } catch (err) {\n const errRes = await options.errorHandler(err);\n if (!errRes) {\n return;\n }\n res = errRes;\n }\n } else {\n res = await res.catch(handleFetchError);\n }\n }\n if (cacheKey in res) {\n return responseViaCache(res, outgoing);\n }\n const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);\n if (res.body) {\n const reader = res.body.getReader();\n const values = [];\n let done = false;\n let currentReadPromise = void 0;\n if (resHeaderRecord[\"transfer-encoding\"] !== \"chunked\") {\n let maxReadCount = 2;\n for (let i = 0; i < maxReadCount; i++) {\n currentReadPromise ||= reader.read();\n const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {\n console.error(e);\n done = true;\n });\n if (!chunk) {\n if (i === 1) {\n await new Promise((resolve) => setTimeout(resolve));\n maxReadCount = 3;\n continue;\n }\n break;\n }\n currentReadPromise = void 0;\n if (chunk.value) {\n values.push(chunk.value);\n }\n if (chunk.done) {\n done = true;\n break;\n }\n }\n if (done && !(\"content-length\" in resHeaderRecord)) {\n resHeaderRecord[\"content-length\"] = values.reduce((acc, value) => acc + value.length, 0);\n }\n }\n outgoing.writeHead(res.status, resHeaderRecord);\n values.forEach((value) => {\n ;\n outgoing.write(value);\n });\n if (done) {\n outgoing.end();\n } else {\n if (values.length === 0) {\n flushHeaders(outgoing);\n }\n await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);\n }\n } else if (resHeaderRecord[X_ALREADY_SENT]) {\n } else {\n outgoing.writeHead(res.status, resHeaderRecord);\n outgoing.end();\n }\n ;\n outgoing[outgoingEnded]?.();\n};\nvar getRequestListener = (fetchCallback, options = {}) => {\n const autoCleanupIncoming = options.autoCleanupIncoming ?? true;\n if (options.overrideGlobalObjects !== false && global.Request !== Request) {\n Object.defineProperty(global, \"Request\", {\n value: Request\n });\n Object.defineProperty(global, \"Response\", {\n value: Response2\n });\n }\n return async (incoming, outgoing) => {\n let res, req;\n try {\n req = newRequest(incoming, options.hostname);\n let incomingEnded = !autoCleanupIncoming || incoming.method === \"GET\" || incoming.method === \"HEAD\";\n if (!incomingEnded) {\n ;\n incoming[wrapBodyStream] = true;\n incoming.on(\"end\", () => {\n incomingEnded = true;\n });\n if (incoming instanceof Http2ServerRequest2) {\n ;\n outgoing[outgoingEnded] = () => {\n if (!incomingEnded) {\n setTimeout(() => {\n if (!incomingEnded) {\n setTimeout(() => {\n drainIncoming(incoming);\n });\n }\n });\n }\n };\n }\n outgoing.on(\"finish\", () => {\n if (!incomingEnded) {\n drainIncoming(incoming);\n }\n });\n }\n outgoing.on(\"close\", () => {\n const abortController = req[abortControllerKey];\n if (abortController) {\n if (incoming.errored) {\n req[abortControllerKey].abort(incoming.errored.toString());\n } else if (!outgoing.writableFinished) {\n req[abortControllerKey].abort(\"Client connection prematurely closed.\");\n }\n }\n if (!incomingEnded) {\n setTimeout(() => {\n if (!incomingEnded) {\n setTimeout(() => {\n drainIncoming(incoming);\n });\n }\n });\n }\n });\n res = fetchCallback(req, { incoming, outgoing });\n if (cacheKey in res) {\n return responseViaCache(res, outgoing);\n }\n } catch (e) {\n if (!res) {\n if (options.errorHandler) {\n res = await options.errorHandler(req ? e : toRequestError(e));\n if (!res) {\n return;\n }\n } else if (!req) {\n res = handleRequestError();\n } else {\n res = handleFetchError(e);\n }\n } else {\n return handleResponseError(e, outgoing);\n }\n }\n try {\n return await responseViaResponseObject(res, outgoing, options);\n } catch (e) {\n return handleResponseError(e, outgoing);\n }\n };\n};\n\n// src/server.ts\nvar createAdaptorServer = (options) => {\n const fetchCallback = options.fetch;\n const requestListener = getRequestListener(fetchCallback, {\n hostname: options.hostname,\n overrideGlobalObjects: options.overrideGlobalObjects,\n autoCleanupIncoming: options.autoCleanupIncoming\n });\n const createServer = options.createServer || createServerHTTP;\n const server = createServer(options.serverOptions || {}, requestListener);\n return server;\n};\nvar serve = (options, listeningListener) => {\n const server = createAdaptorServer(options);\n server.listen(options?.port ?? 3e3, options.hostname, () => {\n const serverInfo = server.address();\n listeningListener && listeningListener(serverInfo);\n });\n return server;\n};\nexport {\n RequestError,\n createAdaptorServer,\n getRequestListener,\n serve\n};\n","/**\n * Web Standards Streamable HTTP Server Transport\n *\n * This is the core transport implementation using Web Standard APIs (Request, Response, ReadableStream).\n * It can run on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc.\n *\n * For Node.js Express/HTTP compatibility, use `StreamableHTTPServerTransport` which wraps this transport.\n */\nimport { isInitializeRequest, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, JSONRPCMessageSchema, SUPPORTED_PROTOCOL_VERSIONS, DEFAULT_NEGOTIATED_PROTOCOL_VERSION } from '../types.js';\n/**\n * Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification\n * using Web Standard APIs (Request, Response, ReadableStream).\n *\n * This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc.\n *\n * Usage example:\n *\n * ```typescript\n * // Stateful mode - server sets the session ID\n * const statefulTransport = new WebStandardStreamableHTTPServerTransport({\n * sessionIdGenerator: () => crypto.randomUUID(),\n * });\n *\n * // Stateless mode - explicitly set session ID to undefined\n * const statelessTransport = new WebStandardStreamableHTTPServerTransport({\n * sessionIdGenerator: undefined,\n * });\n *\n * // Hono.js usage\n * app.all('/mcp', async (c) => {\n * return transport.handleRequest(c.req.raw);\n * });\n *\n * // Cloudflare Workers usage\n * export default {\n * async fetch(request: Request): Promise<Response> {\n * return transport.handleRequest(request);\n * }\n * };\n * ```\n *\n * In stateful mode:\n * - Session ID is generated and included in response headers\n * - Session ID is always included in initialization responses\n * - Requests with invalid session IDs are rejected with 404 Not Found\n * - Non-initialization requests without a session ID are rejected with 400 Bad Request\n * - State is maintained in-memory (connections, message history)\n *\n * In stateless mode:\n * - No Session ID is included in any responses\n * - No session validation is performed\n */\nexport class WebStandardStreamableHTTPServerTransport {\n constructor(options = {}) {\n this._started = false;\n this._hasHandledRequest = false;\n this._streamMapping = new Map();\n this._requestToStreamMapping = new Map();\n this._requestResponseMap = new Map();\n this._initialized = false;\n this._enableJsonResponse = false;\n this._standaloneSseStreamId = '_GET_stream';\n this.sessionIdGenerator = options.sessionIdGenerator;\n this._enableJsonResponse = options.enableJsonResponse ?? false;\n this._eventStore = options.eventStore;\n this._onsessioninitialized = options.onsessioninitialized;\n this._onsessionclosed = options.onsessionclosed;\n this._allowedHosts = options.allowedHosts;\n this._allowedOrigins = options.allowedOrigins;\n this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false;\n this._retryInterval = options.retryInterval;\n }\n /**\n * Starts the transport. This is required by the Transport interface but is a no-op\n * for the Streamable HTTP transport as connections are managed per-request.\n */\n async start() {\n if (this._started) {\n throw new Error('Transport already started');\n }\n this._started = true;\n }\n /**\n * Helper to create a JSON error response\n */\n createJsonErrorResponse(status, code, message, options) {\n const error = { code, message };\n if (options?.data !== undefined) {\n error.data = options.data;\n }\n return new Response(JSON.stringify({\n jsonrpc: '2.0',\n error,\n id: null\n }), {\n status,\n headers: {\n 'Content-Type': 'application/json',\n ...options?.headers\n }\n });\n }\n /**\n * Validates request headers for DNS rebinding protection.\n * @returns Error response if validation fails, undefined if validation passes.\n */\n validateRequestHeaders(req) {\n // Skip validation if protection is not enabled\n if (!this._enableDnsRebindingProtection) {\n return undefined;\n }\n // Validate Host header if allowedHosts is configured\n if (this._allowedHosts && this._allowedHosts.length > 0) {\n const hostHeader = req.headers.get('host');\n if (!hostHeader || !this._allowedHosts.includes(hostHeader)) {\n const error = `Invalid Host header: ${hostHeader}`;\n this.onerror?.(new Error(error));\n return this.createJsonErrorResponse(403, -32000, error);\n }\n }\n // Validate Origin header if allowedOrigins is configured\n if (this._allowedOrigins && this._allowedOrigins.length > 0) {\n const originHeader = req.headers.get('origin');\n if (originHeader && !this._allowedOrigins.includes(originHeader)) {\n const error = `Invalid Origin header: ${originHeader}`;\n this.onerror?.(new Error(error));\n return this.createJsonErrorResponse(403, -32000, error);\n }\n }\n return undefined;\n }\n /**\n * Handles an incoming HTTP request, whether GET, POST, or DELETE\n * Returns a Response object (Web Standard)\n */\n async handleRequest(req, options) {\n // In stateless mode (no sessionIdGenerator), each request must use a fresh transport.\n // Reusing a stateless transport causes message ID collisions between clients.\n if (!this.sessionIdGenerator && this._hasHandledRequest) {\n throw new Error('Stateless transport cannot be reused across requests. Create a new transport per request.');\n }\n this._hasHandledRequest = true;\n // Validate request headers for DNS rebinding protection\n const validationError = this.validateRequestHeaders(req);\n if (validationError) {\n return validationError;\n }\n switch (req.method) {\n case 'POST':\n return this.handlePostRequest(req, options);\n case 'GET':\n return this.handleGetRequest(req);\n case 'DELETE':\n return this.handleDeleteRequest(req);\n default:\n return this.handleUnsupportedRequest();\n }\n }\n /**\n * Writes a priming event to establish resumption capability.\n * Only sends if eventStore is configured (opt-in for resumability) and\n * the client's protocol version supports empty SSE data (>= 2025-11-25).\n */\n async writePrimingEvent(controller, encoder, streamId, protocolVersion) {\n if (!this._eventStore) {\n return;\n }\n // Priming events have empty data which older clients cannot handle.\n // Only send priming events to clients with protocol version >= 2025-11-25\n // which includes the fix for handling empty SSE data.\n if (protocolVersion < '2025-11-25') {\n return;\n }\n const primingEventId = await this._eventStore.storeEvent(streamId, {});\n let primingEvent = `id: ${primingEventId}\\ndata: \\n\\n`;\n if (this._retryInterval !== undefined) {\n primingEvent = `id: ${primingEventId}\\nretry: ${this._retryInterval}\\ndata: \\n\\n`;\n }\n controller.enqueue(encoder.encode(primingEvent));\n }\n /**\n * Handles GET requests for SSE stream\n */\n async handleGetRequest(req) {\n // The client MUST include an Accept header, listing text/event-stream as a supported content type.\n const acceptHeader = req.headers.get('accept');\n if (!acceptHeader?.includes('text/event-stream')) {\n this.onerror?.(new Error('Not Acceptable: Client must accept text/event-stream'));\n return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept text/event-stream');\n }\n // If an Mcp-Session-Id is returned by the server during initialization,\n // clients using the Streamable HTTP transport MUST include it\n // in the Mcp-Session-Id header on all of their subsequent HTTP requests.\n const sessionError = this.validateSession(req);\n if (sessionError) {\n return sessionError;\n }\n const protocolError = this.validateProtocolVersion(req);\n if (protocolError) {\n return protocolError;\n }\n // Handle resumability: check for Last-Event-ID header\n if (this._eventStore) {\n const lastEventId = req.headers.get('last-event-id');\n if (lastEventId) {\n return this.replayEvents(lastEventId);\n }\n }\n // Check if there's already an active standalone SSE stream for this session\n if (this._streamMapping.get(this._standaloneSseStreamId) !== undefined) {\n // Only one GET SSE stream is allowed per session\n this.onerror?.(new Error('Conflict: Only one SSE stream is allowed per session'));\n return this.createJsonErrorResponse(409, -32000, 'Conflict: Only one SSE stream is allowed per session');\n }\n const encoder = new TextEncoder();\n let streamController;\n // Create a ReadableStream with a controller we can use to push SSE events\n const readable = new ReadableStream({\n start: controller => {\n streamController = controller;\n },\n cancel: () => {\n // Stream was cancelled by client\n this._streamMapping.delete(this._standaloneSseStreamId);\n }\n });\n const headers = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive'\n };\n // After initialization, always include the session ID if we have one\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n // Store the stream mapping with the controller for pushing data\n this._streamMapping.set(this._standaloneSseStreamId, {\n controller: streamController,\n encoder,\n cleanup: () => {\n this._streamMapping.delete(this._standaloneSseStreamId);\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n });\n return new Response(readable, { headers });\n }\n /**\n * Replays events that would have been sent after the specified event ID\n * Only used when resumability is enabled\n */\n async replayEvents(lastEventId) {\n if (!this._eventStore) {\n this.onerror?.(new Error('Event store not configured'));\n return this.createJsonErrorResponse(400, -32000, 'Event store not configured');\n }\n try {\n // If getStreamIdForEventId is available, use it for conflict checking\n let streamId;\n if (this._eventStore.getStreamIdForEventId) {\n streamId = await this._eventStore.getStreamIdForEventId(lastEventId);\n if (!streamId) {\n this.onerror?.(new Error('Invalid event ID format'));\n return this.createJsonErrorResponse(400, -32000, 'Invalid event ID format');\n }\n // Check conflict with the SAME streamId we'll use for mapping\n if (this._streamMapping.get(streamId) !== undefined) {\n this.onerror?.(new Error('Conflict: Stream already has an active connection'));\n return this.createJsonErrorResponse(409, -32000, 'Conflict: Stream already has an active connection');\n }\n }\n const headers = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive'\n };\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n // Create a ReadableStream with controller for SSE\n const encoder = new TextEncoder();\n let streamController;\n const readable = new ReadableStream({\n start: controller => {\n streamController = controller;\n },\n cancel: () => {\n // Stream was cancelled by client\n // Cleanup will be handled by the mapping\n }\n });\n // Replay events - returns the streamId for backwards compatibility\n const replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, {\n send: async (eventId, message) => {\n const success = this.writeSSEEvent(streamController, encoder, message, eventId);\n if (!success) {\n this.onerror?.(new Error('Failed replay events'));\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n }\n });\n this._streamMapping.set(replayedStreamId, {\n controller: streamController,\n encoder,\n cleanup: () => {\n this._streamMapping.delete(replayedStreamId);\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n });\n return new Response(readable, { headers });\n }\n catch (error) {\n this.onerror?.(error);\n return this.createJsonErrorResponse(500, -32000, 'Error replaying events');\n }\n }\n /**\n * Writes an event to an SSE stream via controller with proper formatting\n */\n writeSSEEvent(controller, encoder, message, eventId) {\n try {\n let eventData = `event: message\\n`;\n // Include event ID if provided - this is important for resumability\n if (eventId) {\n eventData += `id: ${eventId}\\n`;\n }\n eventData += `data: ${JSON.stringify(message)}\\n\\n`;\n controller.enqueue(encoder.encode(eventData));\n return true;\n }\n catch (error) {\n this.onerror?.(error);\n return false;\n }\n }\n /**\n * Handles unsupported requests (PUT, PATCH, etc.)\n */\n handleUnsupportedRequest() {\n this.onerror?.(new Error('Method not allowed.'));\n return new Response(JSON.stringify({\n jsonrpc: '2.0',\n error: {\n code: -32000,\n message: 'Method not allowed.'\n },\n id: null\n }), {\n status: 405,\n headers: {\n Allow: 'GET, POST, DELETE',\n 'Content-Type': 'application/json'\n }\n });\n }\n /**\n * Handles POST requests containing JSON-RPC messages\n */\n async handlePostRequest(req, options) {\n try {\n // Validate the Accept header\n const acceptHeader = req.headers.get('accept');\n // The client MUST include an Accept header, listing both application/json and text/event-stream as supported content types.\n if (!acceptHeader?.includes('application/json') || !acceptHeader.includes('text/event-stream')) {\n this.onerror?.(new Error('Not Acceptable: Client must accept both application/json and text/event-stream'));\n return this.createJsonErrorResponse(406, -32000, 'Not Acceptable: Client must accept both application/json and text/event-stream');\n }\n const ct = req.headers.get('content-type');\n if (!ct || !ct.includes('application/json')) {\n this.onerror?.(new Error('Unsupported Media Type: Content-Type must be application/json'));\n return this.createJsonErrorResponse(415, -32000, 'Unsupported Media Type: Content-Type must be application/json');\n }\n // Build request info from headers and URL\n const requestInfo = {\n headers: Object.fromEntries(req.headers.entries()),\n url: new URL(req.url)\n };\n let rawMessage;\n if (options?.parsedBody !== undefined) {\n rawMessage = options.parsedBody;\n }\n else {\n try {\n rawMessage = await req.json();\n }\n catch {\n this.onerror?.(new Error('Parse error: Invalid JSON'));\n return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON');\n }\n }\n let messages;\n // handle batch and single messages\n try {\n if (Array.isArray(rawMessage)) {\n messages = rawMessage.map(msg => JSONRPCMessageSchema.parse(msg));\n }\n else {\n messages = [JSONRPCMessageSchema.parse(rawMessage)];\n }\n }\n catch {\n this.onerror?.(new Error('Parse error: Invalid JSON-RPC message'));\n return this.createJsonErrorResponse(400, -32700, 'Parse error: Invalid JSON-RPC message');\n }\n // Check if this is an initialization request\n // https://spec.modelcontextprotocol.io/specification/2025-03-26/basic/lifecycle/\n const isInitializationRequest = messages.some(isInitializeRequest);\n if (isInitializationRequest) {\n // If it's a server with session management and the session ID is already set we should reject the request\n // to avoid re-initialization.\n if (this._initialized && this.sessionId !== undefined) {\n this.onerror?.(new Error('Invalid Request: Server already initialized'));\n return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Server already initialized');\n }\n if (messages.length > 1) {\n this.onerror?.(new Error('Invalid Request: Only one initialization request is allowed'));\n return this.createJsonErrorResponse(400, -32600, 'Invalid Request: Only one initialization request is allowed');\n }\n this.sessionId = this.sessionIdGenerator?.();\n this._initialized = true;\n // If we have a session ID and an onsessioninitialized handler, call it immediately\n // This is needed in cases where the server needs to keep track of multiple sessions\n if (this.sessionId && this._onsessioninitialized) {\n await Promise.resolve(this._onsessioninitialized(this.sessionId));\n }\n }\n if (!isInitializationRequest) {\n // If an Mcp-Session-Id is returned by the server during initialization,\n // clients using the Streamable HTTP transport MUST include it\n // in the Mcp-Session-Id header on all of their subsequent HTTP requests.\n const sessionError = this.validateSession(req);\n if (sessionError) {\n return sessionError;\n }\n // Mcp-Protocol-Version header is required for all requests after initialization.\n const protocolError = this.validateProtocolVersion(req);\n if (protocolError) {\n return protocolError;\n }\n }\n // check if it contains requests\n const hasRequests = messages.some(isJSONRPCRequest);\n if (!hasRequests) {\n // if it only contains notifications or responses, return 202\n for (const message of messages) {\n this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo });\n }\n return new Response(null, { status: 202 });\n }\n // The default behavior is to use SSE streaming\n // but in some cases server will return JSON responses\n const streamId = crypto.randomUUID();\n // Extract protocol version for priming event decision.\n // For initialize requests, get from request params.\n // For other requests, get from header (already validated).\n const initRequest = messages.find(m => isInitializeRequest(m));\n const clientProtocolVersion = initRequest\n ? initRequest.params.protocolVersion\n : (req.headers.get('mcp-protocol-version') ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION);\n if (this._enableJsonResponse) {\n // For JSON response mode, return a Promise that resolves when all responses are ready\n return new Promise(resolve => {\n this._streamMapping.set(streamId, {\n resolveJson: resolve,\n cleanup: () => {\n this._streamMapping.delete(streamId);\n }\n });\n for (const message of messages) {\n if (isJSONRPCRequest(message)) {\n this._requestToStreamMapping.set(message.id, streamId);\n }\n }\n for (const message of messages) {\n this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo });\n }\n });\n }\n // SSE streaming mode - use ReadableStream with controller for more reliable data pushing\n const encoder = new TextEncoder();\n let streamController;\n const readable = new ReadableStream({\n start: controller => {\n streamController = controller;\n },\n cancel: () => {\n // Stream was cancelled by client\n this._streamMapping.delete(streamId);\n }\n });\n const headers = {\n 'Content-Type': 'text/event-stream',\n 'Cache-Control': 'no-cache',\n Connection: 'keep-alive'\n };\n // After initialization, always include the session ID if we have one\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n // Store the response for this request to send messages back through this connection\n // We need to track by request ID to maintain the connection\n for (const message of messages) {\n if (isJSONRPCRequest(message)) {\n this._streamMapping.set(streamId, {\n controller: streamController,\n encoder,\n cleanup: () => {\n this._streamMapping.delete(streamId);\n try {\n streamController.close();\n }\n catch {\n // Controller might already be closed\n }\n }\n });\n this._requestToStreamMapping.set(message.id, streamId);\n }\n }\n // Write priming event if event store is configured (after mapping is set up)\n await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion);\n // handle each message\n for (const message of messages) {\n // Build closeSSEStream callback for requests when eventStore is configured\n // AND client supports resumability (protocol version >= 2025-11-25).\n // Old clients can't resume if the stream is closed early because they\n // didn't receive a priming event with an event ID.\n let closeSSEStream;\n let closeStandaloneSSEStream;\n if (isJSONRPCRequest(message) && this._eventStore && clientProtocolVersion >= '2025-11-25') {\n closeSSEStream = () => {\n this.closeSSEStream(message.id);\n };\n closeStandaloneSSEStream = () => {\n this.closeStandaloneSSEStream();\n };\n }\n this.onmessage?.(message, { authInfo: options?.authInfo, requestInfo, closeSSEStream, closeStandaloneSSEStream });\n }\n // The server SHOULD NOT close the SSE stream before sending all JSON-RPC responses\n // This will be handled by the send() method when responses are ready\n return new Response(readable, { status: 200, headers });\n }\n catch (error) {\n // return JSON-RPC formatted error\n this.onerror?.(error);\n return this.createJsonErrorResponse(400, -32700, 'Parse error', { data: String(error) });\n }\n }\n /**\n * Handles DELETE requests to terminate sessions\n */\n async handleDeleteRequest(req) {\n const sessionError = this.validateSession(req);\n if (sessionError) {\n return sessionError;\n }\n const protocolError = this.validateProtocolVersion(req);\n if (protocolError) {\n return protocolError;\n }\n await Promise.resolve(this._onsessionclosed?.(this.sessionId));\n await this.close();\n return new Response(null, { status: 200 });\n }\n /**\n * Validates session ID for non-initialization requests.\n * Returns Response error if invalid, undefined otherwise\n */\n validateSession(req) {\n if (this.sessionIdGenerator === undefined) {\n // If the sessionIdGenerator ID is not set, the session management is disabled\n // and we don't need to validate the session ID\n return undefined;\n }\n if (!this._initialized) {\n // If the server has not been initialized yet, reject all requests\n this.onerror?.(new Error('Bad Request: Server not initialized'));\n return this.createJsonErrorResponse(400, -32000, 'Bad Request: Server not initialized');\n }\n const sessionId = req.headers.get('mcp-session-id');\n if (!sessionId) {\n // Non-initialization requests without a session ID should return 400 Bad Request\n this.onerror?.(new Error('Bad Request: Mcp-Session-Id header is required'));\n return this.createJsonErrorResponse(400, -32000, 'Bad Request: Mcp-Session-Id header is required');\n }\n if (sessionId !== this.sessionId) {\n // Reject requests with invalid session ID with 404 Not Found\n this.onerror?.(new Error('Session not found'));\n return this.createJsonErrorResponse(404, -32001, 'Session not found');\n }\n return undefined;\n }\n /**\n * Validates the MCP-Protocol-Version header on incoming requests.\n *\n * For initialization: Version negotiation handles unknown versions gracefully\n * (server responds with its supported version).\n *\n * For subsequent requests with MCP-Protocol-Version header:\n * - Accept if in supported list\n * - 400 if unsupported\n *\n * For HTTP requests without the MCP-Protocol-Version header:\n * - Accept and default to the version negotiated at initialization\n */\n validateProtocolVersion(req) {\n const protocolVersion = req.headers.get('mcp-protocol-version');\n if (protocolVersion !== null && !SUPPORTED_PROTOCOL_VERSIONS.includes(protocolVersion)) {\n this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${protocolVersion}` +\n ` (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})`));\n return this.createJsonErrorResponse(400, -32000, `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${SUPPORTED_PROTOCOL_VERSIONS.join(', ')})`);\n }\n return undefined;\n }\n async close() {\n // Close all SSE connections\n this._streamMapping.forEach(({ cleanup }) => {\n cleanup();\n });\n this._streamMapping.clear();\n // Clear any pending responses\n this._requestResponseMap.clear();\n this.onclose?.();\n }\n /**\n * Close an SSE stream for a specific request, triggering client reconnection.\n * Use this to implement polling behavior during long-running operations -\n * client will reconnect after the retry interval specified in the priming event.\n */\n closeSSEStream(requestId) {\n const streamId = this._requestToStreamMapping.get(requestId);\n if (!streamId)\n return;\n const stream = this._streamMapping.get(streamId);\n if (stream) {\n stream.cleanup();\n }\n }\n /**\n * Close the standalone GET SSE stream, triggering client reconnection.\n * Use this to implement polling behavior for server-initiated notifications.\n */\n closeStandaloneSSEStream() {\n const stream = this._streamMapping.get(this._standaloneSseStreamId);\n if (stream) {\n stream.cleanup();\n }\n }\n async send(message, options) {\n let requestId = options?.relatedRequestId;\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n // If the message is a response, use the request ID from the message\n requestId = message.id;\n }\n // Check if this message should be sent on the standalone SSE stream (no request ID)\n // Ignore notifications from tools (which have relatedRequestId set)\n // Those will be sent via dedicated response SSE streams\n if (requestId === undefined) {\n // For standalone SSE streams, we can only send requests and notifications\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n throw new Error('Cannot send a response on a standalone SSE stream unless resuming a previous client request');\n }\n // Generate and store event ID if event store is provided\n // Store even if stream is disconnected so events can be replayed on reconnect\n let eventId;\n if (this._eventStore) {\n // Stores the event and gets the generated event ID\n eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message);\n }\n const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId);\n if (standaloneSse === undefined) {\n // Stream is disconnected - event is stored for replay, nothing more to do\n return;\n }\n // Send the message to the standalone SSE stream\n if (standaloneSse.controller && standaloneSse.encoder) {\n this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId);\n }\n return;\n }\n // Get the response for this request\n const streamId = this._requestToStreamMapping.get(requestId);\n if (!streamId) {\n throw new Error(`No connection established for request ID: ${String(requestId)}`);\n }\n const stream = this._streamMapping.get(streamId);\n if (!this._enableJsonResponse && stream?.controller && stream?.encoder) {\n // For SSE responses, generate event ID if event store is provided\n let eventId;\n if (this._eventStore) {\n eventId = await this._eventStore.storeEvent(streamId, message);\n }\n // Write the event to the response stream\n this.writeSSEEvent(stream.controller, stream.encoder, message, eventId);\n }\n if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {\n this._requestResponseMap.set(requestId, message);\n const relatedIds = Array.from(this._requestToStreamMapping.entries())\n .filter(([_, sid]) => sid === streamId)\n .map(([id]) => id);\n // Check if we have responses for all requests using this connection\n const allResponsesReady = relatedIds.every(id => this._requestResponseMap.has(id));\n if (allResponsesReady) {\n if (!stream) {\n throw new Error(`No connection established for request ID: ${String(requestId)}`);\n }\n if (this._enableJsonResponse && stream.resolveJson) {\n // All responses ready, send as JSON\n const headers = {\n 'Content-Type': 'application/json'\n };\n if (this.sessionId !== undefined) {\n headers['mcp-session-id'] = this.sessionId;\n }\n const responses = relatedIds.map(id => this._requestResponseMap.get(id));\n if (responses.length === 1) {\n stream.resolveJson(new Response(JSON.stringify(responses[0]), { status: 200, headers }));\n }\n else {\n stream.resolveJson(new Response(JSON.stringify(responses), { status: 200, headers }));\n }\n }\n else {\n // End the SSE stream\n stream.cleanup();\n }\n // Clean up\n for (const id of relatedIds) {\n this._requestResponseMap.delete(id);\n this._requestToStreamMapping.delete(id);\n }\n }\n }\n }\n}\n//# sourceMappingURL=webStandardStreamableHttp.js.map","/**\n * Node.js HTTP Streamable HTTP Server Transport\n *\n * This is a thin wrapper around `WebStandardStreamableHTTPServerTransport` that provides\n * compatibility with Node.js HTTP server (IncomingMessage/ServerResponse).\n *\n * For web-standard environments (Cloudflare Workers, Deno, Bun), use `WebStandardStreamableHTTPServerTransport` directly.\n */\nimport { getRequestListener } from '@hono/node-server';\nimport { WebStandardStreamableHTTPServerTransport } from './webStandardStreamableHttp.js';\n/**\n * Server transport for Streamable HTTP: this implements the MCP Streamable HTTP transport specification.\n * It supports both SSE streaming and direct HTTP responses.\n *\n * This is a wrapper around `WebStandardStreamableHTTPServerTransport` that provides Node.js HTTP compatibility.\n * It uses the `@hono/node-server` library to convert between Node.js HTTP and Web Standard APIs.\n *\n * Usage example:\n *\n * ```typescript\n * // Stateful mode - server sets the session ID\n * const statefulTransport = new StreamableHTTPServerTransport({\n * sessionIdGenerator: () => randomUUID(),\n * });\n *\n * // Stateless mode - explicitly set session ID to undefined\n * const statelessTransport = new StreamableHTTPServerTransport({\n * sessionIdGenerator: undefined,\n * });\n *\n * // Using with pre-parsed request body\n * app.post('/mcp', (req, res) => {\n * transport.handleRequest(req, res, req.body);\n * });\n * ```\n *\n * In stateful mode:\n * - Session ID is generated and included in response headers\n * - Session ID is always included in initialization responses\n * - Requests with invalid session IDs are rejected with 404 Not Found\n * - Non-initialization requests without a session ID are rejected with 400 Bad Request\n * - State is maintained in-memory (connections, message history)\n *\n * In stateless mode:\n * - No Session ID is included in any responses\n * - No session validation is performed\n */\nexport class StreamableHTTPServerTransport {\n constructor(options = {}) {\n // Store auth and parsedBody per request for passing through to handleRequest\n this._requestContext = new WeakMap();\n this._webStandardTransport = new WebStandardStreamableHTTPServerTransport(options);\n // Create a request listener that wraps the web standard transport\n // getRequestListener converts Node.js HTTP to Web Standard and properly handles SSE streaming\n // overrideGlobalObjects: false prevents Hono from overwriting global Response, which would\n // break frameworks like Next.js whose response classes extend the native Response\n this._requestListener = getRequestListener(async (webRequest) => {\n // Get context if available (set during handleRequest)\n const context = this._requestContext.get(webRequest);\n return this._webStandardTransport.handleRequest(webRequest, {\n authInfo: context?.authInfo,\n parsedBody: context?.parsedBody\n });\n }, { overrideGlobalObjects: false });\n }\n /**\n * Gets the session ID for this transport instance.\n */\n get sessionId() {\n return this._webStandardTransport.sessionId;\n }\n /**\n * Sets callback for when the transport is closed.\n */\n set onclose(handler) {\n this._webStandardTransport.onclose = handler;\n }\n get onclose() {\n return this._webStandardTransport.onclose;\n }\n /**\n * Sets callback for transport errors.\n */\n set onerror(handler) {\n this._webStandardTransport.onerror = handler;\n }\n get onerror() {\n return this._webStandardTransport.onerror;\n }\n /**\n * Sets callback for incoming messages.\n */\n set onmessage(handler) {\n this._webStandardTransport.onmessage = handler;\n }\n get onmessage() {\n return this._webStandardTransport.onmessage;\n }\n /**\n * Starts the transport. This is required by the Transport interface but is a no-op\n * for the Streamable HTTP transport as connections are managed per-request.\n */\n async start() {\n return this._webStandardTransport.start();\n }\n /**\n * Closes the transport and all active connections.\n */\n async close() {\n return this._webStandardTransport.close();\n }\n /**\n * Sends a JSON-RPC message through the transport.\n */\n async send(message, options) {\n return this._webStandardTransport.send(message, options);\n }\n /**\n * Handles an incoming HTTP request, whether GET or POST.\n *\n * This method converts Node.js HTTP objects to Web Standard Request/Response\n * and delegates to the underlying WebStandardStreamableHTTPServerTransport.\n *\n * @param req - Node.js IncomingMessage, optionally with auth property from middleware\n * @param res - Node.js ServerResponse\n * @param parsedBody - Optional pre-parsed body from body-parser middleware\n */\n async handleRequest(req, res, parsedBody) {\n // Store context for this request to pass through auth and parsedBody\n // We need to intercept the request creation to attach this context\n const authInfo = req.auth;\n // Create a custom handler that includes our context\n // overrideGlobalObjects: false prevents Hono from overwriting global Response, which would\n // break frameworks like Next.js whose response classes extend the native Response\n const handler = getRequestListener(async (webRequest) => {\n return this._webStandardTransport.handleRequest(webRequest, {\n authInfo,\n parsedBody\n });\n }, { overrideGlobalObjects: false });\n // Delegate to the request listener which handles all the Node.js <-> Web Standard conversion\n // including proper SSE streaming support\n await handler(req, res);\n }\n /**\n * Close an SSE stream for a specific request, triggering client reconnection.\n * Use this to implement polling behavior during long-running operations -\n * client will reconnect after the retry interval specified in the priming event.\n */\n closeSSEStream(requestId) {\n this._webStandardTransport.closeSSEStream(requestId);\n }\n /**\n * Close the standalone GET SSE stream, triggering client reconnection.\n * Use this to implement polling behavior for server-initiated notifications.\n */\n closeStandaloneSSEStream() {\n this._webStandardTransport.closeStandaloneSSEStream();\n }\n}\n//# sourceMappingURL=streamableHttp.js.map","/**\n * The wrapper's local HTTP MCP server — real-tool bridging plus the actual enforcement of which\n * bridged tools are callable. Wrapper-only — never imported by `adapter.ts`.\n *\n * @remarks\n * Built on the LOW-LEVEL `Server` class from `@modelcontextprotocol/sdk/server`, never\n * `McpServer.registerTool()` (which requires Zod-shaped schemas — incompatible with ADK's\n * Joi-based tools, already rendered to plain JSON Schema by the adapter before this module ever\n * sees them). The low-level `Server` takes MCP *protocol* schemas (`ListToolsRequestSchema`/\n * `CallToolRequestSchema`), not per-tool argument schemas, so no Zod object is authored anywhere\n * in this file — the only Zod footprint is the two pre-built protocol-schema tokens imported from\n * the SDK itself.\n *\n * `--allowedTools` is kept in the CLI invocation only as a defense-in-depth, human-readable\n * statement of intent (see `wrapper.ts`'s argv construction) — it CANNOT be the real enforcement\n * mechanism, because `--dangerously-skip-permissions` removes the permission engine that an\n * allow-RULE feeds. The real enforcement happens here, twice over: `bridgedTools` arrives from the\n * adapter already pre-filtered to exclude `disallowedTools`, so a disallowed name is never even\n * listed; and the `CallTool` handler independently re-checks the requested name against that same\n * already-filtered list before ever emitting a `tool_call_request` to the adapter.\n */\n\nimport { randomUUID } from 'node:crypto'\nimport { createServer as createHttpServer } from 'node:http'\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js'\nimport { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'\nimport { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js'\nimport type { WrapperBridgedTool } from './wire'\nimport type { Server as HttpServer } from 'node:http'\n\n/** A pending `CallTool` request awaiting a `tool_call_response` from the adapter. */\ninterface PendingCall {\n resolve: (result: { content: Array<Record<string, unknown>>; isError?: boolean }) => void\n}\n\n/** The running bridge: its bound port, and hooks to route calls to/from the adapter side. */\nexport interface McpBridge {\n /** The ephemeral loopback port the bridge is listening on. */\n port: number\n /**\n * Replaces the bridge's advertised tool set. The bridge starts with an EMPTY set at boot (so it\n * can bind its port and let the wrapper emit `ready` before a `run` command — carrying the real\n * tool list — has arrived); `wrapper.ts` calls this once, when `run` arrives, before spawning\n * `claude`.\n */\n setBridgedTools(tools: WrapperBridgedTool[]): void\n /**\n * Called by `wrapper.ts` when a `tool_call_response` command arrives from the adapter, to\n * settle the matching pending `CallTool` request.\n */\n resolveToolCall(\n requestId: string,\n result: { content: Array<Record<string, unknown>>; isError?: boolean }\n ): void\n /**\n * Reject every still-pending `CallTool` request with an `isError: true` result explaining the\n * bridge is shutting down. Must run BEFORE `close()` — an in-flight request is itself an active\n * HTTP connection, so settling it first is what lets `close()` (and the underlying `http.Server`\n * close callback) unblock.\n */\n rejectPending(reason: string): void\n /** Closes the MCP transport — this is what actually tears down any open SSE stream via its own `cleanup()` calls. Must run AFTER `rejectPending()` and BEFORE the HTTP listener is closed. */\n closeTransport(): Promise<void>\n /** Closes the HTTP listener. Callback-based under the hood — promisified here. Must run LAST. */\n closeHttpServer(): Promise<void>\n}\n\n/**\n * Start the bridge: bind an ephemeral loopback HTTP listener, wire a `StreamableHTTPServerTransport`\n * (session-scoped to this one wrapper-lifetime connection — see the `sessionIdGenerator` remark\n * below) to a low-level `Server` constructed with the explicit `tools` capability (required — the\n * SDK throws for `tools/list`/`tools/call` otherwise), and register the two handlers that make the\n * current `bridgedTools` set reachable over MCP.\n *\n * @remarks\n * Starts with an EMPTY tool set — the bridge must bind its port and let the wrapper emit `ready`\n * BEFORE the adapter has sent a `run` command carrying the real tool list (the adapter waits for\n * `ready` before sending `run`, so starting the bridge only after `run` arrives would deadlock\n * both sides). Call {@link McpBridge.setBridgedTools} once `run` arrives, before spawning `claude`.\n *\n * @param onToolCallRequest - Called with `(requestId, toolName, args)` for every `CallTool` the\n * bridge accepts; the caller (`wrapper.ts`) forwards this as a `tool_call_request` `WrapperEvent`\n * to the adapter and eventually calls `resolveToolCall` with the adapter's answer.\n */\nexport const startMcpBridge = async (\n onToolCallRequest: (requestId: string, toolName: string, args: unknown) => void\n): Promise<McpBridge> => {\n const pending = new Map<string, PendingCall>()\n let nextRequestId = 0\n let bridgedTools: WrapperBridgedTool[] = []\n\n const server = new Server({ name: 'adk_bridge', version: '1' }, { capabilities: { tools: {} } })\n\n server.setRequestHandler(ListToolsRequestSchema, () => ({\n tools: bridgedTools.map((t) => ({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n })),\n }))\n\n server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const name = request.params.name\n if (!bridgedTools.some((t) => t.name === name)) {\n // Defense-in-depth: this should be unreachable in practice, since `bridgedTools` was\n // already filtered by the adapter before it ever reached this process — but re-check\n // anyway rather than trusting that invariant blindly.\n return {\n content: [{ type: 'text', text: `Tool \"${name}\" is not available in this session.` }],\n isError: true,\n }\n }\n const requestId = String(nextRequestId++)\n const result = await new Promise<{\n content: Array<Record<string, unknown>>\n isError?: boolean\n }>((resolve) => {\n pending.set(requestId, { resolve })\n onToolCallRequest(requestId, name, request.params.arguments)\n })\n return result\n })\n\n // NOT `sessionIdGenerator: undefined` (\"stateless\" mode). Confirmed directly against the\n // installed SDK (@modelcontextprotocol/sdk@1.29.0): `WebStandardStreamableHTTPServerTransport`\n // throws \"Stateless transport cannot be reused across requests. Create a new transport per\n // request.\" on the SECOND request a stateless transport ever handles (source:\n // server/webStandardStreamableHttp.js's `_hasHandledRequest` guard in `handleRequest`) — every\n // `ListTools`/`CallTool` after the very first over the bridge's lifetime would 500. A single\n // wrapper-lifetime session id (scoped to one dispatch iteration, discarded with the process) is\n // what \"stateless across DISPATCHES\" (Decision D) actually requires here, not a stateless\n // transport in the SDK's own sense.\n const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: () => randomUUID() })\n\n // Settling a pending call (`resolveToolCall`/`rejectPending`'s `entry.resolve(...)`, below) only\n // unblocks the SDK's OWN internal handler-completion Promise — the actual `transport.send()` call\n // that flushes the JSON-RPC response over the wire happens several microtask turns later, inside\n // the SDK's own `.then(handler).then(send)` chain (`shared/protocol.js`'s `_onrequest`). Confirmed\n // by direct reproduction: calling `closeTransport()` immediately after `rejectPending()` (no gap)\n // silently drops the very response `rejectPending()` just produced — the caller's `CallTool`\n // promise then never settles. Wrapping `send` here to track every in-flight call is what lets\n // `closeTransport()` (below) drain them first, a real fix rather than a fixed-delay guess.\n const inFlightSends = new Set<Promise<unknown>>()\n const originalSend = transport.send.bind(transport)\n transport.send = ((...args: Parameters<typeof originalSend>) => {\n const sent = originalSend(...args)\n inFlightSends.add(sent)\n void sent.finally(() => inFlightSends.delete(sent))\n return sent\n }) as typeof transport.send\n\n await server.connect(transport)\n\n const httpServer: HttpServer = createHttpServer((req, res) => {\n void transport.handleRequest(req, res)\n })\n\n const port = await new Promise<number>((resolve, reject) => {\n httpServer.once('error', reject)\n httpServer.listen(0, '127.0.0.1', () => {\n const address = httpServer.address()\n if (address === null || typeof address === 'string') {\n reject(new Error('MCP bridge HTTP listener did not bind to a port'))\n return\n }\n resolve(address.port)\n })\n })\n\n return {\n port,\n setBridgedTools(tools) {\n bridgedTools = tools\n },\n resolveToolCall(requestId, result) {\n const entry = pending.get(requestId)\n if (!entry) return\n pending.delete(requestId)\n entry.resolve(result)\n },\n rejectPending(reason) {\n for (const [requestId, entry] of pending) {\n pending.delete(requestId)\n entry.resolve({ content: [{ type: 'text', text: reason }], isError: true })\n }\n },\n async closeTransport() {\n // A call `resolveToolCall`/`rejectPending` just settled has NOT yet reached\n // `transport.send()` at the instant those methods return — the SDK's own handler-completion\n // chain needs at least one more event-loop turn to get there (see the `inFlightSends`\n // remark above), so `inFlightSends` can still be empty here even though a send is about to\n // start. Yield one turn first, then drain whatever is actually in flight, repeating briefly\n // in case draining itself lets a further queued send begin — bounded so a genuinely stuck\n // send can't hang shutdown forever.\n await new Promise<void>((resolve) => setImmediate(resolve))\n for (let i = 0; i < 5; i++) {\n const snapshot = Array.from(inFlightSends)\n if (snapshot.length === 0) break\n await Promise.allSettled(snapshot)\n }\n await transport.close()\n },\n async closeHttpServer() {\n await new Promise<void>((resolve, reject) => {\n httpServer.close((err) => (err ? reject(err) : resolve()))\n })\n },\n }\n}\n","/**\n * Tiny serial async task queue. Wrapper-only — never imported by `adapter.ts` (mirrors\n * `message_id_state.ts`'s and `cli_protocol.ts`'s own self-containment: no `@nhtio/adk/*` imports\n * anywhere, safe for the wrapper's self-contained-process boundary — Decision A/C).\n *\n * @remarks\n * Extracted out of `wrapper.ts`'s `startTurn` closure (issue #43, fix B follow-up, HIGH\n * verification finding against f3d7fde) so the queue's ordering guarantee is directly,\n * deterministically testable without spawning any process or racing real timers.\n *\n * The bug this exists to make structurally impossible: `wrapper.ts`'s NDJSON line reader invokes\n * its callback SYNCHRONOUSLY, once per complete line, in input order — but the original handler\n * dispatch was `void handleClaudeLine(line)`, unawaited. Since `handleClaudeLine` is `async` and\n * `await`s (e.g. `writeEvent`, which resolves on a real stdout-write callback — not necessarily on\n * the same tick, and not necessarily in call order under backpressure), firing it unawaited let a\n * SECOND line's handler start running, reach its own synchronous prefix, and even fully complete,\n * WHILE the first line's handler was still suspended at an `await`. Any mutable state shared\n * across calls (e.g. `message_id_state.ts`'s per-spawn id counter) could then be read or reset out\n * of order, and any output written from inside the handler (e.g. `message_delta` events) could be\n * written out of input order too.\n *\n * `createSerialQueue` fixes both by construction: every `enqueue`d task is chained strictly\n * after the FULL completion (including every `await` inside it) of the task before it, via a\n * single running `Promise` tail. A task that throws/rejects is caught by `onError` so one bad\n * line can never break the chain for every line enqueued after it — the tail promise itself is\n * never allowed to become rejected, or every subsequent `.then()` chained onto it would skip\n * straight to its own catch, silently dropping every later task.\n */\n\n/** A serial queue: `enqueue`d tasks run strictly one at a time, in the order they were enqueued. */\nexport interface SerialQueue {\n /** Schedule `task` to run after every previously enqueued task has fully settled. */\n enqueue: (task: () => Promise<void>) => void\n}\n\n/**\n * Create a fresh, empty serial queue. `onError` is invoked (never thrown/rejected further) for\n * any task that rejects, so the queue's own tail promise stays perpetually resolved and later\n * tasks are never skipped.\n */\nexport const createSerialQueue = (onError: (err: unknown) => void): SerialQueue => {\n let tail: Promise<void> = Promise.resolve()\n return {\n enqueue: (task) => {\n tail = tail.then(task).catch(onError)\n },\n }\n}\n","/**\n * Pure, synchronous per-spawn message-id state machine. Wrapper-only — never imported by\n * `adapter.ts` (mirrors `cli_protocol.ts`'s own header note: no `@nhtio/adk/*` imports anywhere,\n * so it stays safe for the wrapper's self-contained-process boundary — Decision A/C).\n *\n * @remarks\n * Extracted out of `wrapper.ts`'s `startTurn` closure (issue #43, fix B follow-up) so the\n * claim-and-reset step is provable WITHOUT any I/O or timing: every exported function here does\n * ONE synchronous state transition and returns before `wrapper.ts` ever reaches an `await`. This\n * matters because `wrapper.ts`'s own NDJSON line handler is `void handleClaudeLine(line)` —\n * unawaited — so several lines from one stdout chunk (or across chunks/`data` events) can have\n * their handler bodies INTERLEAVED at each other's `await` points. A version of this state machine\n * that mutated its fields AFTER an `await writeEvent(...)` (as the original fix-B patch did) let a\n * second, distinct assistant message's handler read the stale, not-yet-reset id and collide with\n * the just-sealed one — the exact race a verification pass caught against f3d7fde. Moving the\n * claim/reset into a single synchronous function call makes that race structurally impossible: by\n * the time ANY caller reaches its own first `await`, this module's state has already been fully\n * transitioned, with no in-between tick for a second line's synchronous prefix to observe.\n */\n\n/** Mutable per-spawn state, created once per `startTurn` call. Never shared across spawns. */\nexport interface MessageIdState {\n /** The wrapper-local id of the message currently accumulating partial deltas, if any. */\n partialMessageId: string | undefined\n /** Bumped once per SEALED message, so the next distinct message mints a fresh wrapper-local id. */\n messageIndex: number\n}\n\n/** Fresh state for a new `startTurn` spawn. */\nexport const createMessageIdState = (): MessageIdState => ({\n partialMessageId: undefined,\n messageIndex: 0,\n})\n\n/**\n * Claim the wrapper-local id for a `stream_event` partial delta. Synchronously assigns\n * `partialMessageId` if this is the first delta seen for the in-progress message, so every\n * subsequent partial delta (and the eventual complete-message line) reuses the SAME id — call\n * this, and only this, before ever `await`-ing the corresponding `writeEvent`.\n */\nexport const claimPartialDeltaId = (state: MessageIdState): string => {\n const id = state.partialMessageId ?? `message-${state.messageIndex}`\n state.partialMessageId = id\n return id\n}\n\n/**\n * Claim the wrapper-local id for a complete (`assistant`/`user`) message line, and atomically\n * reset the state for whatever distinct message this SAME spawn may still emit next (text ->\n * tool_use -> more text all arrive within one spawn — issue #43, fix B). `hadPriorPartialDelta`\n * tells the caller whether a `stream_event` delta already carried this message's text (in which\n * case the complete line's own text must NOT be re-sent as the delta, or the adapter's per-id\n * accumulator would duplicate it) — matching the wrapper's pre-existing `partialMessageId ===\n * undefined ? text : ''` decision, now made in the same atomic step as the claim itself.\n */\nexport const claimCompleteMessageId = (\n state: MessageIdState\n): { id: string; hadPriorPartialDelta: boolean } => {\n const id = state.partialMessageId ?? `message-${state.messageIndex}`\n const hadPriorPartialDelta = state.partialMessageId !== undefined\n state.partialMessageId = undefined\n state.messageIndex += 1\n return { id, hadPriorPartialDelta }\n}\n","/**\n * Claude Code CLI's own stream-json vocabulary types and parser. Wrapper-only — never imported by\n * `adapter.ts`.\n *\n * @remarks\n * No `@nhtio/adk/*` imports (this module runs inside the wrapper process, per Decision A/C — the\n * wrapper is self-contained with respect to the ADK). Parses the `--output-format stream-json`\n * NDJSON lines `claude` emits into a small internal shape `wrapper.ts` then translates into the\n * normalized `WrapperEvent` union from `./wire`.\n *\n * The vocabulary here converges across the official docs and two independent prior-art parsers\n * (`nhtio-agent-delegator`'s `claude_harness.ts`, `giveon-claude-max-api-proxy`'s `manager.ts`):\n * `system` (init/api_retry subtypes), `assistant`/`user` (with `parent_tool_use_id` distinguishing\n * main-conversation from subagent text), `stream_event` (partial message deltas), and a terminal\n * `result` (success/error).\n */\n\n/** A `system` event — either the one-time init handshake or a mid-turn retry notice. */\nexport interface ClaudeSystemInitLine {\n type: 'system'\n subtype: 'init'\n model?: string\n tools?: string[]\n mcp_servers?: Array<{ name: string; status?: string }>\n [key: string]: unknown\n}\n\nexport interface ClaudeSystemApiRetryLine {\n type: 'system'\n subtype: 'api_retry'\n attempt?: number\n max_retries?: number\n retry_delay_ms?: number\n error_status?: number\n error?: string\n [key: string]: unknown\n}\n\n/** An `assistant`/`user` message line. `parent_tool_use_id` distinguishes subagent from main-conversation text. */\nexport interface ClaudeMessageLine {\n type: 'assistant' | 'user'\n parent_tool_use_id?: string | null\n message?: {\n id?: string\n content?: Array<{ type: string; text?: string; [key: string]: unknown }>\n [key: string]: unknown\n }\n [key: string]: unknown\n}\n\n/** A `stream_event` line — a partial message delta under `--include-partial-messages`. */\nexport interface ClaudeStreamEventLine {\n type: 'stream_event'\n event?: {\n type?: string\n delta?: { type?: string; text?: string; [key: string]: unknown }\n [key: string]: unknown\n }\n parent_tool_use_id?: string | null\n [key: string]: unknown\n}\n\n/** The terminal `result` line — always exactly one per turn, success or error. */\nexport interface ClaudeResultLine {\n type: 'result'\n subtype?: string\n is_error?: boolean\n result?: string\n session_id?: string\n total_cost_usd?: number\n usage?: Record<string, unknown>\n stop_reason?: string\n [key: string]: unknown\n}\n\nexport type ClaudeStreamJsonLine =\n | ClaudeSystemInitLine\n | ClaudeSystemApiRetryLine\n | ClaudeMessageLine\n | ClaudeStreamEventLine\n | ClaudeResultLine\n\n/**\n * Parse one already-newline-split `claude --output-format stream-json` line. Returns `undefined`\n * for anything that fails to parse as JSON or does not match a recognized `type` — the caller\n * (`wrapper.ts`) treats an `undefined` result as a non-fatal `log` event at `trace`, never throws.\n */\nexport const parseClaudeStreamJsonLine = (raw: string): ClaudeStreamJsonLine | undefined => {\n const trimmed = raw.trim()\n if (trimmed.length === 0) return undefined\n let value: unknown\n try {\n value = JSON.parse(trimmed)\n } catch {\n return undefined\n }\n if (value === null || typeof value !== 'object') return undefined\n const obj = value as Record<string, unknown>\n const type = obj.type\n if (type === 'system' && obj.subtype === 'init') return obj as unknown as ClaudeSystemInitLine\n if (type === 'system' && obj.subtype === 'api_retry')\n return obj as unknown as ClaudeSystemApiRetryLine\n if (type === 'assistant' || type === 'user') return obj as unknown as ClaudeMessageLine\n if (type === 'stream_event') return obj as unknown as ClaudeStreamEventLine\n if (type === 'result') return obj as unknown as ClaudeResultLine\n return undefined\n}\n\n/**\n * Extract the plain-text delta from a `stream_event` line's content-block delta, or `undefined`\n * if this particular stream_event carries no text delta (e.g. a tool-call-argument delta, which\n * this battery does not surface as message text).\n */\nexport const extractStreamEventTextDelta = (line: ClaudeStreamEventLine): string | undefined => {\n const delta = line.event?.delta\n if (!delta) return undefined\n if (delta.type === 'text_delta' && typeof delta.text === 'string') return delta.text\n return undefined\n}\n\n/** Extract the concatenated plain text from a complete (non-streamed) assistant/user message line. */\nexport const extractMessageText = (line: ClaudeMessageLine): string => {\n const blocks = line.message?.content\n if (!Array.isArray(blocks)) return ''\n return blocks\n .filter((b) => b.type === 'text' && typeof b.text === 'string')\n .map((b) => b.text as string)\n .join('')\n}\n","#!/usr/bin/env node\n/**\n * Standalone Node entry point that owns all Claude-Code-specific complexity: spawning the real\n * `claude` binary, hosting the MCP bridge, and translating its stream-json into the normalized\n * adapter↔wrapper protocol.\n *\n * @remarks\n * Self-contained with respect to `@nhtio/adk/*` — no such imports anywhere in this file or its\n * five siblings (`wire.ts`, `cli_protocol.ts`, `mcp_bridge.ts`, `message_id_state.ts`,\n * `line_queue.ts`). Only `node:*` builtins, `@modelcontextprotocol/sdk`, and those five\n * battery-local modules. Ships as a sibling dist asset (see Decision C in the design notes) —\n * never imported as a library, only ever spawned by file path via\n * `execa(process.execPath, [wrapperPath])` from `adapter.ts`.\n *\n * Carries no `@module` JSDoc tag: it is invisible to the `@module`-tag scraper that builds the\n * public `exports` map, and is added to `vite.config.mts`'s `build.lib.entry` as an explicit extra\n * key instead, following the `mcp/server.ts` precedent for a non-consumer-facing standalone\n * executable.\n */\n\nimport { spawn } from 'node:child_process'\nimport { startMcpBridge } from './mcp_bridge'\nimport { createSerialQueue } from './line_queue'\nimport { createNdjsonLineReader, encodeWrapperEvent } from './wire'\nimport {\n createMessageIdState,\n claimPartialDeltaId,\n claimCompleteMessageId,\n} from './message_id_state'\nimport {\n parseClaudeStreamJsonLine,\n extractStreamEventTextDelta,\n extractMessageText,\n} from './cli_protocol'\nimport type { McpBridge } from './mcp_bridge'\nimport type { ChildProcess } from 'node:child_process'\nimport type { WrapperCommand, WrapperRunCommand, WrapperEvent, ClaudeCodeCliExtraArg } from './wire'\n\n// ─── stdout writer (every emit is an awaited, flush-confirmed write) ───────────\n\n// Every stdout write this process makes — including `log()`'s fire-and-forget ones below — is\n// counted while in flight. The normal-completion exit path (`shutdownNormally`, ~L220) awaits this\n// counter reaching zero before calling `process.exit(0)`: Node's Writable stream ordering already\n// guarantees any write ENQUEUED before the terminal `shutdown_complete` write has its callback fire\n// no later than that write's own callback (same underlying fd, same queue, strictly FIFO), but a\n// `log()` call is fire-and-forget by design and nothing stops one from being *enqueued* by a\n// still-settling async step (e.g. inside `bridge.closeTransport()`/`closeHttpServer()`, whose\n// internals this file does not control) concurrently with or after the terminal write — a counter\n// is the only mechanism that also covers a write that hasn't been enqueued yet at the moment we\n// check. `waitForPendingWrites()` resolves once every write outstanding AT THE TIME IT IS CALLED\n// has settled, which is the correct instant to poll it: called synchronously right before\n// `process.exit(0)`, with nothing awaited in between, so nothing new can slip in after the check.\nlet pendingWriteCount = 0\nlet pendingWritesSettled: (() => void) | undefined\nconst trackPendingWrite = (promise: Promise<void>): Promise<void> => {\n pendingWriteCount += 1\n const settle = (): void => {\n pendingWriteCount -= 1\n if (pendingWriteCount === 0) pendingWritesSettled?.()\n }\n // Both branches must decrement — a rejected write (e.g. EPIPE on a closed stdout) is still a\n // settled write for drain-tracking purposes; the rejection itself is handled by each write's own\n // caller (writeEvent's caller, or log()'s own `.catch(() => {})`).\n promise.then(settle, settle)\n return promise\n}\nconst waitForPendingWrites = (): Promise<void> => {\n if (pendingWriteCount === 0) return Promise.resolve()\n return new Promise<void>((resolve) => {\n pendingWritesSettled = resolve\n })\n}\n\nconst writeEvent = (event: WrapperEvent): Promise<void> =>\n trackPendingWrite(\n new Promise<void>((resolve) => {\n process.stdout.write(encodeWrapperEvent(event), (err) => {\n // issue #42 defect #2: writeEvent itself must never reject. The stream-level\n // `process.stdout.on('error', ...)` handler installed in `main()` only covers the\n // STREAM's own 'error' event — it does nothing to protect the many call sites throughout\n // this file that `await`/`void` a `writeEvent(...)` call without their own `.catch()`\n // (e.g. `ready`, `init`, `message_delta`, `result`, `grandchild_spawned`,\n // `tool_call_request`). A rejected promise from one of those unguarded call sites is an\n // unhandled rejection that crashes this process with exit code 1 — confirmed empirically\n // against a real closed-stdout/EPIPE condition — precisely the ungraceful crash Part A\n // (and this defect's stream-level handler) already exists to eliminate. Every caller\n // that DOES branch on write success only ever does so via `waitForPendingWrites`'s\n // settle-on-either-outcome tracking (see `trackPendingWrite` above), which is unaffected\n // by resolving here instead of rejecting, so there is no behavioral loss in never\n // rejecting.\n if (err && (err as NodeJS.ErrnoException).code !== 'EPIPE') {\n process.stderr.write(`[claude_code_cli wrapper] stdout write error: ${String(err)}\\n`)\n }\n resolve()\n })\n })\n )\n\nconst log = (\n level: 'trace' | 'debug' | 'info' | 'warn' | 'error',\n kind: string,\n message: string,\n payload?: unknown\n): void => {\n void writeEvent({ type: 'log', level, kind, message, payload }).catch(() => {})\n}\n\n// ─── stdin command reader ───────────────────────────────────────────────────\n\nlet stdinDataListener: ((chunk: Uint8Array) => void) | undefined\nlet stdinEndListener: (() => void) | undefined\n\n/** Stop the stdin command reader and detach its listeners — called on every exit path. */\nconst stopStdinReader = (): void => {\n if (stdinDataListener) process.stdin.off('data', stdinDataListener)\n if (stdinEndListener) process.stdin.off('end', stdinEndListener)\n stdinDataListener = undefined\n stdinEndListener = undefined\n try {\n process.stdin.pause()\n } catch {\n /* stdin may already be gone */\n }\n}\n\n// ─── argv construction (Decision F0) ───────────────────────────────────────\n\n/** Validate one `extraArgs` entry has already been checked by the adapter; convert it to argv tokens. */\nconst extraArgToArgv = (entry: ClaudeCodeCliExtraArg): string[] => {\n if (entry.value === undefined) return [entry.flag]\n if (Array.isArray(entry.value)) return [entry.flag, ...entry.value]\n return [entry.flag, entry.value]\n}\n\n/** Build the complete, authoritative argv for the `claude` grandchild. */\nconst buildClaudeArgv = (cmd: WrapperRunCommand, bridgeUrl: string): string[] => {\n const args: string[] = [\n '--bare',\n '-p',\n '--verbose',\n '--output-format',\n 'stream-json',\n '--include-partial-messages',\n '--no-session-persistence',\n '--tools',\n '',\n '--strict-mcp-config',\n '--mcp-config',\n JSON.stringify({ mcpServers: { adk_bridge: { type: 'http', url: bridgeUrl } } }),\n '--dangerously-skip-permissions',\n ]\n // --allowedTools: OMITTED ENTIRELY when there are no bridged tools — the flag is variadic, and a\n // bare `--allowedTools` with nothing after it swallows the very next argv token (confirmed by\n // direct reproduction against the live CLI during design).\n if (cmd.allowedTools.length > 0) {\n args.push(\n '--allowedTools',\n cmd.allowedTools.map((name) => `mcp__adk_bridge__${name}`).join(',')\n )\n }\n if (cmd.appendSystemPrompt !== undefined) {\n args.push('--append-system-prompt', cmd.appendSystemPrompt)\n }\n if (cmd.model !== undefined) {\n args.push('--model', cmd.model)\n }\n if (cmd.addDir !== undefined && cmd.addDir.length > 0) {\n args.push('--add-dir', ...cmd.addDir)\n }\n if (cmd.maxBudgetUsd !== undefined) {\n args.push('--max-budget-usd', String(cmd.maxBudgetUsd))\n }\n // Fixed single-turn dispatch contract: the harness owns iteration boundaries.\n args.push('--max-turns', '1')\n if (cmd.fallbackModel !== undefined && cmd.fallbackModel.length > 0) {\n // ONE comma-joined value, never separate argv tokens — confirmed by direct reproduction: the\n // flag is singular (`--fallback-model <model>`) and documented as accepting \"a comma-separated\n // list to try each in order.\"\n args.push('--fallback-model', cmd.fallbackModel.join(','))\n }\n if (cmd.forwardSubagentText === true) {\n args.push('--forward-subagent-text')\n }\n for (const entry of cmd.extraArgs ?? []) {\n args.push(...extraArgToArgv(entry))\n }\n args.push('--', cmd.prompt)\n return args\n}\n\n/** Build the grandchild's env: start from the ambient env, then explicitly delete-then-set every credential/behavior variable this command controls. */\nconst buildClaudeEnv = (cmd: WrapperRunCommand): Record<string, string | undefined> => {\n const env: Record<string, string | undefined> = { ...process.env }\n // issue #42 defect #3: `ELECTRON_RUN_AS_NODE` in THIS wrapper's own env may have been injected\n // by the adapter (Part C, issue #42) purely to make an Electron-host copy of the wrapper itself\n // run as plain Node — that injection has nothing to do with the `claude` grandchild, which\n // could itself be a Node/Electron-based binary whose behavior this stray var could unexpectedly\n // change. The marker is set ONLY alongside the adapter's own injection (see adapter.ts's\n // `wrapperEnv` construction), never by a consumer setting `ELECTRON_RUN_AS_NODE` in their own\n // ambient environment for an unrelated reason — so stripping is conditional on the marker being\n // present, not unconditional, to avoid surprising a consumer who relies on it being forwarded.\n // Both the marker itself and the var it gates are removed; neither should reach `claude`.\n if (env.ADK_CLAUDE_CODE_CLI_STRIP_RUN_AS_NODE_FROM_GRANDCHILD !== undefined) {\n delete env.ELECTRON_RUN_AS_NODE\n }\n delete env.ADK_CLAUDE_CODE_CLI_STRIP_RUN_AS_NODE_FROM_GRANDCHILD\n delete env.ANTHROPIC_API_KEY\n delete env.ANTHROPIC_AUTH_TOKEN\n delete env.ANTHROPIC_BASE_URL\n delete env.DISABLE_TELEMETRY\n delete env.DISABLE_ERROR_REPORTING\n delete env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC\n delete env.CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT\n if (cmd.auth?.apiKey !== undefined) env.ANTHROPIC_API_KEY = cmd.auth.apiKey\n if (cmd.auth?.authToken !== undefined) env.ANTHROPIC_AUTH_TOKEN = cmd.auth.authToken\n if (cmd.auth?.baseUrl !== undefined) env.ANTHROPIC_BASE_URL = cmd.auth.baseUrl\n if (cmd.disableTelemetry === true) env.DISABLE_TELEMETRY = '1'\n if (cmd.disableErrorReporting === true) env.DISABLE_ERROR_REPORTING = '1'\n if (cmd.disableNonessentialTraffic === true) env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC = '1'\n if (cmd.mcpToolIdleTimeoutMs !== undefined) {\n env.CLAUDE_CODE_MCP_TOOL_IDLE_TIMEOUT = String(cmd.mcpToolIdleTimeoutMs)\n }\n return env\n}\n\n// ─── main ───────────────────────────────────────────────────────────────────\n\nconst main = async (): Promise<void> => {\n // issue #42 defect #2: a closed stdout (EPIPE — the reader on the other end of the pipe is\n // gone) is a normal shutdown-adjacent condition here, not a bug. Without an explicit listener,\n // Node's default behavior for an unhandled Writable 'error' event is to throw, crashing this\n // process with exit code 1 — precisely the kind of ungraceful crash Part A exists to eliminate.\n // Every write's own promise (see `trackPendingWrite`/`writeEvent` above) already settles via its\n // callback's `err` branch regardless of this listener, so `waitForPendingWrites()` still\n // resolves correctly on its own (nothing further to wait on once the reader is gone) — this\n // listener's only job is to stop Node from treating a gone reader as fatal.\n process.stdout.on('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EPIPE') return\n // Any other stdout stream error is unexpected; surface it to stderr for diagnosis (stdout\n // itself may not be usable) rather than silently discarding it.\n process.stderr.write(`[claude_code_cli wrapper] stdout stream error: ${String(err)}\\n`)\n })\n\n let bridge: McpBridge | undefined\n let grandchild: ChildProcess | undefined\n let shuttingDown = false\n let sawResult = false\n\n /** Kill the grandchild's entire detached process group. POSIX only (enforced by the adapter's own options validation before this wrapper is ever spawned). */\n const killGrandchildGroup = (signal: NodeJS.Signals): void => {\n if (!grandchild || grandchild.pid === undefined || grandchild.exitCode !== null) return\n try {\n process.kill(-grandchild.pid, signal)\n } catch {\n /* the group may already be gone */\n }\n }\n\n /** Await the grandchild's actual exit for a bounded period; fall through to a process-group kill if it hasn't exited in time. */\n const waitForGrandchildExit = async (graceMs: number): Promise<void> => {\n if (!grandchild || grandchild.exitCode !== null || grandchild.signalCode !== null) return\n const exited = await new Promise<boolean>((resolve) => {\n const timer = setTimeout(() => resolve(false), graceMs)\n grandchild?.once('exit', () => {\n clearTimeout(timer)\n resolve(true)\n })\n })\n if (!exited) {\n killGrandchildGroup('SIGTERM')\n }\n }\n\n /**\n * The corrected shutdown sequence (Decision D step 5), shared by the normal-completion path and\n * the SIGTERM/SIGINT handler. Order matters: reject pending calls, THEN close the transport\n * (which tears down any open SSE stream), THEN close the HTTP listener (now genuinely\n * unblocked), THEN bound-wait/kill the grandchild, THEN flush `shutdown_complete`, THEN stop the\n * stdin reader.\n */\n const runShutdownSequence = async (disposeGraceMs: number): Promise<void> => {\n bridge?.rejectPending('The Claude Code CLI wrapper is shutting down.')\n if (bridge) await bridge.closeTransport()\n if (bridge) await bridge.closeHttpServer()\n await waitForGrandchildExit(disposeGraceMs)\n await writeEvent({ type: 'shutdown_complete' }).catch(() => {})\n stopStdinReader()\n }\n\n // A 5-second backstop, entirely separate from the normal-completion path: if the graceful\n // sequence above hangs, this fires, force-kills the grandchild's process group unconditionally,\n // and calls process.exit(1) — a SEPARATE, hang-recovery process.exit() call from the one\n // `shutdownNormally` makes below on its own (non-hung) success path. The two can never both run\n // for the same shutdown: `disarmBackstop()` always clears this timer before `shutdownNormally`'s\n // own `process.exit(0)`, and this callback body itself exits before returning control, so at most\n // one of the two `process.exit()` calls in this function's family actually executes.\n let backstopTimer: ReturnType<typeof setTimeout> | undefined\n const armBackstop = (): void => {\n backstopTimer = setTimeout(() => {\n killGrandchildGroup('SIGKILL')\n process.exitCode = 1\n process.exit(1)\n }, 5_000)\n }\n const disarmBackstop = (): void => {\n if (backstopTimer) clearTimeout(backstopTimer)\n backstopTimer = undefined\n }\n\n const shutdownNormally = async (disposeGraceMs: number): Promise<void> => {\n if (shuttingDown) return\n shuttingDown = true\n armBackstop()\n await runShutdownSequence(disposeGraceMs)\n process.exitCode = 0\n // Explicit process.exit(0) — this is the actual fix for the reported bug (issue #42): when the\n // host process is an Electron main process (or any other host with a persistent, non-draining\n // event loop — an open BrowserWindow, a live timer, an open server socket the host itself\n // owns), a bare \"fall off the end of main()\" never terminates the process, because Node only\n // exits on its own once the event loop has NOTHING left to do, and this wrapper does not own\n // every handle that might be keeping that loop alive in an Electron host. A plain Node CLI host\n // exits fine either way (its own loop drains once `main()`'s promise settles with nothing else\n // pending), so this exit is safe and equivalent there — it is only ever OBSERVABLE as a fix in\n // a host with something else keeping the loop alive.\n //\n // `runShutdownSequence` above already `await`s `writeEvent({ type: 'shutdown_complete' })`\n // directly, so its OWN write's callback (and, by Node's strictly-FIFO per-stream write-callback\n // ordering, every write enqueued to this same stdout stream BEFORE it) has already fired by\n // this point. That does not cover every write, though: `log()` (used for diagnostics\n // throughout this file, including possibly from something like a lingering 'close'/'error'\n // handler on the MCP bridge's HTTP server) is fire-and-forget by design (`void writeEvent(...)`)\n // and can be invoked from a callback that is not sequenced via any `await` in this function —\n // such a call could still be IN FLIGHT (enqueued to stdout, callback not yet fired) at this\n // exact point, arbitrarily AFTER `shutdown_complete`'s own write settled, which the FIFO\n // guarantee above says nothing about. `waitForPendingWrites()` (see its definition and the\n // `pendingWriteCount` machinery near the top of this file) is the flush barrier that actually\n // accounts for that case: it tracks every `writeEvent(...)` call site (not just this one), and\n // resolves only once every write outstanding at the moment it's called has actually settled —\n // so a `log()` call racing the shutdown sequence is never truncated by this `process.exit(0)`.\n //\n // issue #42 defect #2: the backstop (armed above) MUST stay live through this await, not be\n // disarmed before it — a stuck/backpressured stdout flush (e.g. a slow or paused reader on\n // the other end of the pipe) is exactly the kind of hang Part A exists to recover from, and\n // disarming here would leave this final await with no timeout protection at all. Disarm only\n // now, immediately before the exit call that makes the backstop's own alternate exit path\n // moot.\n await waitForPendingWrites()\n disarmBackstop()\n process.exit(0)\n }\n\n // Idempotent SIGTERM/SIGINT handling. Registering a handler REPLACES Node's default\n // terminate-on-signal behavior, so this path must explicitly call process.exit() itself once the\n // shutdown sequence completes — same requirement `shutdownNormally` above now has for the same\n // reason (a signal handler being registered at all is itself evidence of \"something else may be\n // keeping this event loop alive\", exactly the condition that motivates `shutdownNormally`'s own\n // explicit exit). This path does not thread through the `pendingWriteCount` flush barrier the\n // way `shutdownNormally` does — a killed/interrupted process discarding its last `log()` line is\n // an acceptable loss on a signal-driven shutdown, unlike the normal-completion path where\n // preserving every diagnostic write matters more. Uses its own `handlingSignal` guard rather than\n // the `shuttingDown` flag `shutdownNormally` sets, so the two CAN run concurrently if a signal\n // arrives mid-shutdown — a pre-existing race, unaffected by this fix: whichever `process.exit()`\n // call reaches the event loop first wins, and Node ignores a second one against an\n // already-terminating process.\n let handlingSignal = false\n const onSignal = (): void => {\n if (handlingSignal) return\n handlingSignal = true\n void runShutdownSequence(2_000)\n .then(() => process.exit(0))\n .catch(() => process.exit(1))\n }\n process.on('SIGTERM', onSignal)\n process.on('SIGINT', onSignal)\n // Final, synchronous, best-effort safety net — cannot await anything per Node's own `exit` event\n // contract, so it is not the primary cleanup mechanism for any path above.\n process.on('exit', () => {\n killGrandchildGroup('SIGTERM')\n })\n\n let runCommand: WrapperRunCommand | undefined\n\n const handleCommand = (command: WrapperCommand): void => {\n if (command.type === 'run') {\n if (runCommand !== undefined) {\n log('error', 'duplicate-run-command', 'A run command was already accepted; ignoring.')\n return\n }\n runCommand = command\n void startTurn(command)\n return\n }\n if (command.type === 'tool_call_response') {\n bridge?.resolveToolCall(command.requestId, command.results)\n return\n }\n if (command.type === 'shutdown') {\n void shutdownNormally(runCommand ? 2_000 : 0)\n return\n }\n }\n\n const commandReader = createNdjsonLineReader<WrapperCommand>((raw) => {\n let command: WrapperCommand\n try {\n command = JSON.parse(raw) as WrapperCommand\n } catch {\n log('trace', 'malformed-command', 'Failed to parse inbound command line; skipping.', {\n linePreview: raw.slice(0, 256),\n })\n return undefined\n }\n handleCommand(command)\n return command\n })\n stdinDataListener = (chunk) => commandReader.push(chunk)\n stdinEndListener = () => commandReader.end()\n process.stdin.on('data', stdinDataListener)\n process.stdin.on('end', stdinEndListener)\n\n // The bridge starts and binds its port IMMEDIATELY at wrapper boot, with an empty tool set —\n // NOT inside `startTurn`. The adapter waits for `ready` before ever sending `run` (which is what\n // carries the real tool list), so starting the bridge only after `run` arrives would deadlock\n // both sides: the adapter waiting for `ready`, the wrapper waiting for `run`. `run`'s own\n // handling (`startTurn`, below) calls `bridge.setBridgedTools(...)` once the real list is known,\n // before spawning `claude`.\n try {\n bridge = await startMcpBridge((requestId, toolName, args) => {\n void writeEvent({ type: 'tool_call_request', requestId, tool: toolName, args })\n })\n } catch (err) {\n await writeEvent({\n type: 'error',\n message: 'Failed to start the MCP bridge.',\n // eslint-disable-next-line adk/prefer-is-error -- self-contained wrt @nhtio/adk/* (Decision A)\n detail: err instanceof Error ? err.message : String(err),\n }).catch(() => {})\n process.exitCode = 1\n return\n }\n\n await writeEvent({ type: 'ready' })\n\n const startTurn = async (command: WrapperRunCommand): Promise<void> => {\n if (!bridge) return\n bridge.setBridgedTools(command.bridgedTools)\n\n const bridgeUrl = `http://127.0.0.1:${bridge.port}/`\n const argv = buildClaudeArgv(command, bridgeUrl)\n const env = buildClaudeEnv(command)\n\n grandchild = spawn(command.claudeBin, argv, {\n cwd: command.cwd,\n env,\n detached: true,\n stdio: ['ignore', 'pipe', 'pipe'],\n })\n // issue #42 defect #1: report the grandchild's pid (== pgid, since it's detached) so the\n // adapter can escalate a SIGKILL to the whole process group, not just the wrapper itself.\n if (typeof grandchild.pid === 'number') {\n void writeEvent({ type: 'grandchild_spawned', pid: grandchild.pid })\n }\n\n // Per-spawn message-id claim/reset state (issue #43, fix B) — see `message_id_state.ts` for\n // why this lives in its own synchronous, awaitless module rather than as loose locals mutated\n // around an `await`.\n const messageIdState = createMessageIdState()\n\n // Every stdout `'data'` chunk can carry several NDJSON lines, and `createNdjsonLineReader`\n // invokes its callback SYNCHRONOUSLY, once per complete line, in the order they appear in the\n // chunk — but `handleClaudeLine` itself is `async` and `await`s (e.g. `writeEvent`), so firing\n // it unawaited per line (the original shape here) let a SECOND line's handler start running,\n // reach its own synchronous prefix, and even complete entirely, WHILE the first line's handler\n // was still suspended at an `await`. That is exactly the race a verification pass caught\n // against the initial fix-B patch: two `assistant`/`user` lines arriving in one chunk could\n // have their `writeEvent(..., isComplete: true)` calls (and any state built on top of them)\n // resolve out of order relative to the input. `createSerialQueue` (see `line_queue.ts`) chains\n // every line's handling onto a single promise tail, so the processing of one line strictly\n // happen-afters the full completion (including every `await` inside it) of the line before it\n // — `messageIdState`'s claim/reset calls, and the `writeEvent`s they gate, always run in input\n // order, with no window for a later line to observe stale state left over from an earlier one\n // still in flight. A handler that throws/rejects is caught by the queue's `onError` so one bad\n // line can never break the chain for every line after it.\n const lineQueue = createSerialQueue((err: unknown) => {\n log('error', 'stream-line-handler-error', 'Error handling a Claude stream-json line.', {\n // eslint-disable-next-line adk/prefer-is-error -- self-contained wrt @nhtio/adk/* (Decision A)\n detail: err instanceof Error ? err.message : String(err),\n })\n })\n\n const dispatchReader = createNdjsonLineReader((raw) => {\n const line = parseClaudeStreamJsonLine(raw)\n if (line === undefined) {\n log(\n 'trace',\n 'malformed-stream-json',\n 'Failed to parse Claude stream-json line; skipping.',\n {\n linePreview: raw.slice(0, 256),\n }\n )\n return undefined\n }\n lineQueue.enqueue(() => handleClaudeLine(line))\n return line\n })\n grandchild.stdout?.on('data', (chunk: Uint8Array) => {\n dispatchReader.push(chunk)\n })\n\n const handleClaudeLine = async (\n line: ReturnType<typeof parseClaudeStreamJsonLine>\n ): Promise<void> => {\n if (line === undefined) return\n if (line.type === 'system' && line.subtype === 'init') {\n const mcpServerErrors = Array.isArray(line.mcp_servers)\n ? line.mcp_servers\n .filter((s) => s.status === 'failed' && s.name === 'adk_bridge')\n .map((s) => s.name)\n : []\n await writeEvent({\n type: 'init',\n model: line.model,\n tools: line.tools,\n mcpServerErrors: mcpServerErrors.length > 0 ? mcpServerErrors : undefined,\n raw: line,\n })\n return\n }\n if (line.type === 'system' && line.subtype === 'api_retry') {\n await writeEvent({\n type: 'retry',\n attempt: line.attempt ?? 0,\n maxRetries: line.max_retries,\n retryDelayMs: line.retry_delay_ms,\n errorStatus: line.error_status,\n error: line.error,\n })\n return\n }\n if (line.type === 'stream_event') {\n if (line.parent_tool_use_id && command.forwardSubagentText !== true) return\n const delta = extractStreamEventTextDelta(line)\n if (delta !== undefined) {\n // `claimPartialDeltaId` reads AND assigns `messageIdState.partialMessageId` in one\n // synchronous call, with no `await` in between — see `message_id_state.ts`'s header for\n // why this matters (the line-handling queue above already serializes calls into this\n // function, but the claim itself staying synchronous is what keeps this function safe to\n // call from anywhere, including a future caller that isn't behind that queue).\n const id = claimPartialDeltaId(messageIdState)\n await writeEvent({ type: 'message_delta', id, delta })\n }\n return\n }\n if (line.type === 'assistant' || line.type === 'user') {\n if (line.parent_tool_use_id && command.forwardSubagentText !== true) return\n const text = extractMessageText(line)\n if (text.length > 0) {\n // Claim this message's id AND reset the state for whatever distinct message this SAME\n // spawn may still emit next (text -> tool_use -> more text) in one synchronous call,\n // strictly BEFORE the `await writeEvent(...)` below — the original fix-B patch mutated\n // `partialMessageId`/`messageIndex` AFTER that `await`, which let a second message's\n // handler (running concurrently, per the queue-serialization note above) read the\n // stale, not-yet-reset id and collide with the one just sealed here (issue #43, fix B\n // race, caught by a subsequent verification pass against f3d7fde).\n const { id, hadPriorPartialDelta } = claimCompleteMessageId(messageIdState)\n // If no prior stream_event deltas arrived for this id, the complete message carries the\n // ONLY copy of the text — send it as the delta itself, not an empty seal, or the\n // adapter's per-id accumulator (which treats the first call's deltaText as the full\n // content) would create an empty message despite real text having arrived.\n const delta = hadPriorPartialDelta ? '' : text\n await writeEvent({ type: 'message_delta', id, delta, isComplete: true })\n }\n return\n }\n if (line.type === 'result') {\n sawResult = true\n await writeEvent({\n type: 'result',\n resultText: line.result,\n sessionId: line.session_id,\n totalCostUsd: line.total_cost_usd,\n usage: line.usage,\n isError: line.is_error === true,\n subtype: line.subtype,\n stopReason: line.stop_reason,\n raw: line,\n })\n await shutdownNormally(2_000)\n }\n }\n\n grandchild.on('error', (err) => {\n void writeEvent({\n type: 'error',\n message: 'The claude grandchild process failed to spawn.',\n detail: err.message,\n }).catch(() => {})\n })\n grandchild.on('exit', (code, signal) => {\n // issue #42 round-2 defect #1: tell the adapter the grandchild is gone, unconditionally and\n // regardless of the `sawResult`/`shuttingDown` guard below — this is what lets the adapter\n // clear its own cached pid/pgid so a later SIGKILL escalation never signals a stale value\n // that the OS may have already reused for an unrelated process group. This wrapper process\n // itself may be mid-shutdown (or about to be) when this fires; Node still delivers the\n // `ChildProcess` 'exit' event to this handler regardless, unless the wrapper is wedged badly\n // enough to never run any JS at all — in which case no event this process could emit would\n // help the adapter anyway (see the matching comment on `gracefulShutdown()` in adapter.ts).\n void writeEvent({ type: 'grandchild_exited' }).catch(() => {})\n if (sawResult || shuttingDown) return\n void writeEvent({\n type: 'error',\n message: `claude exited (code=${String(code)}, signal=${String(signal)}) with no terminal result observed.`,\n }).catch(() => {})\n })\n }\n}\n\nmain().catch((error: unknown) => {\n // eslint-disable-next-line adk/prefer-is-error -- self-contained wrt @nhtio/adk/* (Decision A)\n const message = error instanceof Error ? error.message : String(error)\n process.stderr.write(`claude_code_cli wrapper fatal: ${message}\\n`)\n process.exitCode = 1\n})\n"],"x_google_ignoreList":[0,1,2],"mappings":";;;;;;;;;;;AASA,IAAI,eAAe,cAAc,MAAM;CACrC,YAAY,SAAS,SAAS;EAC5B,MAAM,SAAS,OAAO;EACtB,KAAK,OAAO;CACd;AACF;AACA,IAAI,kBAAkB,MAAM;CAC1B,IAAI,aAAa,cACf,OAAO;CAET,OAAO,IAAI,aAAa,EAAE,SAAS,EAAE,OAAO,EAAE,CAAC;AACjD;AACA,IAAI,gBAAgB,OAAO;AAC3B,IAAI,UAAU,cAAc,cAAc;CACxC,YAAY,OAAO,SAAS;EAC1B,IAAI,OAAO,UAAU,YAAY,mBAAmB,OAClD,QAAQ,MAAM,iBAAiB;EAEjC,IAAI,OAAO,SAAS,MAAM,cAAc,aAEtC,QAAQ,WAAW;EAErB,MAAM,OAAO,OAAO;CACtB;AACF;AACA,IAAI,0BAA0B,aAAa;CACzC,MAAM,eAAe,CAAC;CACtB,MAAM,aAAa,SAAS;CAC5B,KAAK,IAAI,IAAI,GAAG,IAAI,WAAW,QAAQ,KAAK,GAAG;EAC7C,MAAM,GAAG,IAAI,MAAM,IAAI,IAAI,UAAU;EACrC,IAAI,IAAI,WAAW,CAAC,MACpB,IACE,aAAa,KAAK,CAAC,KAAK,KAAK,CAAC;CAElC;CACA,OAAO,IAAI,QAAQ,YAAY;AACjC;AACA,IAAI,iBAAiB,OAAO,gBAAgB;AAC5C,IAAI,0BAA0B,QAAQ,KAAK,SAAS,UAAU,oBAAoB;CAChF,MAAM,OAAO;EACX;EACA;EACA,QAAQ,gBAAgB;CAC1B;CACA,IAAI,WAAW,SAAS;EACtB,KAAK,SAAS;EACd,MAAM,MAAM,IAAI,QAAQ,KAAK,IA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