@hostclubeos/miraos 0.0.1-beta → 0.0.5-beta

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 (417) hide show
  1. package/bundled/app-store-compliance/SKILL.md +58 -0
  2. package/bundled/bug-hunter/NOTICE +17 -0
  3. package/bundled/bug-hunter/SKILL.md +65 -0
  4. package/bundled/superpowers/NOTICE +11 -0
  5. package/bundled/superpowers/SKILL.md +43 -0
  6. package/bundled/superpowers/references/brainstorming/SKILL.md +316 -0
  7. package/bundled/superpowers/references/brainstorming/builder-check-prompt.md +23 -0
  8. package/bundled/superpowers/references/brainstorming/scripts/frame-template.html +213 -0
  9. package/bundled/superpowers/references/brainstorming/scripts/helper.js +167 -0
  10. package/bundled/superpowers/references/brainstorming/scripts/server.cjs +723 -0
  11. package/bundled/superpowers/references/brainstorming/scripts/start-server.sh +216 -0
  12. package/bundled/superpowers/references/brainstorming/scripts/stop-server.sh +120 -0
  13. package/bundled/superpowers/references/brainstorming/visual-companion.md +299 -0
  14. package/bundled/superpowers/references/diagnosing-superpowers/SKILL.md +120 -0
  15. package/bundled/superpowers/references/diagnosing-superpowers/prompts/analyst-common.md +38 -0
  16. package/bundled/superpowers/references/diagnosing-superpowers/prompts/cost-and-time.md +28 -0
  17. package/bundled/superpowers/references/diagnosing-superpowers/prompts/plan-adherence.md +29 -0
  18. package/bundled/superpowers/references/diagnosing-superpowers/prompts/quality-evidence.md +26 -0
  19. package/bundled/superpowers/references/diagnosing-superpowers/prompts/repeated-work.md +30 -0
  20. package/bundled/superpowers/references/diagnosing-superpowers/prompts/request-conflicts.md +20 -0
  21. package/bundled/superpowers/references/diagnosing-superpowers/prompts/scrub-audit.md +33 -0
  22. package/bundled/superpowers/references/diagnosing-superpowers/prompts/scrub.md +29 -0
  23. package/bundled/superpowers/references/diagnosing-superpowers/prompts/similar-session.md +38 -0
  24. package/bundled/superpowers/references/diagnosing-superpowers/prompts/skill-timeline.md +30 -0
  25. package/bundled/superpowers/references/diagnosing-superpowers/prompts/stumbles.md +28 -0
  26. package/bundled/superpowers/references/diagnosing-superpowers/references/context-safety.md +22 -0
  27. package/bundled/superpowers/references/diagnosing-superpowers/references/github-issues.md +47 -0
  28. package/bundled/superpowers/references/diagnosing-superpowers/references/redaction-policy.md +34 -0
  29. package/bundled/superpowers/references/diagnosing-superpowers/references/session-discovery.md +31 -0
  30. package/bundled/superpowers/references/diagnosing-superpowers/templates/bundle-README.md +77 -0
  31. package/bundled/superpowers/references/diagnosing-superpowers/templates/case.md +64 -0
  32. package/bundled/superpowers/references/diagnosing-superpowers/templates/issue.md +70 -0
  33. package/bundled/superpowers/references/diagnosing-superpowers/templates/report.md +82 -0
  34. package/bundled/superpowers/references/dispatching-parallel-agents/SKILL.md +167 -0
  35. package/bundled/superpowers/references/executing-plans/SKILL.md +323 -0
  36. package/bundled/superpowers/references/executing-plans/scripts/task-done +55 -0
  37. package/bundled/superpowers/references/executing-plans/scripts/task-start +32 -0
  38. package/bundled/superpowers/references/finishing-a-development-branch/SKILL.md +225 -0
  39. package/bundled/superpowers/references/receiving-code-review/SKILL.md +205 -0
  40. package/bundled/superpowers/references/requesting-code-review/SKILL.md +95 -0
  41. package/bundled/superpowers/references/requesting-code-review/code-reviewer.md +198 -0
  42. package/bundled/superpowers/references/subagent-driven-development/SKILL.md +339 -0
  43. package/bundled/superpowers/references/subagent-driven-development/implementer-prompt.md +154 -0
  44. package/bundled/superpowers/references/subagent-driven-development/re-review-prompt.md +116 -0
  45. package/bundled/superpowers/references/subagent-driven-development/references/batching.md +11 -0
  46. package/bundled/superpowers/references/subagent-driven-development/references/cannot-verify.md +10 -0
  47. package/bundled/superpowers/references/subagent-driven-development/references/final-review.md +49 -0
  48. package/bundled/superpowers/references/subagent-driven-development/references/fix-loop.md +77 -0
  49. package/bundled/superpowers/references/subagent-driven-development/references/handling-reports.md +15 -0
  50. package/bundled/superpowers/references/subagent-driven-development/references/preflight.md +26 -0
  51. package/bundled/superpowers/references/subagent-driven-development/references/resuming.md +12 -0
  52. package/bundled/superpowers/references/subagent-driven-development/scripts/review-package +64 -0
  53. package/bundled/superpowers/references/subagent-driven-development/scripts/sdd-repo +54 -0
  54. package/bundled/superpowers/references/subagent-driven-development/scripts/sdd-workspace +110 -0
  55. package/bundled/superpowers/references/subagent-driven-development/scripts/task-brief +108 -0
  56. package/bundled/superpowers/references/subagent-driven-development/task-reviewer-prompt.md +209 -0
  57. package/bundled/superpowers/references/systematic-debugging/SKILL.md +283 -0
  58. package/bundled/superpowers/references/systematic-debugging/condition-based-waiting-example.ts +159 -0
  59. package/bundled/superpowers/references/systematic-debugging/condition-based-waiting.md +115 -0
  60. package/bundled/superpowers/references/systematic-debugging/defense-in-depth.md +122 -0
  61. package/bundled/superpowers/references/systematic-debugging/find-polluter.sh +72 -0
  62. package/bundled/superpowers/references/systematic-debugging/root-cause-tracing.md +169 -0
  63. package/bundled/superpowers/references/test-driven-development/SKILL.md +330 -0
  64. package/bundled/superpowers/references/test-driven-development/writing-good-tests.md +198 -0
  65. package/bundled/superpowers/references/using-git-worktrees/SKILL.md +167 -0
  66. package/bundled/superpowers/references/using-superpowers/SKILL.md +65 -0
  67. package/bundled/superpowers/references/using-superpowers/references/antigravity-tools.md +23 -0
  68. package/bundled/superpowers/references/using-superpowers/references/claude-code-tools.md +29 -0
  69. package/bundled/superpowers/references/using-superpowers/references/codex-tools.md +108 -0
  70. package/bundled/superpowers/references/using-superpowers/references/gemini-tools.md +63 -0
  71. package/bundled/superpowers/references/using-superpowers/references/hermes-tools.md +56 -0
  72. package/bundled/superpowers/references/using-superpowers/references/muse-tools.md +35 -0
  73. package/bundled/superpowers/references/using-superpowers/references/pi-tools.md +16 -0
  74. package/bundled/superpowers/references/verification-before-completion/SKILL.md +120 -0
  75. package/bundled/superpowers/references/writing-plans/SKILL.md +204 -0
  76. package/bundled/superpowers/references/writing-skills/SKILL.md +399 -0
  77. package/bundled/superpowers/references/writing-skills/references/CLAUDE_MD_TESTING.md +189 -0
  78. package/bundled/superpowers/references/writing-skills/references/anthropic-best-practices.md +1150 -0
  79. package/bundled/superpowers/references/writing-skills/references/bulletproofing.md +80 -0
  80. package/bundled/superpowers/references/writing-skills/references/discovery.md +201 -0
  81. package/bundled/superpowers/references/writing-skills/references/flowcharts.md +37 -0
  82. package/bundled/superpowers/references/writing-skills/references/graphviz-conventions.dot +172 -0
  83. package/bundled/superpowers/references/writing-skills/references/persuasion-principles.md +187 -0
  84. package/bundled/superpowers/references/writing-skills/references/testing-skills-with-subagents.md +384 -0
  85. package/bundled/superpowers/references/writing-skills/render-graphs.js +169 -0
  86. package/bundled/swarm/SKILL.md +47 -0
  87. package/chunks/{MaxSizedBox-4XZJGJCR.js → MaxSizedBox-CBUPHLMW.js} +1 -1
  88. package/chunks/{StandaloneSessionPicker-YUWFI6WT.js → StandaloneSessionPicker-EXZJQKTK.js} +1 -1
  89. package/chunks/{acp-subagent-executor-7BGJRBWA.js → acp-subagent-executor-BMIXP52W.js} +1 -1
  90. package/chunks/{acpAgent-DO3DYSKS.js → acpAgent-UHWDA3W7.js} +3 -3
  91. package/chunks/{advisor-ZMSGPCRF.js → advisor-5RUG3VFZ.js} +1 -1
  92. package/chunks/{agent-ZMZLTEBG.js → agent-SGQ7AEZI.js} +1 -1
  93. package/chunks/{agent-headless-5COOZKMA.js → agent-headless-ZGCZ2DA7.js} +1 -1
  94. package/chunks/{agent-host-client-L2ROWXVT.js → agent-host-client-HY5GPSHM.js} +1 -1
  95. package/chunks/{agent-host-connections-A4UGANXV.js → agent-host-connections-KGTBS37X.js} +1 -1
  96. package/chunks/{autofix-pr-N3M7IGHT.js → autofix-pr-E62FC67X.js} +1 -1
  97. package/chunks/{autofix-pr-VWZPABZQ.js → autofix-pr-TRI4NMYI.js} +1 -1
  98. package/chunks/{batch-RTO7FWGG.js → batch-OUC6FGCQ.js} +1 -1
  99. package/chunks/{bridge-ZZ2GF4DM.js → bridge-FLEIBB5V.js} +1 -1
  100. package/chunks/{bwrap-execution-6NIUP47A.js → bwrap-execution-VLHJWP4O.js} +1 -1
  101. package/chunks/{channel-settings-store-Y5HXLPQF.js → channel-settings-store-QG6HREVH.js} +1 -1
  102. package/chunks/{chunk-FXFSZ7QF.js → chunk-23543L6E.js} +1 -1
  103. package/chunks/{chunk-NM5TUAPJ.js → chunk-2GVKPBW5.js} +1 -1
  104. package/chunks/{chunk-DPKN7TSL.js → chunk-2QYFSBJY.js} +1 -1
  105. package/chunks/{chunk-NMB6IBA7.js → chunk-2TDRP3IX.js} +1 -1
  106. package/chunks/{chunk-ZE5YXIAJ.js → chunk-2VW4HXVF.js} +1 -1
  107. package/chunks/{chunk-FQXNP7EE.js → chunk-2ZWVSKPK.js} +1 -1
  108. package/chunks/{chunk-SBFKWNC3.js → chunk-3GJ56V2J.js} +1 -1
  109. package/chunks/{chunk-7JU5ZJJ7.js → chunk-3KFLO5W3.js} +1 -1
  110. package/chunks/{chunk-P4ZCOMZS.js → chunk-3MBYQYPC.js} +1 -1
  111. package/chunks/{chunk-FHGGT7VE.js → chunk-4346FNTB.js} +1 -1
  112. package/chunks/{chunk-IKQHFQ74.js → chunk-4GNHXVJZ.js} +1 -1
  113. package/chunks/{chunk-2FD2BYUZ.js → chunk-4IVYVCCU.js} +3 -3
  114. package/chunks/{chunk-ZEIWENJU.js → chunk-4KIFAVR2.js} +1 -1
  115. package/chunks/{chunk-YSWDQYJU.js → chunk-4MGTY3CJ.js} +1 -1
  116. package/chunks/{chunk-3LS3HVJA.js → chunk-4WYKHP7Q.js} +1 -1
  117. package/chunks/{chunk-MWGGXT4P.js → chunk-56PVVXUG.js} +1 -1
  118. package/chunks/{chunk-J4KLD52D.js → chunk-62DMHXLL.js} +1 -1
  119. package/chunks/{chunk-TALEJQWF.js → chunk-66DZADDA.js} +1 -1
  120. package/chunks/{chunk-GOEBFMO2.js → chunk-6RDYPRV6.js} +1 -1
  121. package/chunks/{chunk-5HNCGRMZ.js → chunk-724YPZRX.js} +1 -1
  122. package/chunks/{chunk-HA6K73R7.js → chunk-744QTJR2.js} +2 -2
  123. package/chunks/{chunk-SCQWVHLA.js → chunk-7F5IYTVE.js} +1 -1
  124. package/chunks/{chunk-TDM5PKRC.js → chunk-7VP4KALB.js} +1 -1
  125. package/chunks/{chunk-QWOBTVIO.js → chunk-7W5DOBKY.js} +1 -1
  126. package/chunks/{chunk-UL5A63VS.js → chunk-AE6E2YKY.js} +1 -1
  127. package/chunks/{chunk-J2DA7XAM.js → chunk-AIAYQAPA.js} +1 -1
  128. package/chunks/{chunk-3XFUS57Z.js → chunk-AIGBQN6R.js} +1 -1
  129. package/chunks/{chunk-BVYNPYGP.js → chunk-AJ75BPTA.js} +6 -1
  130. package/chunks/{chunk-LEZ3AZJI.js → chunk-ATVRF62A.js} +1 -1
  131. package/chunks/{chunk-DW4HTZVZ.js → chunk-BX3KM7OK.js} +1 -1
  132. package/chunks/{chunk-4UVQYN33.js → chunk-CUY6CVSL.js} +1 -1
  133. package/chunks/{chunk-RRXNG7AI.js → chunk-D3QZNIFB.js} +6 -6
  134. package/chunks/{chunk-5PZ4EFXH.js → chunk-D3YOXHQF.js} +1 -1
  135. package/chunks/{chunk-L66KXTVG.js → chunk-DABLVQXV.js} +1 -1
  136. package/chunks/{chunk-6AA5DYMC.js → chunk-DMM5LJWL.js} +2 -2
  137. package/chunks/{chunk-TWCQNRBQ.js → chunk-DNYXZVBT.js} +1 -1
  138. package/chunks/{chunk-HCIFQTQ4.js → chunk-E6LRCLLE.js} +2 -2
  139. package/chunks/{chunk-L44CUCID.js → chunk-EF3HUB7S.js} +1 -1
  140. package/chunks/{chunk-WQEJL3HN.js → chunk-EW3EVEYN.js} +1 -1
  141. package/chunks/{chunk-RMATGKAM.js → chunk-FC7SJIAS.js} +1 -1
  142. package/chunks/{chunk-4NQCOITC.js → chunk-FK5L2WVV.js} +1 -1
  143. package/chunks/{chunk-EMRZ722U.js → chunk-FRADUGRC.js} +1 -1
  144. package/chunks/{chunk-T2O3JMRH.js → chunk-FS67DOZQ.js} +1 -1
  145. package/chunks/{chunk-27MEJGPT.js → chunk-FXANOHXI.js} +5 -5
  146. package/chunks/{chunk-VCLKQDTV.js → chunk-GLQWA4W2.js} +1 -1
  147. package/chunks/{chunk-STPD3MIX.js → chunk-GOZ5FAUV.js} +1 -1
  148. package/chunks/{chunk-POX6TDCX.js → chunk-GTQULDIL.js} +1 -1
  149. package/chunks/{chunk-SR6MFJYO.js → chunk-GY4ID3EB.js} +1 -1
  150. package/chunks/{chunk-IJDGB3GP.js → chunk-H65ZVST6.js} +1 -1
  151. package/chunks/{chunk-6MWOHNU7.js → chunk-HASJX2YS.js} +1 -1
  152. package/chunks/{chunk-TJVI2L24.js → chunk-HSN5QUS7.js} +1 -1
  153. package/chunks/{chunk-7A42KF7G.js → chunk-HZ4L4MDM.js} +1 -1
  154. package/chunks/{chunk-WXVU3W2Q.js → chunk-IC42HQCH.js} +1 -1
  155. package/chunks/{chunk-NSA4ZO4V.js → chunk-IF3SWUYT.js} +1 -1
  156. package/chunks/{chunk-AGVUBA2V.js → chunk-J773THNP.js} +1 -1
  157. package/chunks/{chunk-ETYFIFMT.js → chunk-JDHMSERR.js} +1 -1
  158. package/chunks/{chunk-GNJTCOX3.js → chunk-JIQVUYBI.js} +1 -1
  159. package/chunks/{chunk-F5LMCQ2K.js → chunk-JJDF5FHA.js} +1 -1
  160. package/chunks/{chunk-TSI3G7JM.js → chunk-JQOLNQQN.js} +1 -1
  161. package/chunks/{chunk-ERUWCPGL.js → chunk-JQYPRANX.js} +1 -1
  162. package/chunks/{chunk-IW5GJAOR.js → chunk-K7KY7FIB.js} +1 -1
  163. package/chunks/{chunk-P2CUOX2Q.js → chunk-K7VOBDFT.js} +1 -1
  164. package/chunks/{chunk-SNGI5OD7.js → chunk-KK6SQPYG.js} +1 -1
  165. package/chunks/{chunk-HVAOQB42.js → chunk-KNW2OD46.js} +1 -1
  166. package/chunks/{chunk-GQSVGUOU.js → chunk-KP77CL5U.js} +1 -1
  167. package/chunks/{chunk-G6EIN5FW.js → chunk-KYK53GFP.js} +1 -1
  168. package/chunks/{chunk-432LPP2J.js → chunk-MQWKOOSR.js} +1 -1
  169. package/chunks/{chunk-XMIUDKGO.js → chunk-MUS4ADP7.js} +2 -2
  170. package/chunks/{chunk-IVHSWYWP.js → chunk-MYS5NQXO.js} +1 -1
  171. package/chunks/{chunk-FCOVJQX7.js → chunk-N4RIISOE.js} +1 -1
  172. package/chunks/{chunk-FCB7X7TI.js → chunk-NCBA52SB.js} +1 -1
  173. package/chunks/{chunk-GNV3UOVR.js → chunk-NGH27AWP.js} +1 -1
  174. package/chunks/{chunk-YM7CPT6W.js → chunk-NKWATWMD.js} +2 -2
  175. package/chunks/{chunk-R4HUU27E.js → chunk-NVD63O5H.js} +1 -1
  176. package/chunks/{chunk-WNT3ND65.js → chunk-NYM67KKZ.js} +2 -2
  177. package/chunks/{chunk-F6MHDBMX.js → chunk-O6Z3KO6R.js} +1 -1
  178. package/chunks/{chunk-RPMW55YH.js → chunk-OV2J3OED.js} +1 -1
  179. package/chunks/{chunk-RGOWOT3Z.js → chunk-P42MFWO2.js} +1 -1
  180. package/chunks/{chunk-XREDCQA5.js → chunk-P5543CFV.js} +1 -1
  181. package/chunks/{chunk-RHFRL6CB.js → chunk-PFECH6U6.js} +1 -1
  182. package/chunks/{chunk-3SQ76U4F.js → chunk-PFKTTUGS.js} +6 -6
  183. package/chunks/{chunk-XU5D2FKZ.js → chunk-PGKFDR73.js} +1 -1
  184. package/chunks/{chunk-LTUKVA3O.js → chunk-PQOQONLN.js} +1 -1
  185. package/chunks/{chunk-E7PL6EYK.js → chunk-PVHBBTAU.js} +1 -1
  186. package/chunks/{chunk-SKLO2WHR.js → chunk-PXBJPUGN.js} +1 -1
  187. package/chunks/{chunk-BCY6VYWQ.js → chunk-QEIX42MZ.js} +1 -1
  188. package/chunks/{chunk-MEUP65FI.js → chunk-QTCO5I4C.js} +1 -1
  189. package/chunks/{chunk-3KM4JL4Y.js → chunk-RBA3TP7L.js} +1 -1
  190. package/chunks/{chunk-R3H2AN4X.js → chunk-RKFNQQNA.js} +1 -1
  191. package/chunks/{chunk-RBYRJBQV.js → chunk-RNPVWQ3V.js} +1 -1
  192. package/chunks/{chunk-G7KBHT53.js → chunk-RRMTSVGU.js} +1 -1
  193. package/chunks/{chunk-W5YMSMZG.js → chunk-RWFOQXPU.js} +1 -1
  194. package/chunks/{chunk-R32F7IAM.js → chunk-SCHCTQCG.js} +1 -1
  195. package/chunks/{chunk-MC47YWMG.js → chunk-SHKSVOTG.js} +1 -1
  196. package/chunks/{chunk-YPG2SMZS.js → chunk-SK3QOQR4.js} +1 -1
  197. package/chunks/{chunk-5SFSOCHV.js → chunk-T3A53XMM.js} +1 -1
  198. package/chunks/{chunk-3SCCBDDE.js → chunk-T5PDEAU5.js} +1 -1
  199. package/chunks/{chunk-PIHZPQYO.js → chunk-T5XGTSQU.js} +1 -1
  200. package/chunks/{chunk-J4SZAKAX.js → chunk-TFITRCIC.js} +1 -1
  201. package/chunks/{chunk-THO23XWK.js → chunk-TLZM3DMY.js} +1 -1
  202. package/chunks/{chunk-Y6PDX4C4.js → chunk-TU5QHOJC.js} +1 -1
  203. package/chunks/{chunk-FFE5LIA6.js → chunk-TWJ4XBED.js} +1 -1
  204. package/chunks/{chunk-K6I2EP3G.js → chunk-UNJYVYTC.js} +1 -1
  205. package/chunks/{chunk-KSWZ6FTA.js → chunk-UOYXBAN7.js} +1 -1
  206. package/chunks/{chunk-GGXMABF2.js → chunk-USR2Y7B3.js} +1 -1
  207. package/chunks/{chunk-6O6IED5M.js → chunk-UWMLSAQY.js} +1 -1
  208. package/chunks/{chunk-OGPOUNG7.js → chunk-V5Z6OEKJ.js} +1 -1
  209. package/chunks/{chunk-MWMYT4PK.js → chunk-VBJV7T47.js} +1 -1
  210. package/chunks/{chunk-BAHNLZJQ.js → chunk-VF2UWWI2.js} +1 -1
  211. package/chunks/{chunk-MVF4MYTY.js → chunk-VJUTDS6C.js} +1 -1
  212. package/chunks/{chunk-A42T2FGM.js → chunk-W2ZVZ6LS.js} +1 -1
  213. package/chunks/{chunk-V6ZOOFZ3.js → chunk-W6IOHGWW.js} +1 -1
  214. package/chunks/{chunk-I5FHTXDB.js → chunk-WC72OWF2.js} +2 -2
  215. package/chunks/{chunk-XW5ZOTPK.js → chunk-WJLHLFIR.js} +1 -1
  216. package/chunks/{chunk-T4P4FF3I.js → chunk-WZTO3EYG.js} +1 -1
  217. package/chunks/{chunk-IUUWYEF5.js → chunk-XZNF4YNN.js} +1 -1
  218. package/chunks/{chunk-N7OJZ7AS.js → chunk-YN6WXB6B.js} +1 -1
  219. package/chunks/{chunk-PJUXHD2F.js → chunk-YVN32EUM.js} +1 -1
  220. package/chunks/{chunk-B7XMOQLO.js → chunk-Z4JY3HGO.js} +1 -1
  221. package/chunks/{chunk-AIIV662S.js → chunk-ZOWMHZWO.js} +1 -1
  222. package/chunks/{codex-subagent-executor-AR4Q5IHV.js → codex-subagent-executor-UCDGQFTR.js} +1 -1
  223. package/chunks/{config-utils-5S5PZQ5S.js → config-utils-Z6F4DVLG.js} +1 -1
  224. package/chunks/{contextCommand-YEZP3P4L.js → contextCommand-HMVZT56Y.js} +1 -1
  225. package/chunks/{core-runtime-LISS3YR4.js → core-runtime-AV7CJXOL.js} +1 -1
  226. package/chunks/{create-sub-session-FCB4YENT.js → create-sub-session-NNKVHZKT.js} +1 -1
  227. package/chunks/{cron-create-E2PZGYSL.js → cron-create-HWZDFVPA.js} +1 -1
  228. package/chunks/{daemon-git-worktree-guard-23KFZWC5.js → daemon-git-worktree-guard-Q3C45X7T.js} +1 -1
  229. package/chunks/{daemon-status-provider-KU7B5BBQ.js → daemon-status-provider-F6KB2LNG.js} +1 -1
  230. package/chunks/{daemon-trust-policy-FL3DDA6T.js → daemon-trust-policy-6D4KJANB.js} +1 -1
  231. package/chunks/{daemon-trust-policy-monitor-FCCK3YHW.js → daemon-trust-policy-monitor-BZ46W4IA.js} +1 -1
  232. package/chunks/{deferred-core-runtime-BCJU6YQI.js → deferred-core-runtime-YC5XIWEI.js} +1 -1
  233. package/chunks/{display-image-ZHNLZCK7.js → display-image-LAGHQ4RY.js} +1 -1
  234. package/chunks/{edit-SXQ5HK4W.js → edit-LOWDEKPX.js} +1 -1
  235. package/chunks/{enterPlanMode-NX6SOALP.js → enterPlanMode-NGSATDRH.js} +1 -1
  236. package/chunks/{environment-GFCR2C43.js → environment-CVIB5DW4.js} +1 -1
  237. package/chunks/{errors-WZJPHSEP.js → errors-USKSVZFO.js} +1 -1
  238. package/chunks/{execute-sandbox-VZ4OKFCC.js → execute-sandbox-KNRRYQ52.js} +1 -1
  239. package/chunks/{execution-sandbox-config-XQNSHI7G.js → execution-sandbox-config-XBW3PXDA.js} +1 -1
  240. package/chunks/{execution-tool-XPHUDQJ4.js → execution-tool-QSJLRU5N.js} +1 -1
  241. package/chunks/{execution-worker-6RXFIQH4.js → execution-worker-TQEIC4AJ.js} +1 -1
  242. package/chunks/{exitPlanMode-LP3D7M5M.js → exitPlanMode-AW2HOTIK.js} +1 -1
  243. package/chunks/{fast-path-2D5QZRQW.js → fast-path-DWPD5EGQ.js} +1 -1
  244. package/chunks/{glob-JFH2DTI7.js → glob-7U6FQSWZ.js} +1 -1
  245. package/chunks/{goal-tools-UL3O364Y.js → goal-tools-5ZB6GPCJ.js} +1 -1
  246. package/chunks/{handleAutoUpdate-MYD2LZXQ.js → handleAutoUpdate-MLUFTWFP.js} +1 -1
  247. package/chunks/{i18n-LDINZEX3.js → i18n-QAPQLOC3.js} +1 -1
  248. package/chunks/{initializer-LLXI4EVO.js → initializer-B27IZ7K4.js} +1 -1
  249. package/chunks/{installationInfo-4FS5ROEO.js → installationInfo-SAMHABWV.js} +1 -1
  250. package/chunks/{interactive-mod-session-UFB2CURW.js → interactive-mod-session-7LQ5CYUR.js} +1 -1
  251. package/chunks/{landlock-execution-3T5Y3SFY.js → landlock-execution-2BJ56FDV.js} +1 -1
  252. package/chunks/{list-45PFXWOV.js → list-TDMJQDQO.js} +1 -1
  253. package/chunks/{llm-VIFUT34L.js → llm-RBI7KXDE.js} +4 -4
  254. package/chunks/{loadedSettingsAdapter-3MNB7PHB.js → loadedSettingsAdapter-ZQK5KMEW.js} +1 -1
  255. package/chunks/{local-TBDN3BOU.js → local-HSG47CNJ.js} +1 -1
  256. package/chunks/{local-execution-environment-PNRU2WTJ.js → local-execution-environment-WJVCE26F.js} +1 -1
  257. package/chunks/{loggingContentGenerator-JA22TIC4.js → loggingContentGenerator-ALSG42YA.js} +1 -1
  258. package/chunks/{loop-wakeup-BXKFVB7H.js → loop-wakeup-LFU4LDJM.js} +1 -1
  259. package/chunks/{manage-memory-BMKA64KG.js → manage-memory-FBL6CHX2.js} +1 -1
  260. package/chunks/{managed-execution-engine-PVXRANOE.js → managed-execution-engine-FX7FDAWW.js} +1 -1
  261. package/chunks/{managed-local-serve-H5BEBXVR.js → managed-local-serve-YE4JDFNP.js} +1 -1
  262. package/chunks/{managed-npm-update-JGC5W6SL.js → managed-npm-update-2MKV7UOI.js} +1 -1
  263. package/chunks/{managed-runtime-attestation-worker-KCUQIRVR.js → managed-runtime-attestation-worker-DBAHM5MN.js} +1 -1
  264. package/chunks/{managed-runtime-bootstrap-HCN3NINM.js → managed-runtime-bootstrap-SHEXUEZN.js} +1 -1
  265. package/chunks/{managed-runtime-session-worker-G4TB3S5M.js → managed-runtime-session-worker-YN4KML7A.js} +1 -1
  266. package/chunks/{managed-runtime-ssh-worker-4WSWY2MH.js → managed-runtime-ssh-worker-BZNJV7IB.js} +1 -1
  267. package/chunks/{managed-session-authority-H5USCQ6W.js → managed-session-authority-MFEINLXC.js} +1 -1
  268. package/chunks/{mcp-WXNSQID6.js → mcp-TS5PX5FY.js} +1 -1
  269. package/chunks/{memory-E5SQH3NJ.js → memory-JTDN5AEA.js} +1 -1
  270. package/chunks/{model-call-collection-PULBNXXQ.js → model-call-collection-TNBMD3YL.js} +1 -1
  271. package/chunks/{model-configuration-SJEIOQGZ.js → model-configuration-6KTQQTMO.js} +1 -1
  272. package/chunks/{modelConfigUtils-WJ27GPGB.js → modelConfigUtils-LCZZ3EQU.js} +1 -1
  273. package/chunks/{monitor-N25QQU7J.js → monitor-KCCNIKLE.js} +1 -1
  274. package/chunks/{nonInteractiveCli-E6RLP7AG.js → nonInteractiveCli-BXHX6EIU.js} +1 -1
  275. package/chunks/{nonInteractiveToolExecutor-Z5JBEIAW.js → nonInteractiveToolExecutor-R5CTTWKD.js} +1 -1
  276. package/chunks/{notebook-edit-WVLO2EUN.js → notebook-edit-KIWE2XOA.js} +1 -1
  277. package/chunks/{omni-RKVYBBQI.js → omni-IFTMWBMU.js} +1 -1
  278. package/chunks/{openaiContentGenerator-2G2XB3DF.js → openaiContentGenerator-XP3VPU6C.js} +1 -1
  279. package/chunks/{openaiResponsesContentGenerator-344BTMHF.js → openaiResponsesContentGenerator-ZJ6C22EA.js} +1 -1
  280. package/chunks/{pidfile-KS6QFQIJ.js → pidfile-42P24JIA.js} +1 -1
  281. package/chunks/{processUtils-U45GFMXN.js → processUtils-I2XOO5U2.js} +1 -1
  282. package/chunks/{prompt-terminal-ledger-HAK6RGOC.js → prompt-terminal-ledger-7EW46VQ4.js} +1 -1
  283. package/chunks/{reactive-degrade-S7C6GXHH.js → reactive-degrade-O4JO7MOX.js} +1 -1
  284. package/chunks/{read-file-RG5ZNNCH.js → read-file-VGC4O7F2.js} +1 -1
  285. package/chunks/{record-source-6J47E2DW.js → record-source-VX26ZO6I.js} +1 -1
  286. package/chunks/{request-shutdown-SCU5TN5V.js → request-shutdown-P7227UEF.js} +1 -1
  287. package/chunks/{resumeHistoryUtils-CDDEU4RO.js → resumeHistoryUtils-QMVIHQRW.js} +1 -1
  288. package/chunks/{review-H6FLIVJV.js → review-PC4IDLCG.js} +1 -1
  289. package/chunks/{ripGrep-XEDOYGPA.js → ripGrep-JY4PZABK.js} +1 -1
  290. package/chunks/{run-qwen-serve-ODBFOM6H.js → run-qwen-serve-XRWVWOZK.js} +1 -1
  291. package/chunks/{runtime-SCINDTK2.js → runtime-OL7B72CH.js} +1 -1
  292. package/chunks/{runtime-shell-policy-77EFLSNG.js → runtime-shell-policy-TXAWAOBK.js} +1 -1
  293. package/chunks/{sandboxConfig-WE7GXTES.js → sandboxConfig-EJTMWZHD.js} +1 -1
  294. package/chunks/{scheduled-tasks-4HL6GKQ4.js → scheduled-tasks-XQSZWZXG.js} +1 -1
  295. package/chunks/{scheduler-ETHKOB4B.js → scheduler-3TIRZEVB.js} +1 -1
  296. package/chunks/{search-memory-R4O5AIEV.js → search-memory-P5KOTUVV.js} +1 -1
  297. package/chunks/{send-message-SBQSBXDW.js → send-message-KFSKFXLX.js} +1 -1
  298. package/chunks/{serve-TRAGNNK6.js → serve-JCUT4WK7.js} +1 -1
  299. package/chunks/{server-BXVHT3XW.js → server-HMTRZJF7.js} +3 -3
  300. package/chunks/{session-A6NV4RLU.js → session-RGLZU6KY.js} +1 -1
  301. package/chunks/{session-attachments-root-WU56VFQN.js → session-attachments-root-O3YQ7HWD.js} +1 -1
  302. package/chunks/{session-execution-engine-selector-MG2ZDK25.js → session-execution-engine-selector-LZBHS3UO.js} +1 -1
  303. package/chunks/{session-pr-refresh-HQOHASVU.js → session-pr-refresh-L5Z5WCXS.js} +1 -1
  304. package/chunks/{sessionService-XBFZRVW6.js → sessionService-MMPZUN5X.js} +1 -1
  305. package/chunks/{settings-HDG72SDU.js → settings-7PYHXPN4.js} +1 -1
  306. package/chunks/{shell-VNVPTXQO.js → shell-E6QLKRVU.js} +1 -1
  307. package/chunks/{skill-4VDNIMOV.js → skill-55IZUUM5.js} +1 -1
  308. package/chunks/{skill-settings-VKC2ATCK.js → skill-settings-A2M5BPH7.js} +1 -1
  309. package/chunks/{spawnChannel-RB5Q6Z4U.js → spawnChannel-KWU26CB7.js} +1 -1
  310. package/chunks/{standalone-update-QDH63IIS.js → standalone-update-32WYZ3BJ.js} +1 -1
  311. package/chunks/{start-opentui-ui-VULNQJ3L.js → start-opentui-ui-YNTPK7LX.js} +2 -2
  312. package/chunks/{startInteractiveUI-XZATGHLR.js → startInteractiveUI-MWA2VYTJ.js} +2 -2
  313. package/chunks/{task-create-ODLLJ5EF.js → task-create-67YBESBR.js} +1 -1
  314. package/chunks/{task-update-ZNWF5QPF.js → task-update-DLBXOE5R.js} +1 -1
  315. package/chunks/{team-create-CUJXJ2ZS.js → team-create-ARICYIQB.js} +1 -1
  316. package/chunks/{team-plan-approval-36LS5SZD.js → team-plan-approval-JPRE6Q3R.js} +1 -1
  317. package/chunks/{terminal-image-renderer-FYGH5GYJ.js → terminal-image-renderer-HVIZ2VNE.js} +1 -1
  318. package/chunks/{theme-manager-AMNU6BMN.js → theme-manager-UEPLIBUP.js} +1 -1
  319. package/chunks/{tool-call-E635LKSC.js → tool-call-EFJKXI3Z.js} +1 -1
  320. package/chunks/{tool-result-media-USCQTGHC.js → tool-result-media-LMIYNXSD.js} +1 -1
  321. package/chunks/{tool-search-FNTAT2ZW.js → tool-search-D7HQTRQG.js} +1 -1
  322. package/chunks/{total-session-admission-6P5YNVII.js → total-session-admission-67QMR44O.js} +1 -1
  323. package/chunks/{trustedFolders-7SPIYZSS.js → trustedFolders-HARYVS3F.js} +1 -1
  324. package/chunks/{update-relaunch-ZYID7ZKA.js → update-relaunch-NVNPOK5J.js} +1 -1
  325. package/chunks/{updateCheck-A3JUVWQV.js → updateCheck-7NMXUCTN.js} +1 -1
  326. package/chunks/{upload-config-DT3IQPC7.js → upload-config-W2SICJ32.js} +1 -1
  327. package/chunks/{useAutoAcceptIndicator-OS64SJOW.js → useAutoAcceptIndicator-ELMIP4TJ.js} +1 -1
  328. package/chunks/{validateNonInterActiveAuth-SJLXPGT4.js → validateNonInterActiveAuth-3433WFLE.js} +1 -1
  329. package/chunks/{version-CD2O2AJ7.js → version-XCFKTEY3.js} +1 -1
  330. package/chunks/{web-fetch-CQZMLBDV.js → web-fetch-537RS6IX.js} +1 -1
  331. package/chunks/{web-search-47YZU3PO.js → web-search-O27MYFSW.js} +1 -1
  332. package/chunks/{workflow-ROHRWGL5.js → workflow-6QF4RMYM.js} +1 -1
  333. package/chunks/{workflow-ancestor-trust-YSFNC6J5.js → workflow-ancestor-trust-CABLU3VV.js} +1 -1
  334. package/chunks/{workspace-agents-P4T5564B.js → workspace-agents-5WP3PY7W.js} +1 -1
  335. package/chunks/{workspace-providers-status-GZOJR5XX.js → workspace-providers-status-7G2EJJEO.js} +1 -1
  336. package/chunks/{workspace-recovery-worker-C4KTT7J5.js → workspace-recovery-worker-ICCIDEWU.js} +1 -1
  337. package/chunks/{workspace-registration-store-2WDVL42M.js → workspace-registration-store-WHXMNQQQ.js} +1 -1
  338. package/chunks/{workspace-registry-2V2LYFXO.js → workspace-registry-NXBODLYH.js} +1 -1
  339. package/chunks/{workspace-runtime-coordinator-7OH4M6FV.js → workspace-runtime-coordinator-CJXS273B.js} +1 -1
  340. package/chunks/{workspace-service-353F3S2A.js → workspace-service-HUDE2RXN.js} +1 -1
  341. package/chunks/{workspace-skills-status-A5FRCJJF.js → workspace-skills-status-FJC6U62F.js} +1 -1
  342. package/chunks/{workspace-trust-reconciler-N4AKVBD4.js → workspace-trust-reconciler-ZIQ3A5ZB.js} +1 -1
  343. package/chunks/{write-file-XOIVQYGC.js → write-file-652YGG7I.js} +1 -1
  344. package/chunks/{zoom-image-ACTDUJ4C.js → zoom-image-YEH4O74G.js} +1 -1
  345. package/cli.js +2 -2
  346. package/execution-worker.js +1 -1
  347. package/export-transcript-document.js +1 -1
  348. package/package.json +2 -2
  349. package/web-shell/assets/{PierreFilePreview-DR46bTX6.js → PierreFilePreview-DEhWK46v.js} +1 -1
  350. package/web-shell/assets/{SpreadsheetPreview-zgxr-aKy.js → SpreadsheetPreview-C-GgIuPX.js} +1 -1
  351. package/web-shell/assets/{WorkspaceFileBrowser-BEoibHvP.js → WorkspaceFileBrowser-64vDYikf.js} +1 -1
  352. package/web-shell/assets/{abnfDiagram-VCTEODGH-Cba-rfLM.js → abnfDiagram-VCTEODGH-C2WWURam.js} +1 -1
  353. package/web-shell/assets/{agents-route-DexLhLcH.js → agents-route-j5ba59xn.js} +1 -1
  354. package/web-shell/assets/{arc-BLxikpdy.js → arc-Bkr_-GVn.js} +1 -1
  355. package/web-shell/assets/{architectureDiagram-5GKGNRK7-BMaIAoGQ.js → architectureDiagram-5GKGNRK7-D_v_wDDW.js} +1 -1
  356. package/web-shell/assets/{blockDiagram-NRAW4CY4-CGSbuIDn.js → blockDiagram-NRAW4CY4-Csxc3YNo.js} +1 -1
  357. package/web-shell/assets/{c4Diagram-UCG6FXSJ-DVwZ8MO2.js → c4Diagram-UCG6FXSJ-PXryoJCB.js} +1 -1
  358. package/web-shell/assets/channel-6Pj4KPAs.js +1 -0
  359. package/web-shell/assets/{chunk-2Q5K7J3B-BzKDWtZ3.js → chunk-2Q5K7J3B-DwK5UBHI.js} +1 -1
  360. package/web-shell/assets/{chunk-5VM5RSS4-C8SFBHFV.js → chunk-5VM5RSS4-BC1hvD6_.js} +1 -1
  361. package/web-shell/assets/{chunk-F27PBJKO-D8brpDvU.js → chunk-F27PBJKO-iFe0IxfJ.js} +1 -1
  362. package/web-shell/assets/{chunk-G27WJ6UU-Cilx_eO_.js → chunk-G27WJ6UU-ROSuKRxI.js} +1 -1
  363. package/web-shell/assets/{chunk-JWPE2WC7-CeplW23S.js → chunk-JWPE2WC7-CYHS6PxA.js} +1 -1
  364. package/web-shell/assets/{chunk-LCL6LL3I-BUO5XSSe.js → chunk-LCL6LL3I-D5bFMqCy.js} +1 -1
  365. package/web-shell/assets/{chunk-POPQ4Y6H-DPo869nv.js → chunk-POPQ4Y6H-BJh77MGv.js} +1 -1
  366. package/web-shell/assets/{chunk-SVP7TREG-DhfIj0Jt.js → chunk-SVP7TREG-Cs81aYft.js} +1 -1
  367. package/web-shell/assets/{chunk-XXDRQBXY-B72Tsbdi.js → chunk-XXDRQBXY-DqDbN44E.js} +1 -1
  368. package/web-shell/assets/classDiagram-DTDB5LWJ-BaTUuuB8.js +1 -0
  369. package/web-shell/assets/classDiagram-v2-JRS7N3AN-BaTUuuB8.js +1 -0
  370. package/web-shell/assets/{cose-bilkent-JH36ORCC-8EANR5K4.js → cose-bilkent-JH36ORCC-DhjrwADJ.js} +1 -1
  371. package/web-shell/assets/{cynefin-OW5HDTMX-Cj3uoFr9.js → cynefin-OW5HDTMX-Dh7t-_3M.js} +1 -1
  372. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-CHwRYcv9.js → cynefinDiagram-5FMLGOSQ-5J4kto0C.js} +1 -1
  373. package/web-shell/assets/{dagre-3AP2YEHR-B50MDk4E.js → dagre-3AP2YEHR-28AdbIcl.js} +1 -1
  374. package/web-shell/assets/{diagram-S7CK7UJ4-Fbk8W4Ks.js → diagram-S7CK7UJ4-DmksuoIf.js} +1 -1
  375. package/web-shell/assets/{diagram-UQ7AKVKN-CNeEtpni.js → diagram-UQ7AKVKN-DUjgQ8Fg.js} +1 -1
  376. package/web-shell/assets/{diagram-VSXAHHWV-CYXiWI4p.js → diagram-VSXAHHWV-DUe_FpG-.js} +1 -1
  377. package/web-shell/assets/{diagram-VX7I27RA-CF7R7hGA.js → diagram-VX7I27RA-CJJ70teK.js} +1 -1
  378. package/web-shell/assets/{diagram-Z3DM3KII-DZzHpEub.js → diagram-Z3DM3KII-BgABlJO4.js} +1 -1
  379. package/web-shell/assets/{docx-preview-CjpeB47y.js → docx-preview-BMBWboRx.js} +1 -1
  380. package/web-shell/assets/{ebnfDiagram-PWID7BFC-CtH0z2j9.js → ebnfDiagram-PWID7BFC-B3nK_Lh7.js} +1 -1
  381. package/web-shell/assets/{erDiagram-SSCWMZ5O-D51BQ445.js → erDiagram-SSCWMZ5O-DCTdCWlu.js} +1 -1
  382. package/web-shell/assets/{flowDiagram-A5DVABFB-B1-3lJwP.js → flowDiagram-A5DVABFB-CPxk2UUl.js} +1 -1
  383. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-iMw3jNW5.js → ganttDiagram-EL5Y4UJY-WZzMAKht.js} +1 -1
  384. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-D_KI4JVS.js → gitGraphDiagram-WWUBYQGX-DKcO5ugU.js} +1 -1
  385. package/web-shell/assets/{index-D1oIEFvH.js → index-CkRLMu1y.js} +6 -6
  386. package/web-shell/assets/{index-iouf3mnZ.js → index-Dbm3-Fps.js} +1 -1
  387. package/web-shell/assets/{infoDiagram-RXCK75RN-CwG9MQQq.js → infoDiagram-RXCK75RN-CJX5DzdL.js} +1 -1
  388. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-C99w6R-O.js → ishikawaDiagram-5VMMS53U-fF0Id5B6.js} +1 -1
  389. package/web-shell/assets/{journeyDiagram-EYS64GPL--T5XVhJh.js → journeyDiagram-EYS64GPL-BOAezBVe.js} +1 -1
  390. package/web-shell/assets/{kanban-definition-3QL26DDD-Cs-rGYgZ.js → kanban-definition-3QL26DDD-DdNBof9J.js} +1 -1
  391. package/web-shell/assets/{layout-BHU2s0xS.js → layout-CXX3l5w0.js} +1 -1
  392. package/web-shell/assets/{linear-DbLtsa7_.js → linear-Dnaccp-S.js} +1 -1
  393. package/web-shell/assets/{mermaid.core-CTBkTEXb.js → mermaid.core-BzdC3B6T.js} +6 -6
  394. package/web-shell/assets/{mindmap-definition-FBJOCRG2-RWLGqkYd.js → mindmap-definition-FBJOCRG2-D-gMUzLw.js} +1 -1
  395. package/web-shell/assets/{pegDiagram-XKGWAZYB-DIQRWxNr.js → pegDiagram-XKGWAZYB-B9n1WVZq.js} +1 -1
  396. package/web-shell/assets/{pieDiagram-E7YTZNPT-Dg9VHqU0.js → pieDiagram-E7YTZNPT-ok49U0zT.js} +1 -1
  397. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-BFeuB7Iq.js → quadrantDiagram-AXDQQJYC-DJKha-v3.js} +1 -1
  398. package/web-shell/assets/{railroadDiagram-O6MQD6OU-DbO9AYto.js → railroadDiagram-O6MQD6OU-DjL4pl7y.js} +1 -1
  399. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-ClpOYbUE.js → requirementDiagram-EFPCY7ZU-BpmmRw3A.js} +1 -1
  400. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CaHmNc0O.js → sankeyDiagram-P5KCCOFB-KpteHB8X.js} +1 -1
  401. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-4r32bqWv.js → sequenceDiagram-WJ2MYXX4-COMghCpA.js} +1 -1
  402. package/web-shell/assets/{sizeCapture-X5ZJPWSS-CGXqc7rW.js → sizeCapture-X5ZJPWSS-5fEwJD-n.js} +1 -1
  403. package/web-shell/assets/{stateDiagram-HBIQ2CUA-DuAO60my.js → stateDiagram-HBIQ2CUA-CnC7oXvs.js} +1 -1
  404. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-V_cfZFBL.js +1 -0
  405. package/web-shell/assets/{swimlanes-XN3QIQJK-DUQMHZRn.js → swimlanes-XN3QIQJK-bVlhZdve.js} +1 -1
  406. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-25wVg0WL.js +8 -0
  407. package/web-shell/assets/{timeline-definition-24CTP7MA-DNCSPOxv.js → timeline-definition-24CTP7MA-CBvYgMu5.js} +1 -1
  408. package/web-shell/assets/{vennDiagram-4TSXK5OY-Bxh1Z0T6.js → vennDiagram-4TSXK5OY-CUTYvV1j.js} +1 -1
  409. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-D6fuN1bA.js → wardleyDiagram-VM6X3IG4-Djl4gxCB.js} +1 -1
  410. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-DkwTa8kZ.js → xychartDiagram-S5SC5T6Z-BcJZtI2X.js} +1 -1
  411. package/web-shell/index.html +1 -1
  412. package/web-shell/sw.js +1 -1
  413. package/web-shell/assets/channel-CvkbH6SO.js +0 -1
  414. package/web-shell/assets/classDiagram-DTDB5LWJ-DuyseBqE.js +0 -1
  415. package/web-shell/assets/classDiagram-v2-JRS7N3AN-DuyseBqE.js +0 -1
  416. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BjIYif-p.js +0 -1
  417. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-DZB3DqrF.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{DropNoticeThrottle,DropReceiptCoalescer,getPeerControllerRegistryPath,readPeerControllerRegistrySync,resolveControllerToken,startPeerInbox}from"./chunk-P4ZCOMZS.js";import{InboundGate,MAX_HELD_MESSAGES,PEER_ADMISSION_LIMITS,canonicalizeMsgId,drainSendPacer,forgetSendPacerMessages,peerSenderKey,refundSendPacerMessage,refundSendPacerToken,sendDeliveryStatus,settleSentPeerMessage}from"./chunk-UNDRWCST.js";import{formatPeerDisplay,formatPeerEnvelope}from"./chunk-VMRQ6FA2.js";import{MESSAGING_SOCKET_ENV,MESSAGING_TOKEN_ENV,clearInheritedPeerMessagingEnv}from"./chunk-NPAX2UFU.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{randomBytes}from"node:crypto";var debugLogger=createDebugLogger("PEER_MESSAGING");var MAX_ACCEPTED_BACKLOG=MAX_HELD_MESSAGES;var CLOSE_DROP_FLUSH_BOUND_MS=1e3;var MAX_UNHEARD_DROP_NOTICES=20;var RECEIVER_REFILL_MS=PEER_ADMISSION_LIMITS.bucketCapacity/PEER_ADMISSION_LIMITS.refillPerSecond*1e3;var PeerMessaging=class _PeerMessaging{static{__name(this,"PeerMessaging")}inbox=null;gate=null;updateSessionRegistryIpcPath=__name(async()=>{},"updateSessionRegistryIpcPath");getSessionId=null;ownsSessionId=null;settleSentMessage=settleSentPeerMessage;reassertSessionRecord=null;drainMirror=drainSendPacer;forgetMirror=forgetSendPacerMessages;refundMirror=refundSendPacerMessage;refundMirrorToken=refundSendPacerToken;receiptListeners=new Set;dropListeners=new Set;unheardDrops=[];dropReceipts=null;submitFn=null;buffered=[];controllerRegistryPath=null;validControllerIds=null;outstanding=[];queuedPeerCount=null;heldListeners=new Set;listedHeld=null;closed=false;constructor(){}static async start(options){if(options.getSessionId&&options.ownsSessionId){throw new Error("PeerMessaging: pass getSessionId or ownsSessionId, not both")}const messaging=new _PeerMessaging;const controllerRegistryPath=options.controllerRegistryPath??getPeerControllerRegistryPath();messaging.controllerRegistryPath=controllerRegistryPath;const dropReceipts=new DropReceiptCoalescer(({frame,reason,droppedMsgIds})=>{if(!frame.from)return;return sendDeliveryStatus(frame.from,{status:"dropped",origMsgId:frame.msgId,from:messaging.inbox?.socketPath,dropReason:reason,droppedMsgIds},frame.replyToken)},options.dropReceiptTrailMs!==void 0?{trailMs:options.dropReceiptTrailMs}:{});messaging.dropReceipts=dropReceipts;const dropNotices=new DropNoticeThrottle(notice=>messaging.emitDropped(notice));const gate=new InboundGate({getApprovalMode:options.getApprovalMode,getPolicySetting:options.getPolicySetting,...options.getHeldExpiryMs!==void 0?{getHeldExpiryMs:options.getHeldExpiryMs}:{},...options.getPolicyScope?{getPolicyScope:options.getPolicyScope}:{},isControllerValid:__name(id=>messaging.validControllerIds?.has(id)??true,"isControllerValid"),...options.admission?{admission:options.admission}:{},getSessionId:options.getSessionId,...options.ownsSessionId?{ownsSessionId:options.ownsSessionId}:{},deliver:__name((frame,origin)=>messaging.deliver(frame,origin),"deliver"),reportDropped:__name((frame,reason,origin)=>dropReceipts.note(frame,origin??{selfSent:false},reason),"reportDropped"),onDropped:__name((frame,origin,reason)=>dropNotices.note(frame,origin,reason),"onDropped"),reportStatus:__name((frame,status)=>{if(!frame.from)return;return sendDeliveryStatus(frame.from,{status,origMsgId:frame.msgId,from:messaging.inbox?.socketPath},frame.replyToken)},"reportStatus"),onHeldChange:__name(held=>messaging.emitHeldChange(held),"onHeldChange")});messaging.gate=gate;messaging.getSessionId=options.getSessionId??null;messaging.ownsSessionId=options.ownsSessionId??null;messaging.settleSentMessage=options.settleSentMessage??settleSentPeerMessage;messaging.reassertSessionRecord=options.reassertSessionRecord??null;messaging.drainMirror=options.drainMirror??drainSendPacer;messaging.forgetMirror=options.forgetMirror??forgetSendPacerMessages;messaging.refundMirror=options.refundMirror??refundSendPacerMessage;messaging.refundMirrorToken=options.refundMirrorToken??refundSendPacerToken;clearInheritedPeerMessagingEnv();const ipcToken=options.ipcToken??randomBytes(32).toString("hex");const childToken=options.childToken??randomBytes(32).toString("hex");const inbox=await startPeerInbox({...options.socketPath!==void 0?{socketPath:options.socketPath}:{},requiredToken:ipcToken,childToken,resolveController:__name(presented=>resolveControllerToken(presented,controllerRegistryPath),"resolveController"),onFrame:__name((frame,auth,controller)=>messaging.onFrame(frame,{selfSent:auth==="child",...controller?{controller}:{}}),"onFrame")});if(!inbox)return null;messaging.inbox=inbox;messaging.updateSessionRegistryIpcPath=options.updateSessionRegistryIpcPath;await messaging.updateSessionRegistryIpcPath(inbox.socketPath,ipcToken);process.env[MESSAGING_SOCKET_ENV]=inbox.socketPath;process.env[MESSAGING_TOKEN_ENV]=childToken;return messaging}get socketPath(){return this.inbox?.socketPath}setSubmitFn(fn){if(this.closed)return;this.withControllerValidity(()=>{this.submitFn=fn;while(this.buffered.length>0){const head=this.buffered[0];if(!head||!this.submit(head.frame,head.origin))break;this.buffered.shift()}})}setQueuedPeerCount(fn){this.queuedPeerCount=fn}getHeld(){return this.withControllerValidity(()=>this.gate?.getHeld()??[])}getHeldExpiryMs(sessionId){return this.gate?.getHeldExpiryMs(sessionId)??null}recordHeldListing(heldEntries){this.listedHeld=heldEntries.map(entry=>({id:entry.frame.msgId,heldAt:entry.heldAt}))}heldSetChangedSinceListing(){const listed=this.listedHeld;if(listed===null)return true;const pinned=new Map(listed.map(entry=>[entry.id,entry.heldAt]));const current=this.getHeld();if(current.some(entry=>pinned.get(entry.frame.msgId)!==entry.heldAt))return true;const liveIds=current.map(entry=>canonicalizeMsgId(entry.frame.msgId));const liveSet=new Set(liveIds);for(const id of pinned.keys()){const departed=canonicalizeMsgId(id);if(liveSet.has(departed))continue;if(liveIds.some(live=>live.startsWith(departed)))return true}return false}decide(msgId,decision){return this.withControllerValidity(()=>this.gate?.decide(msgId,decision)??"gone")}forgetController(id){return this.withControllerValidity(()=>this.gate?.forgetController(id)??0)}reevaluate(reason){return this.withControllerValidity(()=>this.gate?.reevaluate(reason)??0)}onHeldChange(listener){this.heldListeners.add(listener);try{listener(this.getHeld())}catch(error){debugLogger.debug(`held-change listener threw: ${error instanceof Error?error.message:String(error)}`)}return()=>this.heldListeners.delete(listener)}onReceipt(listener){this.receiptListeners.add(listener);return()=>this.receiptListeners.delete(listener)}onDropped(listener){const first=this.dropListeners.size===0;this.dropListeners.add(listener);if(first&&this.unheardDrops.length>0){const unheard=this.unheardDrops.splice(0,this.unheardDrops.length);for(const notice of unheard){try{listener(notice)}catch(error){debugLogger.debug(`drop listener threw on replay: ${error instanceof Error?error.message:String(error)}`)}}}return()=>this.dropListeners.delete(listener)}emitDropped(notice){if(this.dropListeners.size===0){if(this.unheardDrops.length<MAX_UNHEARD_DROP_NOTICES){this.unheardDrops.push(notice)}return}for(const listener of this.dropListeners){try{listener(notice)}catch(error){debugLogger.debug(`drop listener threw: ${error instanceof Error?error.message:String(error)}`)}}}emitReceipt(receipt){for(const listener of this.receiptListeners){try{listener(receipt)}catch(error){debugLogger.debug(`receipt listener threw: ${error instanceof Error?error.message:String(error)}`)}}}async close(){if(this.closed)return;this.closed=true;const shuttingDown=this.gate?.shutdown();await this.inbox?.close();await shuttingDown;await this.settleUnconsumed();clearInheritedPeerMessagingEnv();await this.updateSessionRegistryIpcPath(void 0);await this.dropReceipts?.flush(CLOSE_DROP_FLUSH_BOUND_MS);this.dropReceipts?.dispose()}async settleUnconsumed(){const queued=this.queuedPeerCount?.()??0;const dropped=this.outstanding.slice(Math.max(0,this.outstanding.length-this.buffered.length-queued));const receipts=dropped.filter(frame=>frame.from!==void 0).map(frame=>sendDeliveryStatus(frame.from,{status:"expired",origMsgId:frame.msgId,from:this.inbox?.socketPath},frame.replyToken));await Promise.allSettled(receipts)}onDroppedReceipt(frame){const ids=[frame.origMsgId,...frame.droppedMsgIds??[]];let first;let settledCount=0;const settledByPath=new Map;for(const id of ids){const settled=this.settleSentMessage(id,"dropped");if(!settled)continue;first??=settled;settledCount+=1;const entry=settledByPath.get(settled.ipcPath)??{ids:[],freshestAgeMs:Number.POSITIVE_INFINITY};entry.ids.push(id);entry.freshestAgeMs=Math.min(entry.freshestAgeMs,settled.ageMs);settledByPath.set(settled.ipcPath,entry)}if(!first){debugLogger.debug(`ignoring dropped receipt for ${frame.origMsgId}: unknown message or repeated receipt`);return}debugLogger.debug(`dropped receipt from ${first.address} (${frame.dropReason??"unspecified"}) settled ${settledCount} message(s)`);if(frame.dropReason==="duplicate"){for(const[ipcPath,entry]of settledByPath){for(const id of entry.ids)this.refundMirrorToken(ipcPath,id)}}else{for(const[ipcPath,entry]of settledByPath){this.forgetMirror(ipcPath,entry.ids)}}if(frame.dropReason==="rate-limited"){for(const[ipcPath,entry]of settledByPath){if(entry.freshestAgeMs<=RECEIVER_REFILL_MS)this.drainMirror(ipcPath)}}this.emitReceipt({status:"dropped",address:first.address,origMsgId:frame.origMsgId,previous:"pending",...frame.dropReason?{dropReason:frame.dropReason}:{},dropped:settledCount})}onFrame(frame,origin){if(frame.type==="control"){if(frame.status==="dropped"){this.onDroppedReceipt(frame);return}const settled=this.settleSentMessage(frame.origMsgId,frame.status);if(!settled){debugLogger.debug(`ignoring delivery status ${frame.status} for ${frame.origMsgId}: unknown message or repeated receipt`);return}debugLogger.debug(`delivery status from ${settled.address}: ${settled.previous} -> ${frame.status} for ${frame.origMsgId}`);if(frame.status!=="held"&&frame.status!=="delivered"){if(frame.status==="misaddressed"){this.refundMirror(settled.ipcPath,frame.origMsgId)}else{this.forgetMirror(settled.ipcPath,[frame.origMsgId])}}this.emitReceipt({status:frame.status,address:settled.address,origMsgId:frame.origMsgId,previous:settled.previous});return}const ownSessionId=this.getSessionId?.();const ownsSessionId=this.ownsSessionId;const misaddressed=ownsSessionId?frame.toSessionId===void 0||!ownsSessionId(frame.toSessionId):frame.toSessionId!==void 0&&ownSessionId!==void 0&&frame.toSessionId!==ownSessionId;if(misaddressed){debugLogger.debug(`refusing peer message ${frame.msgId}: addressed to session ${frame.toSessionId??"(unspecified)"}, this process does not hold it`);if(frame.from){void sendDeliveryStatus(frame.from,{status:"misaddressed",origMsgId:frame.msgId,from:this.inbox?.socketPath},frame.replyToken)}void this.reassertSessionRecord?.().catch(error=>{debugLogger.debug(`re-asserting the session record failed: ${error instanceof Error?error.message:String(error)}`)});return}this.gate?.admit(frame,origin)}deliver(frame,origin){if(!this.submitFn){if(this.buffered.length>=MAX_ACCEPTED_BACKLOG){throw new Error("accepted-message backlog is full")}this.buffered.push({frame,origin});this.trackOutstanding(frame);return}if(this.buffered.length>0){this.withControllerValidity(()=>{while(this.buffered.length>0){const head=this.buffered[0];if(!head||!this.submit(head.frame,head.origin)){throw new Error("accepted-message backlog is full")}this.buffered.shift()}})}if(!this.submit(frame,origin)){throw new Error("accepted-message backlog is full")}this.trackOutstanding(frame)}trackOutstanding(frame){this.outstanding.push(frame);while(this.outstanding.length>2*MAX_ACCEPTED_BACKLOG){this.outstanding.shift()}}withControllerValidity(action){if(this.controllerRegistryPath===null||this.validControllerIds){return action()}this.validControllerIds=new Set(readPeerControllerRegistrySync(this.controllerRegistryPath).controllers.map(controller=>controller.id));for(const delivery of this.buffered){const controller=delivery.origin.controller;if(controller&&!this.validControllerIds.has(controller.id)){delete delivery.origin.controller}}try{return action()}finally{this.validControllerIds=null}}submit(frame,origin){const from=frame.from??(origin.controller?"controller":origin.selfSent?"own process":"unknown session");const attribution={selfSent:origin.selfSent,...origin.controller?{controller:origin.controller}:{}};return this.submitFn?.(formatPeerEnvelope({from,...frame.fromName!==void 0?{fromName:frame.fromName}:{},content:frame.message.content,...attribution}),formatPeerDisplay({from,...frame.fromName!==void 0?{fromName:frame.fromName}:{},content:frame.message.content,...attribution}),{msgId:frame.msgId,admissionKey:peerSenderKey(frame,origin),...frame.from!==void 0?{from:frame.from}:{},...frame.replyToken!==void 0?{replyToken:frame.replyToken}:{},...frame.toSessionId!==void 0?{toSessionId:frame.toSessionId}:{}})??false}drainQueuedFrame(delivery){const ownSessionId=this.getSessionId?.();if(delivery?.toSessionId===void 0||ownSessionId===void 0||delivery.toSessionId===ownSessionId){return true}debugLogger.debug(`dropping queued peer message ${delivery.msgId}: addressed to session ${delivery.toSessionId}, this is ${ownSessionId}`);if(delivery.from){void sendDeliveryStatus(delivery.from,{status:"misaddressed",origMsgId:delivery.msgId,from:this.inbox?.socketPath},delivery.replyToken)}if(delivery.admissionKey!==void 0){this.gate?.forgetAdmittedMessage(delivery.admissionKey,delivery.msgId)}return false}emitHeldChange(held){for(const listener of this.heldListeners){try{listener(held)}catch(error){debugLogger.debug(`held-change listener threw: ${error instanceof Error?error.message:String(error)}`)}}}};export{MAX_ACCEPTED_BACKLOG,PeerMessaging};
3
+ import{DropNoticeThrottle,DropReceiptCoalescer,getPeerControllerRegistryPath,readPeerControllerRegistrySync,resolveControllerToken,startPeerInbox}from"./chunk-3MBYQYPC.js";import{InboundGate,MAX_HELD_MESSAGES,PEER_ADMISSION_LIMITS,canonicalizeMsgId,drainSendPacer,forgetSendPacerMessages,peerSenderKey,refundSendPacerMessage,refundSendPacerToken,sendDeliveryStatus,settleSentPeerMessage}from"./chunk-UNDRWCST.js";import{formatPeerDisplay,formatPeerEnvelope}from"./chunk-VMRQ6FA2.js";import{MESSAGING_SOCKET_ENV,MESSAGING_TOKEN_ENV,clearInheritedPeerMessagingEnv}from"./chunk-NPAX2UFU.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{randomBytes}from"node:crypto";var debugLogger=createDebugLogger("PEER_MESSAGING");var MAX_ACCEPTED_BACKLOG=MAX_HELD_MESSAGES;var CLOSE_DROP_FLUSH_BOUND_MS=1e3;var MAX_UNHEARD_DROP_NOTICES=20;var RECEIVER_REFILL_MS=PEER_ADMISSION_LIMITS.bucketCapacity/PEER_ADMISSION_LIMITS.refillPerSecond*1e3;var PeerMessaging=class _PeerMessaging{static{__name(this,"PeerMessaging")}inbox=null;gate=null;updateSessionRegistryIpcPath=__name(async()=>{},"updateSessionRegistryIpcPath");getSessionId=null;ownsSessionId=null;settleSentMessage=settleSentPeerMessage;reassertSessionRecord=null;drainMirror=drainSendPacer;forgetMirror=forgetSendPacerMessages;refundMirror=refundSendPacerMessage;refundMirrorToken=refundSendPacerToken;receiptListeners=new Set;dropListeners=new Set;unheardDrops=[];dropReceipts=null;submitFn=null;buffered=[];controllerRegistryPath=null;validControllerIds=null;outstanding=[];queuedPeerCount=null;heldListeners=new Set;listedHeld=null;closed=false;constructor(){}static async start(options){if(options.getSessionId&&options.ownsSessionId){throw new Error("PeerMessaging: pass getSessionId or ownsSessionId, not both")}const messaging=new _PeerMessaging;const controllerRegistryPath=options.controllerRegistryPath??getPeerControllerRegistryPath();messaging.controllerRegistryPath=controllerRegistryPath;const dropReceipts=new DropReceiptCoalescer(({frame,reason,droppedMsgIds})=>{if(!frame.from)return;return sendDeliveryStatus(frame.from,{status:"dropped",origMsgId:frame.msgId,from:messaging.inbox?.socketPath,dropReason:reason,droppedMsgIds},frame.replyToken)},options.dropReceiptTrailMs!==void 0?{trailMs:options.dropReceiptTrailMs}:{});messaging.dropReceipts=dropReceipts;const dropNotices=new DropNoticeThrottle(notice=>messaging.emitDropped(notice));const gate=new InboundGate({getApprovalMode:options.getApprovalMode,getPolicySetting:options.getPolicySetting,...options.getHeldExpiryMs!==void 0?{getHeldExpiryMs:options.getHeldExpiryMs}:{},...options.getPolicyScope?{getPolicyScope:options.getPolicyScope}:{},isControllerValid:__name(id=>messaging.validControllerIds?.has(id)??true,"isControllerValid"),...options.admission?{admission:options.admission}:{},getSessionId:options.getSessionId,...options.ownsSessionId?{ownsSessionId:options.ownsSessionId}:{},deliver:__name((frame,origin)=>messaging.deliver(frame,origin),"deliver"),reportDropped:__name((frame,reason,origin)=>dropReceipts.note(frame,origin??{selfSent:false},reason),"reportDropped"),onDropped:__name((frame,origin,reason)=>dropNotices.note(frame,origin,reason),"onDropped"),reportStatus:__name((frame,status)=>{if(!frame.from)return;return sendDeliveryStatus(frame.from,{status,origMsgId:frame.msgId,from:messaging.inbox?.socketPath},frame.replyToken)},"reportStatus"),onHeldChange:__name(held=>messaging.emitHeldChange(held),"onHeldChange")});messaging.gate=gate;messaging.getSessionId=options.getSessionId??null;messaging.ownsSessionId=options.ownsSessionId??null;messaging.settleSentMessage=options.settleSentMessage??settleSentPeerMessage;messaging.reassertSessionRecord=options.reassertSessionRecord??null;messaging.drainMirror=options.drainMirror??drainSendPacer;messaging.forgetMirror=options.forgetMirror??forgetSendPacerMessages;messaging.refundMirror=options.refundMirror??refundSendPacerMessage;messaging.refundMirrorToken=options.refundMirrorToken??refundSendPacerToken;clearInheritedPeerMessagingEnv();const ipcToken=options.ipcToken??randomBytes(32).toString("hex");const childToken=options.childToken??randomBytes(32).toString("hex");const inbox=await startPeerInbox({...options.socketPath!==void 0?{socketPath:options.socketPath}:{},requiredToken:ipcToken,childToken,resolveController:__name(presented=>resolveControllerToken(presented,controllerRegistryPath),"resolveController"),onFrame:__name((frame,auth,controller)=>messaging.onFrame(frame,{selfSent:auth==="child",...controller?{controller}:{}}),"onFrame")});if(!inbox)return null;messaging.inbox=inbox;messaging.updateSessionRegistryIpcPath=options.updateSessionRegistryIpcPath;await messaging.updateSessionRegistryIpcPath(inbox.socketPath,ipcToken);process.env[MESSAGING_SOCKET_ENV]=inbox.socketPath;process.env[MESSAGING_TOKEN_ENV]=childToken;return messaging}get socketPath(){return this.inbox?.socketPath}setSubmitFn(fn){if(this.closed)return;this.withControllerValidity(()=>{this.submitFn=fn;while(this.buffered.length>0){const head=this.buffered[0];if(!head||!this.submit(head.frame,head.origin))break;this.buffered.shift()}})}setQueuedPeerCount(fn){this.queuedPeerCount=fn}getHeld(){return this.withControllerValidity(()=>this.gate?.getHeld()??[])}getHeldExpiryMs(sessionId){return this.gate?.getHeldExpiryMs(sessionId)??null}recordHeldListing(heldEntries){this.listedHeld=heldEntries.map(entry=>({id:entry.frame.msgId,heldAt:entry.heldAt}))}heldSetChangedSinceListing(){const listed=this.listedHeld;if(listed===null)return true;const pinned=new Map(listed.map(entry=>[entry.id,entry.heldAt]));const current=this.getHeld();if(current.some(entry=>pinned.get(entry.frame.msgId)!==entry.heldAt))return true;const liveIds=current.map(entry=>canonicalizeMsgId(entry.frame.msgId));const liveSet=new Set(liveIds);for(const id of pinned.keys()){const departed=canonicalizeMsgId(id);if(liveSet.has(departed))continue;if(liveIds.some(live=>live.startsWith(departed)))return true}return false}decide(msgId,decision){return this.withControllerValidity(()=>this.gate?.decide(msgId,decision)??"gone")}forgetController(id){return this.withControllerValidity(()=>this.gate?.forgetController(id)??0)}reevaluate(reason){return this.withControllerValidity(()=>this.gate?.reevaluate(reason)??0)}onHeldChange(listener){this.heldListeners.add(listener);try{listener(this.getHeld())}catch(error){debugLogger.debug(`held-change listener threw: ${error instanceof Error?error.message:String(error)}`)}return()=>this.heldListeners.delete(listener)}onReceipt(listener){this.receiptListeners.add(listener);return()=>this.receiptListeners.delete(listener)}onDropped(listener){const first=this.dropListeners.size===0;this.dropListeners.add(listener);if(first&&this.unheardDrops.length>0){const unheard=this.unheardDrops.splice(0,this.unheardDrops.length);for(const notice of unheard){try{listener(notice)}catch(error){debugLogger.debug(`drop listener threw on replay: ${error instanceof Error?error.message:String(error)}`)}}}return()=>this.dropListeners.delete(listener)}emitDropped(notice){if(this.dropListeners.size===0){if(this.unheardDrops.length<MAX_UNHEARD_DROP_NOTICES){this.unheardDrops.push(notice)}return}for(const listener of this.dropListeners){try{listener(notice)}catch(error){debugLogger.debug(`drop listener threw: ${error instanceof Error?error.message:String(error)}`)}}}emitReceipt(receipt){for(const listener of this.receiptListeners){try{listener(receipt)}catch(error){debugLogger.debug(`receipt listener threw: ${error instanceof Error?error.message:String(error)}`)}}}async close(){if(this.closed)return;this.closed=true;const shuttingDown=this.gate?.shutdown();await this.inbox?.close();await shuttingDown;await this.settleUnconsumed();clearInheritedPeerMessagingEnv();await this.updateSessionRegistryIpcPath(void 0);await this.dropReceipts?.flush(CLOSE_DROP_FLUSH_BOUND_MS);this.dropReceipts?.dispose()}async settleUnconsumed(){const queued=this.queuedPeerCount?.()??0;const dropped=this.outstanding.slice(Math.max(0,this.outstanding.length-this.buffered.length-queued));const receipts=dropped.filter(frame=>frame.from!==void 0).map(frame=>sendDeliveryStatus(frame.from,{status:"expired",origMsgId:frame.msgId,from:this.inbox?.socketPath},frame.replyToken));await Promise.allSettled(receipts)}onDroppedReceipt(frame){const ids=[frame.origMsgId,...frame.droppedMsgIds??[]];let first;let settledCount=0;const settledByPath=new Map;for(const id of ids){const settled=this.settleSentMessage(id,"dropped");if(!settled)continue;first??=settled;settledCount+=1;const entry=settledByPath.get(settled.ipcPath)??{ids:[],freshestAgeMs:Number.POSITIVE_INFINITY};entry.ids.push(id);entry.freshestAgeMs=Math.min(entry.freshestAgeMs,settled.ageMs);settledByPath.set(settled.ipcPath,entry)}if(!first){debugLogger.debug(`ignoring dropped receipt for ${frame.origMsgId}: unknown message or repeated receipt`);return}debugLogger.debug(`dropped receipt from ${first.address} (${frame.dropReason??"unspecified"}) settled ${settledCount} message(s)`);if(frame.dropReason==="duplicate"){for(const[ipcPath,entry]of settledByPath){for(const id of entry.ids)this.refundMirrorToken(ipcPath,id)}}else{for(const[ipcPath,entry]of settledByPath){this.forgetMirror(ipcPath,entry.ids)}}if(frame.dropReason==="rate-limited"){for(const[ipcPath,entry]of settledByPath){if(entry.freshestAgeMs<=RECEIVER_REFILL_MS)this.drainMirror(ipcPath)}}this.emitReceipt({status:"dropped",address:first.address,origMsgId:frame.origMsgId,previous:"pending",...frame.dropReason?{dropReason:frame.dropReason}:{},dropped:settledCount})}onFrame(frame,origin){if(frame.type==="control"){if(frame.status==="dropped"){this.onDroppedReceipt(frame);return}const settled=this.settleSentMessage(frame.origMsgId,frame.status);if(!settled){debugLogger.debug(`ignoring delivery status ${frame.status} for ${frame.origMsgId}: unknown message or repeated receipt`);return}debugLogger.debug(`delivery status from ${settled.address}: ${settled.previous} -> ${frame.status} for ${frame.origMsgId}`);if(frame.status!=="held"&&frame.status!=="delivered"){if(frame.status==="misaddressed"){this.refundMirror(settled.ipcPath,frame.origMsgId)}else{this.forgetMirror(settled.ipcPath,[frame.origMsgId])}}this.emitReceipt({status:frame.status,address:settled.address,origMsgId:frame.origMsgId,previous:settled.previous});return}const ownSessionId=this.getSessionId?.();const ownsSessionId=this.ownsSessionId;const misaddressed=ownsSessionId?frame.toSessionId===void 0||!ownsSessionId(frame.toSessionId):frame.toSessionId!==void 0&&ownSessionId!==void 0&&frame.toSessionId!==ownSessionId;if(misaddressed){debugLogger.debug(`refusing peer message ${frame.msgId}: addressed to session ${frame.toSessionId??"(unspecified)"}, this process does not hold it`);if(frame.from){void sendDeliveryStatus(frame.from,{status:"misaddressed",origMsgId:frame.msgId,from:this.inbox?.socketPath},frame.replyToken)}void this.reassertSessionRecord?.().catch(error=>{debugLogger.debug(`re-asserting the session record failed: ${error instanceof Error?error.message:String(error)}`)});return}this.gate?.admit(frame,origin)}deliver(frame,origin){if(!this.submitFn){if(this.buffered.length>=MAX_ACCEPTED_BACKLOG){throw new Error("accepted-message backlog is full")}this.buffered.push({frame,origin});this.trackOutstanding(frame);return}if(this.buffered.length>0){this.withControllerValidity(()=>{while(this.buffered.length>0){const head=this.buffered[0];if(!head||!this.submit(head.frame,head.origin)){throw new Error("accepted-message backlog is full")}this.buffered.shift()}})}if(!this.submit(frame,origin)){throw new Error("accepted-message backlog is full")}this.trackOutstanding(frame)}trackOutstanding(frame){this.outstanding.push(frame);while(this.outstanding.length>2*MAX_ACCEPTED_BACKLOG){this.outstanding.shift()}}withControllerValidity(action){if(this.controllerRegistryPath===null||this.validControllerIds){return action()}this.validControllerIds=new Set(readPeerControllerRegistrySync(this.controllerRegistryPath).controllers.map(controller=>controller.id));for(const delivery of this.buffered){const controller=delivery.origin.controller;if(controller&&!this.validControllerIds.has(controller.id)){delete delivery.origin.controller}}try{return action()}finally{this.validControllerIds=null}}submit(frame,origin){const from=frame.from??(origin.controller?"controller":origin.selfSent?"own process":"unknown session");const attribution={selfSent:origin.selfSent,...origin.controller?{controller:origin.controller}:{}};return this.submitFn?.(formatPeerEnvelope({from,...frame.fromName!==void 0?{fromName:frame.fromName}:{},content:frame.message.content,...attribution}),formatPeerDisplay({from,...frame.fromName!==void 0?{fromName:frame.fromName}:{},content:frame.message.content,...attribution}),{msgId:frame.msgId,admissionKey:peerSenderKey(frame,origin),...frame.from!==void 0?{from:frame.from}:{},...frame.replyToken!==void 0?{replyToken:frame.replyToken}:{},...frame.toSessionId!==void 0?{toSessionId:frame.toSessionId}:{}})??false}drainQueuedFrame(delivery){const ownSessionId=this.getSessionId?.();if(delivery?.toSessionId===void 0||ownSessionId===void 0||delivery.toSessionId===ownSessionId){return true}debugLogger.debug(`dropping queued peer message ${delivery.msgId}: addressed to session ${delivery.toSessionId}, this is ${ownSessionId}`);if(delivery.from){void sendDeliveryStatus(delivery.from,{status:"misaddressed",origMsgId:delivery.msgId,from:this.inbox?.socketPath},delivery.replyToken)}if(delivery.admissionKey!==void 0){this.gate?.forgetAdmittedMessage(delivery.admissionKey,delivery.msgId)}return false}emitHeldChange(held){for(const listener of this.heldListeners){try{listener(held)}catch(error){debugLogger.debug(`held-change listener threw: ${error instanceof Error?error.message:String(error)}`)}}}};export{MAX_ACCEPTED_BACKLOG,PeerMessaging};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{t}from"./chunk-4NQCOITC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function formatHistoryGapNotice(_gap){return t("\u26A0\uFE0F History gap: earlier conversation was lost before this point (storage interruption) and could not be recovered.")}__name(formatHistoryGapNotice,"formatHistoryGapNotice");function indexGapsByChild(gaps){const byChild=new Map;for(const gap of gaps??[]){byChild.set(gap.childUuid,gap)}return byChild}__name(indexGapsByChild,"indexGapsByChild");export{formatHistoryGapNotice,indexGapsByChild};
3
+ import{t}from"./chunk-FK5L2WVV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function formatHistoryGapNotice(_gap){return t("\u26A0\uFE0F History gap: earlier conversation was lost before this point (storage interruption) and could not be recovered.")}__name(formatHistoryGapNotice,"formatHistoryGapNotice");function indexGapsByChild(gaps){const byChild=new Map;for(const gap of gaps??[]){byChild.set(gap.childUuid,gap)}return byChild}__name(indexGapsByChild,"indexGapsByChild");export{formatHistoryGapNotice,indexGapsByChild};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Code
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{MAX_DROPPED_MSG_IDS,MAX_FRAME_BYTES,MAX_RETAINED_REPLY_TOKEN_CHARS,MAX_SENDER_KEY_CHARS,MAX_SOCKET_PATH_BYTES,SOCKET_DIR_NAME,isLocalIpcPath,parsePeerAuthLine,parsePeerFrame,peerSenderKey,probePeerSocketVerdict,resolvePeerSocketCandidates}from"./chunk-UNDRWCST.js";import{scanForSecrets}from"./chunk-54CHQYA3.js";import{BudgetExhaustedError,IDE_DEFINITIONS,MCP_BUDGET_REARM_FRACTION,MCP_BUDGET_WARN_FRACTION,McpClient,ORPHAN_TOOL_USE_REPAIR_REASON,POOLED_TRANSPORTS_DEFAULT,QWEN_CODE_COMPANION_EXTENSION_NAME,SessionService,StandardFileSystemService,aggregateUsage,buildSessionHistoryFromConversation,buildSyntheticToolResponseParts,classifyShellCommandSafety,classifyShellCommandSafetyInDirectory,coerceMcpFilterEntries,connectionIdOf,convertToFunctionErrorResponse,convertToFunctionResponse,createForkedChat,detectTurnInterruption,discoveryTimeoutFor,estimateContentTokens,evaluateToolInvocationGuard,finalizeToolResponses,getCacheSafeParams,getCacheSafeParamsSessionId,getTimeRangeBounds,isPoolable,listDescendantPids,listExistingSkillDirNames,loadUsageHistoryWithLive,mcpSessionMetadataKey,mcpTransportOf,normalizeMcpIncludeEntry,observeToolResultBoundary,parseConnectionId,recursivelyHydrateStrings,repairOrphanedToolUseTurns,runForkedAgent,runWithForkedChatModel,runWithTimeout,sigtermPids,stripToolResultImages,toolResultBoundaryArtifact,toolResultPartDiagnosticValues,withoutAutoMemorySnapshots}from"./chunk-3SQ76U4F.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{runGit,runGitCapture,streamGitRecords}from"./chunk-I44IFX3I.js";import{hasVerifiableInode,openNoFollow,openSyncNoFollow}from"./chunk-PSKT6KWO.js";import{projectUserTranscriptForDisplay}from"./chunk-UHJUDWBV.js";import{toolSearchBridgeSentence}from"./chunk-TWCQNRBQ.js";import{flattenPeerLabel}from"./chunk-VMRQ6FA2.js";import{isPidAlive}from"./chunk-JB3XRNK7.js";import{getProjectSkillsRoot}from"./chunk-NVXFGZ4Z.js";import{parse}from"./chunk-PNF77EBK.js";import{Ns,zs}from"./chunk-TASTRW4D.js";import{fetchWithPolicy}from"./chunk-IUVB7EIZ.js";import{isDeferredToolBridgeAvailable}from"./chunk-PIHZPQYO.js";import{require_picomatch}from"./chunk-THN4FBQ7.js";import{BUILT_IN_OUTPUT_STYLES,getBuiltInOutputStyle}from"./chunk-KVSDMMDD.js";import{NO_EXEC_CONFIG}from"./chunk-744VRMDB.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{DEFAULT_WRITE_QUEUE_BYTES,collectPtyProcessTree,getPtyBudgetStats,processPtyBudget}from"./chunk-6EDEOERB.js";import{disposeConoutWorker,loadPty,loadXtermHeadless,noteConPtyHostReleased,releaseConPtyHost}from"./chunk-MEUP65FI.js";import{stripAnsi}from"./chunk-YGLM5XPP.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{escapeJsonTagCharacters}from"./chunk-NTRFETZB.js";import{COMBINED_PASS_TOLERANCE_FACTOR,TOOL_OUTPUT_TRUNCATED_PREFIX,TRUNCATION_FALLBACK_ENVELOPE_SLACK,addMCPStatusChangeListener,removeMCPStatusChangeListener,updateMCPServerStatus}from"./chunk-MJEL7DIE.js";import{E_TIMEOUT,Mutex,withTimeout}from"./chunk-JEV36CS7.js";import{runSideQuery}from"./chunk-FCQWRGW5.js";import{MEMORY_SECTION_HEADER,VISION_BRIDGE_MAX_IMAGES,VISION_BRIDGE_MAX_IMAGE_BASE64_BYTES,detectFileType,getCurrentMemoryFilename,isCacheableReadResult,isWithinRoot,processSingleFileContent}from"./chunk-6JHMYZNS.js";import{getInvocationContext}from"./chunk-6QJWBGMS.js";import{atomicWriteFile,atomicWriteJSON}from"./chunk-2GF3E5MI.js";import{getModelsForProviderProtocol,tryResolveModelProtocol}from"./chunk-BVYNPYGP.js";import{DEFAULT_IMAGE_TOKEN_ESTIMATE,estimatePartChars}from"./chunk-Q6UAOTP3.js";import{isBinary,normalizeContent,stripAnsiAndControl,stripHtmlComments}from"./chunk-DBRQGEEI.js";import{cloneApiHistory,getFolderStructure,getStartupContextLength,stripSystemReminderBlocks}from"./chunk-6AA5DYMC.js";import{getQwenIgnoreFileNames,require_ignore}from"./chunk-LWVCLDHV.js";import{ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger,isDebugLogFileEnabled}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{PATH_ARG_KEYS,QWEN_DIR,tildeifyPath,unescapePath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage,isAbortError,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__require,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonFormatter=class{static{__name(this,"JsonFormatter")}format(response,stats,error){const output={};if(response!==void 0){output.response=stripAnsi(response)}if(stats){output.stats=stats}if(error){output.error=error}return JSON.stringify(output,null,2)}formatError(error,code){const jsonError={type:error.constructor.name,message:stripAnsi(error.message),...code&&{code}};return this.format(void 0,void 0,jsonError)}};init_esbuild_shims();function createPlanId(sessionId,historyLength){return`${sessionId}:${historyLength}`}__name(createPlanId,"createPlanId");function buildVisibleNotice(kind,repairs,historyGaps){if(kind==="clean"){return void 0}if(kind==="degraded_history"){return`Resumed session history is incomplete: detected ${historyGaps.length} missing parent link(s). Automatic continuation is disabled for this recovery.`}if(kind==="interrupted_prompt"){return"Previous session appears to have stopped after user input before the model completed a response."}const synthesized=repairs.filter(repair=>repair.type==="synthesized_tool_result").length;if(synthesized>0){return`Previous session appears to have stopped during tool execution. Synthesized ${synthesized} failed tool result(s) so the history can continue safely.`}return"Previous session appears to have stopped during tool execution."}__name(buildVisibleNotice,"buildVisibleNotice");function buildSessionRecoveryPlan({sessionId,conversation,historyGaps,options}){return buildSessionRecoveryPlanFromApiHistory({sessionId,...buildSessionHistoryFromConversation(conversation),historyGaps,options})}__name(buildSessionRecoveryPlan,"buildSessionRecoveryPlan");function buildSessionRecoveryPlanFromApiHistory({sessionId,apiHistory:inputApiHistory,completedToolCallIds,trailingSystemNotifications,historyGaps,options}){const originalApiHistory=inputApiHistory;const gaps=historyGaps??[];const planId=createPlanId(sessionId,originalApiHistory.length);const apiHistory=cloneApiHistory(originalApiHistory);const repairResult=repairOrphanedToolUseTurns(apiHistory);const repairs=[...repairResult.injected.map(repair=>({type:"synthesized_tool_result",callId:repair.callId,name:repair.name})),...repairResult.droppedDuplicates.map(repair=>({type:"dropped_duplicate_tool_result",callId:repair.callId,name:repair.name})),...gaps.map(gap=>({type:"history_gap",childUuid:gap.childUuid,missingParentUuid:gap.missingParentUuid}))];if(gaps.length>0){return{planId,sessionId,kind:"degraded_history",originalApiHistory,apiHistory,repairs,canContinue:false,canAutoContinue:false,requiresUserConfirmation:true,visibleNotice:buildVisibleNotice("degraded_history",repairs,gaps)}}const interruption=detectTurnInterruption(originalApiHistory,completedToolCallIds,trailingSystemNotifications);if(interruption.kind==="none"){return{planId,sessionId,kind:"clean",originalApiHistory,apiHistory,repairs,canContinue:false,canAutoContinue:false,requiresUserConfirmation:false}}if(interruption.kind==="interrupted_prompt"){const continuation2={mode:"retry_user_parts",parts:interruption.parts,displayText:"Continue interrupted user prompt"};return{planId,sessionId,kind:"interrupted_prompt",originalApiHistory,apiHistory,repairs,canContinue:true,canAutoContinue:options?.allowAutoContinue===true,requiresUserConfirmation:options?.allowAutoContinue!==true,visibleNotice:buildVisibleNotice("interrupted_prompt",repairs,gaps),continuation:continuation2}}const continuation={mode:"tool_result_parts",parts:buildSyntheticToolResponseParts(interruption.danglingCalls,ORPHAN_TOOL_USE_REPAIR_REASON),displayText:"Continue interrupted tool turn"};return{planId,sessionId,kind:"interrupted_turn",originalApiHistory,apiHistory,repairs,canContinue:true,canAutoContinue:false,requiresUserConfirmation:true,visibleNotice:buildVisibleNotice("interrupted_turn",repairs,gaps),continuation}}__name(buildSessionRecoveryPlanFromApiHistory,"buildSessionRecoveryPlanFromApiHistory");init_esbuild_shims();init_esbuild_shims();import{EventEmitter}from"node:events";init_esbuild_shims();var debugLogger=createDebugLogger("McpPool:Entry");function defaultPoolEntryOptions(transport){const isRemote=transport==="http"||transport==="sse"||transport==="websocket";return{drainDelayMs:3e4,maxIdleMs:5*6e4,maxReconnectAttempts:isRemote?5:3,reconnectStrategy:isRemote?{kind:"exponential",baseMs:1e3,capMs:16e3}:{kind:"fixed",delayMs:5e3}}}__name(defaultPoolEntryOptions,"defaultPoolEntryOptions");var PoolEntry=class{constructor(id,serverName,entryIndex,cfg,client,cliConfig,opts,onClosed,aggregateStatusByName){this.id=id;this.serverName=serverName;this.entryIndex=entryIndex;this.cfg=cfg;this.client=client;this.cliConfig=cliConfig;this.opts=opts;this.onClosed=onClosed;this.aggregateStatusByName=aggregateStatusByName;this.transportId=connectionIdOf(serverName,cfg);this.emitter.setMaxListeners(0);this.statusChangeListener=(name,status)=>{if(name!==this.serverName)return;if(status===void 0)return;if(this.suppressNextStatusEcho){this.suppressNextStatusEcho=false;return}if(this.client.getStatus()!==status)return;if(status===this.localStatus)return;this.localStatus=status;if(status==="disconnected"&&(this.state==="active"||this.state==="draining")&&!this.restartInProgress){const wasDraining=this.state==="draining";this.state="failed";if(wasDraining){this.cancelDrainTimer()}if(this.maxIdleTimer){clearTimeout(this.maxIdleTimer);this.maxIdleTimer=void 0}if(this.statusChangeListener){removeMCPStatusChangeListener(this.statusChangeListener);this.statusChangeListener=void 0}debugLogger.error(`PoolEntry ${this.id} silent transport drop (prev state='${wasDraining?"draining":"active"}', localStatus\u2192DISCONNECTED). Transitioning to 'failed'; evicting from pool.entries + pooledConnections (W122 R20).`);const upstreamError=this.client.getLastTransportError();this.emit({kind:"failed",serverName:this.serverName,generation:this._generation,lastError:upstreamError?`transport disconnected (silent transport drop): ${upstreamError.message}`:"transport disconnected (silent transport drop)"});for(const[sid]of[...this.subscribers]){this.detach(sid)}void this.sweepAndDisconnect("silent_drop").then(result=>{const partialSignal=result.descendantsFound!==void 0&&result.descendantsSignaled!==void 0&&result.descendantsSignaled<result.descendantsFound;if(result.pidSweepError!==void 0||partialSignal){debugLogger.warn(`PoolEntry ${this.id} silent-drop sweep observability: descendantsFound=${result.descendantsFound??"unknown"}, descendantsSignaled=${result.descendantsSignaled??"unknown"}, pidSweepError=${result.pidSweepError?.message??"none"}. Possible orphan-process pressure \u2014 operator should check for lingering subprocess descendants of the dead transport.`)}this.updateGlobalStatus()},()=>{this.updateGlobalStatus()});this.updateGlobalStatus();this.onClosed(this.id)}};addMCPStatusChangeListener(this.statusChangeListener)}static{__name(this,"PoolEntry")}localStatus="connecting";state="spawning";_generation=0;refs=new Set;subscribers=new Map;subscriberHandles=new Map;toolsSnapshot=[];promptsSnapshot=[];resourcesSnapshot=[];drainTimer;maxIdleTimer;firstIdleAt;restartInFlight;restartInProgress=false;emitter=new EventEmitter;statusChangeListener;suppressNextStatusEcho=false;transportId;get generation(){return this._generation}get currentState(){return this.state}get transportKind(){return mcpTransportOf(this.cfg)}isTerminated(){return this.state==="closed"||this.state==="failed"}markActive(initialTools,initialPrompts,initialResources){if(this.state==="closed"||this.state==="failed")return;this.toolsSnapshot=initialTools;this.promptsSnapshot=initialPrompts;this.resourcesSnapshot=initialResources;this.state="active";this.localStatus="connected";this.updateGlobalStatus()}attach(sessionId,view,opts){if(this.state==="closed"||this.state==="failed"){throw new Error(`Cannot attach to PoolEntry ${this.id} in state ${this.state}`)}const previousState=this.state;const hadRef=this.refs.has(sessionId);const previousView=this.subscribers.get(sessionId);const previousHandle=this.subscriberHandles.get(sessionId);this.refs.add(sessionId);this.subscribers.set(sessionId,view);this.cancelDrainTimer();if(this.state==="draining")this.state="active";if(this.state==="active"&&opts?.skipReplay!==true){try{view.applyTools(this.toolsSnapshot);view.applyPrompts(this.promptsSnapshot);view.applyResources(this.resourcesSnapshot)}catch(err){if(!hadRef){this.refs.delete(sessionId);this.subscribers.delete(sessionId);this.subscriberHandles.delete(sessionId);try{view.teardown()}catch{}}else if(previousView){this.subscribers.set(sessionId,previousView);if(previousHandle){this.subscriberHandles.set(sessionId,previousHandle)}}if(previousState==="draining"&&this.refs.size===0){this.startDrainTimer(this.opts.drainDelayMs)}else{this.state=previousState}debugLogger.error(`Snapshot replay failed for ${sessionId}/${this.serverName}: ${String(err)}`);throw err}}const handle=new PooledConnectionImpl(this,sessionId,opts?.release);this.subscriberHandles.set(sessionId,handle);return handle}updateSessionConfig(sessionId,cfg){if(this.isTerminated()){throw new Error(`Cannot update config on PoolEntry ${this.id} in state ${this.state}`)}const view=this.subscribers.get(sessionId);if(!view){throw new Error(`Cannot update config for detached session ${sessionId} on PoolEntry ${this.id}`)}if(!view.updateConfig(cfg))return;if(this.state==="active"){view.applyTools(this.toolsSnapshot);view.applyPrompts(this.promptsSnapshot);view.applyResources(this.resourcesSnapshot)}}detach(sessionId){const view=this.subscribers.get(sessionId);if(view){try{view.teardown()}catch(err){debugLogger.error(`View teardown failed for ${sessionId}/${this.serverName}: ${String(err)}`)}}this.subscribers.delete(sessionId);this.subscriberHandles.delete(sessionId);this.refs.delete(sessionId)}startDrainTimer(delayMs){this.cancelDrainTimer();this.state="draining";if(this.firstIdleAt===void 0){this.firstIdleAt=Date.now();this.maxIdleTimer=setTimeout(()=>{if(this.refs.size>0){debugLogger.debug(`PoolEntry ${this.id} max-idle reached but ${this.refs.size} sessions active; deferring close, resetting first-idle window`);this.maxIdleTimer=void 0;this.firstIdleAt=void 0;return}debugLogger.warn(`PoolEntry ${this.id} hit MAX_IDLE_MS (${this.opts.maxIdleMs}ms); force-closing`);void this.forceShutdown("max_idle")},this.opts.maxIdleMs);this.maxIdleTimer.unref?.()}this.drainTimer=setTimeout(()=>{void this.forceShutdown("drain_timer")},delayMs);this.drainTimer.unref?.()}cancelDrainTimer(){if(this.drainTimer){clearTimeout(this.drainTimer);this.drainTimer=void 0}}async forceShutdown(reason){if(this.state==="closed"||this.state==="failed")return;this.state="closed";this.localStatus="disconnected";this.suppressNextStatusEcho=true;this.cancelDrainTimer();if(this.maxIdleTimer){clearTimeout(this.maxIdleTimer);this.maxIdleTimer=void 0}if(this.statusChangeListener){removeMCPStatusChangeListener(this.statusChangeListener);this.statusChangeListener=void 0}this.emit({kind:"disconnected",serverName:this.serverName,generation:this._generation,reason:"transport_closed"});for(const[sid]of this.subscribers){this.detach(sid)}await this.sweepAndDisconnect(reason);this.updateGlobalStatus();this.onClosed(this.id)}async sweepAndDisconnect(reason){const result={};try{const rootPid=this.client.getTransportPid?.();if(rootPid!==void 0){const descendants=await listDescendantPids(rootPid);if(descendants.length>0){result.descendantsFound=descendants.length;result.descendantsSignaled=sigtermPids(descendants);debugLogger.debug(`Sent SIGTERM to ${result.descendantsSignaled}/${descendants.length} descendants of pid ${rootPid} for ${this.id} (${reason})`)}}}catch(err){result.pidSweepError=err instanceof Error?err:new Error(String(err));debugLogger.warn(`Descendant pid sweep failed for ${this.id} (${reason}): ${String(err)}. Proceeding with disconnect.`)}try{await this.client.disconnect()}catch(err){debugLogger.error(`client.disconnect failed for ${this.id} (${reason}): ${String(err)}`)}return result}async restart(){if(this.restartInFlight)return this.restartInFlight;this.restartInFlight=this.doRestart().finally(()=>{this.restartInFlight=void 0});return this.restartInFlight}async doRestart(){if(this.state==="closed"||this.state==="failed"){throw new Error(`Cannot restart PoolEntry ${this.id} in state ${this.state}`)}this.restartInProgress=true;try{return await this.doRestartInner()}finally{this.restartInProgress=false}}async doRestartInner(){this.cancelDrainTimer();if(this.maxIdleTimer){clearTimeout(this.maxIdleTimer);this.maxIdleTimer=void 0}this.firstIdleAt=void 0;if(this.state==="draining"){this.state="active"}const oldGen=this._generation;this._generation+=1;this.emit({kind:"disconnected",serverName:this.serverName,generation:oldGen,reason:"restart"});await this.sweepAndDisconnect("restart");let snap;try{const timeoutMs=discoveryTimeoutFor(this.cfg);snap=await runWithTimeout((async()=>{await this.client.connect();return this.client.discoverAndReturn(this.cliConfig,{applyConfigFilters:false})})(),timeoutMs,`pool restart for ${this.id} (pool will roll back the restart and free its budget slot)`)}catch(err){debugLogger.error(`Restart of ${this.id} failed at connect/discover: ${String(err)}. Transitioning to 'failed'.`);await this.sweepAndDisconnect("restart_failed");this.state="failed";this.localStatus="disconnected";this.suppressNextStatusEcho=true;this.updateGlobalStatus();if(this.statusChangeListener){removeMCPStatusChangeListener(this.statusChangeListener);this.statusChangeListener=void 0}this.emit({kind:"failed",serverName:this.serverName,generation:this._generation,lastError:err instanceof Error?err.message:String(err)});for(const[sid]of this.subscribers){this.detach(sid)}this.onClosed(this.id);throw err}if(oldGen+1!==this._generation){await this.sweepAndDisconnect("restart_superseded");throw new Error(`Restart of ${this.id} superseded by newer generation; discarded stale snapshot + swept new transport.`)}const currentState=this.state;if(currentState==="closed"||currentState==="failed"){await this.sweepAndDisconnect("restart_superseded");throw new Error(`Restart of ${this.id} aborted: entry state is ${currentState} (forceShutdown ran concurrently mid-restart). Snapshot discarded; new transport swept.`)}this.toolsSnapshot=snap.tools;this.promptsSnapshot=snap.prompts;if(snap.resources.length>0){this.resourcesSnapshot=snap.resources}for(const[sid,view]of this.subscribers){try{view.applyTools(this.toolsSnapshot);view.applyPrompts(this.promptsSnapshot);view.applyResources(this.resourcesSnapshot)}catch(err){debugLogger.error(`Restart fan-out to view ${sid}/${this.serverName} failed: ${String(err)}`)}}this.localStatus="connected";this.suppressNextStatusEcho=true;this.updateGlobalStatus();this.emit({kind:"reconnected",serverName:this.serverName,generation:this._generation});this.emit({kind:"toolsChanged",serverName:this.serverName,snapshot:this.toolsSnapshot,generation:this._generation});this.emit({kind:"promptsChanged",serverName:this.serverName,snapshot:this.promptsSnapshot,generation:this._generation});this.emit({kind:"resourcesChanged",serverName:this.serverName,snapshot:this.resourcesSnapshot,generation:this._generation})}emit(event){const listeners=this.emitter.listeners("event");for(const listener of listeners){try{listener(event)}catch(err){debugLogger.error(`PoolEntry listener error for ${this.id} (event.kind=${event.kind}): ${err instanceof Error?err.message:String(err)}`)}}}internalOn(listener){this.emitter.on("event",listener)}internalOff(listener){this.emitter.off("event",listener)}updateGlobalStatus(){const aggregated=this.aggregateStatusByName(this.serverName);updateMCPServerStatus(this.serverName,aggregated)}getLocalStatus(){return this.localStatus}};var PooledConnectionImpl=class{constructor(entry,sessionId,releaseCallback){this.entry=entry;this.sessionId=sessionId;this.releaseCallback=releaseCallback}static{__name(this,"PooledConnectionImpl")}listeners=new Set;released=false;get id(){return this.entry.id}get transportId(){return this.entry.transportId}get serverName(){return this.entry.serverName}get entryIndex(){return this.entry.entryIndex}get client(){return this.entry.client}get toolsSnapshot(){return this.entry.toolsSnapshot}get promptsSnapshot(){return this.entry.promptsSnapshot}get resourcesSnapshot(){return this.entry.resourcesSnapshot}updateConfig(cfg){if(this.released){throw new Error(`Cannot update config on released MCP connection ${this.id}`)}this.entry.updateSessionConfig(this.sessionId,cfg)}on(event,listener){if(event!=="event")return this;if(this.listeners.has(listener))return this;this.listeners.add(listener);this.entry.internalOn(listener);return this}off(event,listener){if(event!=="event")return this;this.listeners.delete(listener);this.entry.internalOff(listener);return this}release(){if(this.released)return;this.released=true;for(const l of this.listeners){this.entry.internalOff(l)}this.listeners.clear();this.releaseCallback?.()}};init_esbuild_shims();var debugLogger2=createDebugLogger("McpPool:View");function compileNameFilter(includeTools,excludeTools){return{excludeSet:excludeTools?new Set(coerceMcpFilterEntries(excludeTools)):void 0,includeSet:includeTools!=null?new Set(coerceMcpFilterEntries(includeTools).map(normalizeMcpIncludeEntry)):void 0}}__name(compileNameFilter,"compileNameFilter");function compiledFilterAccepts(filter2,name){if(filter2.excludeSet?.has(name))return false;if(!filter2.includeSet)return true;return filter2.includeSet.has(name)}__name(compiledFilterAccepts,"compiledFilterAccepts");var SessionMcpView=class{constructor(sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry,sessionId,serverName,cfg){this.sessionToolRegistry=sessionToolRegistry;this.sessionPromptRegistry=sessionPromptRegistry;this.sessionResourceRegistry=sessionResourceRegistry;this.sessionId=sessionId;this.serverName=serverName;this.cfg=cfg;this.metadataKey=mcpSessionMetadataKey(cfg)}static{__name(this,"SessionMcpView")}metadataKey;applyTools(snapshot){this.sessionToolRegistry.removeMcpToolsByServer(this.serverName);const filter2=compileNameFilter(this.cfg.includeTools,this.cfg.excludeTools);let registered=0;for(const tool of snapshot){if(!compiledFilterAccepts(filter2,tool.serverToolName)){continue}const sessionTool=tool.withSessionConfig(this.cfg.trust,this.cfg.alwaysLoadTools===true);try{this.sessionToolRegistry.registerTool(sessionTool);registered+=1}catch(err){debugLogger2.error(`SessionMcpView[${this.sessionId}/${this.serverName}] failed to register tool ${tool.serverToolName}: ${String(err instanceof Error?err.message:err)}`)}}debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] applied ${snapshot.length} tools (filtered to ${registered} registered)`)}applyPrompts(snapshot){this.sessionPromptRegistry.removePromptsByServer(this.serverName);const filter2=compileNameFilter(this.cfg.includeTools,this.cfg.excludeTools);let registered=0;for(const prompt of snapshot){if(!compiledFilterAccepts(filter2,prompt.name)){continue}try{this.sessionPromptRegistry.registerPrompt(prompt);registered+=1}catch(err){debugLogger2.error(`SessionMcpView[${this.sessionId}/${this.serverName}] failed to register prompt ${prompt.name}: ${String(err instanceof Error?err.message:err)}`)}}debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] applied ${snapshot.length} prompts (filtered to ${registered} registered)`)}applyResources(snapshot){if(snapshot.length===0){return}this.sessionResourceRegistry.removeResourcesByServer(this.serverName);for(const resource of snapshot){try{this.sessionResourceRegistry.registerResource(resource)}catch(err){debugLogger2.error(`SessionMcpView[${this.sessionId}/${this.serverName}] failed to register resource ${resource.uri}: ${String(err instanceof Error?err.message:err)}`)}}debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] applied ${snapshot.length} resources`)}updateConfig(cfg){const nextKey=mcpSessionMetadataKey(cfg);const changed=this.metadataKey!==nextKey;this.cfg=cfg;this.metadataKey=nextKey;return changed}teardown(){this.sessionToolRegistry.removeMcpToolsByServer(this.serverName);this.sessionPromptRegistry.removePromptsByServer(this.serverName);this.sessionResourceRegistry.removeResourcesByServer(this.serverName);debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] torn down`)}};var debugLogger3=createDebugLogger("McpPool");var McpTransportPool=class{constructor(cliConfig,options){this.cliConfig=cliConfig;this.opts={workspaceContext:options.workspaceContext,debugMode:options.debugMode,sendSdkMcpMessage:options.sendSdkMcpMessage,pooledTransports:options.pooledTransports??POOLED_TRANSPORTS_DEFAULT,drainDelayMs:options.drainDelayMs??3e4,entryOptions:options.entryOptions??defaultPoolEntryOptions,budget:options.budget}}static{__name(this,"McpTransportPool")}entries=new Map;unpooledIds=new Set;spawnInFlight=new Map;sessionToEntries=new Map;draining=false;nextIndexByName=new Map;opts;getBudget(){return this.opts.budget}hasNameSibling(serverName){for(const e of this.entries.values()){if(e.serverName===serverName)return true}for(const id of this.spawnInFlight.keys()){try{if(parseConnectionId(id).serverName===serverName)return true}catch{}}return false}async acquire(serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry){if(this.draining){throw new Error(`McpTransportPool is draining; refusing acquire for ${serverName} (session ${sessionId})`)}const poolable=isPoolable(cfg,this.opts.pooledTransports);const id=poolable?connectionIdOf(serverName,cfg):void 0;if(id!==void 0){const existing=this.entries.get(id);if(existing&&!existing.isTerminated()){try{const conn=this.attachPooledSession(existing,id,serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry);this.indexAttach(sessionId,id);return conn}catch(err){if(existing.isTerminated()){this.evictEntry(id,existing);debugLogger3.warn(`pool self-heal: evicted terminal entry ${id} (state='${existing.currentState}', serverName='${serverName}') mid-attach race; falling through to spawn fresh entry`)}else{throw err}}}else if(existing&&existing.isTerminated()){this.evictEntry(id,existing);debugLogger3.warn(`pool self-heal: evicted stale terminal entry ${id} (state='${existing.currentState}', serverName='${serverName}') before fast-path attach; falling through to spawn fresh entry`)}}let reservationResult;if(this.opts.budget!==void 0){const reservation=this.opts.budget.tryReserve(serverName);if(reservation==="refused"){const transport=mcpTransportOf(cfg);this.opts.budget.recordRefusal(serverName,transport);throw new BudgetExhaustedError(serverName,this.opts.budget.getBudget()??0,this.opts.budget.getReservedCount())}reservationResult=reservation}if(!poolable){try{return await this.createUnpooledConnection(serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry)}catch(err){this.rollbackReservationOnSpawnFailure(reservationResult,serverName);throw err}}if(id===void 0){throw new Error("unreachable: poolable && id === undefined")}let inFlight=this.spawnInFlight.get(id);if(!inFlight){const spawnPromise=this.spawnEntry(serverName,cfg,id);inFlight=spawnPromise.finally(()=>{this.spawnInFlight.delete(id)}).catch(err=>{this.rollbackReservationOnSpawnFailure(reservationResult,serverName);throw err});this.spawnInFlight.set(id,inFlight)}this.indexAttach(sessionId,id);let entry;try{entry=await inFlight}catch(err){this.indexDetach(sessionId,id);throw err}if(!this.entries.has(id)||entry.isTerminated()){this.indexDetach(sessionId,id);throw new Error(`PoolEntry ${id} torn down before attach (concurrent release)`)}try{const conn=this.attachPooledSession(entry,id,serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry);this.indexAttach(sessionId,id);return conn}catch(err){this.indexDetach(sessionId,id);throw err}}release(id,sessionId){const entry=this.entries.get(id);if(!entry)return;entry.detach(sessionId);this.indexDetach(sessionId,id);if(entry.refs.size===0){if(this.unpooledIds.has(id)){void entry.forceShutdown("manual");return}entry.startDrainTimer(this.opts.drainDelayMs)}}releaseSession(sessionId){const ids=this.sessionToEntries.get(sessionId);if(!ids)return;const idList=[...ids];for(const id of idList){const entry=this.entries.get(id);if(!entry)continue;entry.detach(sessionId);if(entry.refs.size===0){if(this.unpooledIds.has(id)){void entry.forceShutdown("manual");continue}entry.startDrainTimer(this.opts.drainDelayMs)}}this.sessionToEntries.delete(sessionId)}async restartByName(serverName,opts){if(this.draining)return[];const matching=[...this.entries.values()].filter(e=>e.serverName===serverName&&(opts?.entryIndex===void 0||e.entryIndex===opts.entryIndex));if(matching.length===0)return[];return Promise.all(matching.map(async entry=>{const started=Date.now();try{await entry.restart();if(entry.refs.size===0&&!this.unpooledIds.has(entry.id)){entry.startDrainTimer(this.opts.drainDelayMs)}return{entryIndex:entry.entryIndex,restarted:true,durationMs:Date.now()-started}}catch(err){return{entryIndex:entry.entryIndex,restarted:false,reason:String(err instanceof Error?err.message:err)}}}))}getSnapshot(){const byName=new Map;let total=0;let subprocessCount=0;for(const entry of this.entries.values()){const status=entry.getLocalStatus();if(status==="connected"){total+=1;if(entry.transportKind==="stdio"){subprocessCount+=1}}const row=byName.get(entry.serverName)??{entryCount:0,entrySummary:[]};row.entryCount+=1;row.entrySummary.push({entryIndex:entry.entryIndex,refs:entry.refs.size,status});byName.set(entry.serverName,row)}return{total,subprocessCount,byName:Object.fromEntries(byName.entries())}}aggregateStatusByName(serverName){let sawConnecting=false;for(const entry of this.entries.values()){if(entry.serverName!==serverName)continue;const s=entry.getLocalStatus();if(s==="connected")return"connected";if(s==="connecting")sawConnecting=true}return sawConnecting?"connecting":"disconnected"}async drainAll(opts){const timeoutMs=opts?.timeoutMs??1e4;const force=opts?.force??false;this.draining=true;const deadline=Date.now()+timeoutMs;if(this.spawnInFlight.size>0){const spawnWait=Promise.allSettled([...this.spawnInFlight.values()]);let inflightTimer;await Promise.race([spawnWait.then(()=>{if(inflightTimer)clearTimeout(inflightTimer)}),new Promise(resolve9=>{inflightTimer=setTimeout(()=>{const stuckIds=[...this.spawnInFlight.keys()];debugLogger3.warn(`drainAll: spawnInFlight wait timed out after ${timeoutMs}ms; ${stuckIds.length} spawn(s) still in-flight: ${stuckIds.join(", ")}. Proceeding with drain.`);resolve9()},Math.max(0,deadline-Date.now()));inflightTimer.unref?.()})])}const entries=[...this.entries.values()];const drained=[];const errors=[];const shutdownPromises=entries.map(entry=>entry.forceShutdown(force?"manual":"drain_timer").then(()=>drained.push(entry.entryIndex)).catch(err=>{errors.push({entryIndex:entry.entryIndex,serverName:entry.serverName,error:String(err instanceof Error?err.message:err)})}));let drainTimer;const remaining=Math.max(0,deadline-Date.now());await Promise.race([Promise.all(shutdownPromises).then(()=>{if(drainTimer)clearTimeout(drainTimer)}),new Promise(resolve9=>{drainTimer=setTimeout(()=>resolve9(),remaining);drainTimer.unref?.()})]);const drainedCount=drained.length;const errorsCount=errors.length;const forced=Math.max(0,entries.length-drainedCount-errorsCount);const errorsCopy=[...errors];this.entries.clear();this.unpooledIds.clear();this.sessionToEntries.clear();this.spawnInFlight.clear();return{drained:drainedCount,forced,errors:errorsCopy}}attachPooledSession(entry,id,serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry){const view=new SessionMcpView(sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry,sessionId,serverName,cfg);return entry.attach(sessionId,view,{release:__name(()=>this.release(id,sessionId),"release")})}rollbackReservationOnSpawnFailure(reservationResult,serverName){if(this.opts.budget!==void 0&&reservationResult==="reserved"&&!this.hasNameSibling(serverName)){this.opts.budget.release(serverName)}}evictEntry(id,entry){if(entry===void 0)return;const current=this.entries.get(id);if(current!==entry)return;this.entries.delete(id);if(this.opts.budget!==void 0){if(!this.hasNameSibling(entry.serverName)){this.opts.budget.release(entry.serverName)}}}async spawnEntry(serverName,cfg,id){const entryIndex=this.allocateEntryIndex(serverName);const transport=mcpTransportOf(cfg);const entryOpts=this.opts.entryOptions(transport);const client=new McpClient(serverName,cfg,poisonedToolRegistry(serverName),poisonedPromptRegistry(serverName),this.opts.workspaceContext,this.opts.debugMode,this.opts.sendSdkMcpMessage);const entryRef={current:void 0};const onClosedForThisEntry=__name(closedId=>{this.evictEntry(closedId,entryRef.current)},"onClosedForThisEntry");const entry=new PoolEntry(id,serverName,entryIndex,cfg,client,this.cliConfig,entryOpts,onClosedForThisEntry,name=>this.aggregateStatusByName(name));entryRef.current=entry;try{const timeoutMs=discoveryTimeoutFor(cfg);const snap=await runWithTimeout((async()=>{await client.connect();return client.discoverAndReturn(this.cliConfig,{applyConfigFilters:false})})(),timeoutMs,`pool spawn for ${id} (pool will roll back the spawn and free its budget slot)`);if(this.draining){debugLogger3.warn(`Spawn for ${id} completed while pool is draining; discarding entry`);try{await entry.forceShutdown("manual")}catch{}throw new Error(`McpTransportPool is draining; discarded spawn ${id}`)}this.entries.set(id,entry);entry.markActive(snap.tools,snap.prompts,snap.resources);debugLogger3.info(`Spawned pool entry ${id} (entryIndex=${entryIndex}, transport=${transport})`);return entry}catch(err){debugLogger3.error(`Failed to spawn pool entry for '${serverName}' (id=${id}, transport=${transport}): ${String(err)}`);try{await entry.forceShutdown("manual")}catch{}this.entries.delete(id);try{await client.disconnect()}catch{}throw err}}allocateEntryIndex(serverName){const next=this.nextIndexByName.get(serverName)??0;this.nextIndexByName.set(serverName,next+1);return next}indexAttach(sessionId,id){let ids=this.sessionToEntries.get(sessionId);if(!ids){ids=new Set;this.sessionToEntries.set(sessionId,ids)}ids.add(id)}indexDetach(sessionId,id){const ids=this.sessionToEntries.get(sessionId);if(!ids)return;ids.delete(id);if(ids.size===0)this.sessionToEntries.delete(sessionId)}async createUnpooledConnection(serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry){const entryIndex=this.allocateEntryIndex(serverName);const id=`${serverName}::unpooled-${entryIndex}`;const transport=mcpTransportOf(cfg);const entryOpts=this.opts.entryOptions(transport);const client=new McpClient(serverName,cfg,sessionToolRegistry,sessionPromptRegistry,this.opts.workspaceContext,this.opts.debugMode,this.opts.sendSdkMcpMessage);const view=new SessionMcpView(sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry,sessionId,serverName,cfg);const entry=new PoolEntry(id,serverName,entryIndex,cfg,client,this.cliConfig,entryOpts,closedId=>{this.entries.delete(closedId);this.unpooledIds.delete(closedId);if(this.opts.budget!==void 0){if(!this.hasNameSibling(serverName)){this.opts.budget.release(serverName)}}},()=>client.getStatus());try{this.entries.set(id,entry);this.unpooledIds.add(id);this.indexAttach(sessionId,id);const timeoutMs=discoveryTimeoutFor(cfg);const snap=await runWithTimeout((async()=>{await client.connect();return await client.discoverAndReturn(this.cliConfig,{applyConfigFilters:false})})(),timeoutMs,`unpooled spawn for ${id} (pool will roll back the spawn and free its budget slot)`);if(this.draining||!this.entries.has(id)||entry.isTerminated()){try{view.teardown()}catch{}try{await entry.forceShutdown("manual")}catch{}this.indexDetach(sessionId,id);throw new Error(`McpTransportPool is draining or unpooled ${id} was cancelled`)}entry.markActive(snap.tools,snap.prompts,snap.resources);const conn=entry.attach(sessionId,view,{release:__name(()=>{this.indexDetach(sessionId,id);void entry.forceShutdown("manual")},"release")});return conn}catch(err){try{await entry.forceShutdown("manual")}catch{}this.entries.delete(id);this.unpooledIds.delete(id);this.indexDetach(sessionId,id);try{await client.disconnect()}catch{}throw err}}};function poisonedToolRegistry(serverName){return{registerTool(){throw new Error(`Pool invariant violated: poisoned ToolRegistry for ${serverName} received registerTool. A pool path must use discoverAndReturn, not discover.`)}}}__name(poisonedToolRegistry,"poisonedToolRegistry");function poisonedPromptRegistry(serverName){return{registerPrompt(){throw new Error(`Pool invariant violated: poisoned PromptRegistry for ${serverName} received registerPrompt. A pool path must use discoverAndReturn.`)}}}__name(poisonedPromptRegistry,"poisonedPromptRegistry");init_esbuild_shims();var debugLogger4=createDebugLogger("McpPool:Budget");var WorkspaceMcpBudget=class{static{__name(this,"WorkspaceMcpBudget")}clientBudget;mode;onEvent;reservedSlots=new Set;pendingRefusalNames=new Set;pendingRefusalTransports=new Map;lastRefusedServerNames=[];warnArmed=true;bulkPassDepth=0;constructor(opts){this.clientBudget=opts.clientBudget;this.mode=opts.mode;this.onEvent=opts.mode==="off"?void 0:opts.onEvent}getMode(){return this.mode}getBudget(){return this.clientBudget}getReservedSlots(){return Array.from(this.reservedSlots)}getRefusedServerNames(){return this.lastRefusedServerNames}getReservedCount(){return this.reservedSlots.size}tryReserve(serverName){if(this.reservedSlots.has(serverName))return"already_held";if(this.clientBudget===void 0||this.mode==="off"){return"reserved"}if(this.mode==="enforce"&&this.reservedSlots.size>=this.clientBudget){return"refused"}this.reservedSlots.add(serverName);this.evaluateState();return"reserved"}release(serverName){const had=this.reservedSlots.delete(serverName);if(had)this.evaluateState();return had}recordRefusal(serverName,transport){if(this.mode!=="enforce")return;this.pendingRefusalNames.add(serverName);this.pendingRefusalTransports.set(serverName,transport);debugLogger4.warn(`MCP server '${serverName}' refused at pool acquire (budget exhausted, budget=${this.clientBudget}, mode=${this.mode})`);if(this.bulkPassDepth===0){this.flushRefusedBatch()}}beginBulkPass(){if(this.bulkPassDepth===0){this.lastRefusedServerNames=[]}this.bulkPassDepth+=1}endBulkPass(){if(this.bulkPassDepth===0){debugLogger4.warn("WorkspaceMcpBudget.endBulkPass called without matching beginBulkPass; ignoring");return}this.bulkPassDepth-=1;if(this.bulkPassDepth>0)return;this.flushRefusedBatch()}flushRefusedBatch(){if(this.pendingRefusalNames.size===0)return;if(this.clientBudget===void 0||this.mode!=="enforce"){this.pendingRefusalNames.clear();this.pendingRefusalTransports.clear();return}const refusedServers=[];const names=[];for(const name of this.pendingRefusalNames){const transport=this.pendingRefusalTransports.get(name)??"unknown";refusedServers.push({name,transport,reason:"budget_exhausted"});names.push(name)}this.lastRefusedServerNames=Object.freeze(names);this.pendingRefusalNames.clear();this.pendingRefusalTransports.clear();if(this.onEvent){try{this.onEvent({kind:"refused_batch",refusedServers,budget:this.clientBudget,liveCount:this.reservedSlots.size,reservedCount:this.reservedSlots.size,mode:"enforce"})}catch(err){debugLogger4.error(`WorkspaceMcpBudget refused_batch event delivery failed: ${err instanceof Error?err.message:String(err)}`)}}}evaluateState(){if(this.mode==="off"||this.clientBudget===void 0)return;const ratio=this.reservedSlots.size/this.clientBudget;if(this.warnArmed&&ratio>=MCP_BUDGET_WARN_FRACTION){this.warnArmed=false;debugLogger4.info(`MCP workspace budget warning fired (ratio=${ratio.toFixed(2)}, reservedCount=${this.reservedSlots.size}, budget=${this.clientBudget}, mode=${this.mode})`);if(this.onEvent){try{this.onEvent({kind:"budget_warning",liveCount:this.reservedSlots.size,reservedCount:this.reservedSlots.size,budget:this.clientBudget,thresholdRatio:MCP_BUDGET_WARN_FRACTION,mode:this.mode})}catch(err){debugLogger4.error(`WorkspaceMcpBudget budget_warning event delivery failed: ${err instanceof Error?err.message:String(err)}`)}}}else if(!this.warnArmed&&ratio<MCP_BUDGET_REARM_FRACTION){this.warnArmed=true;debugLogger4.info(`MCP workspace budget warning re-armed (ratio=${ratio.toFixed(2)}, budget=${this.clientBudget}; next 75% crossing will fire)`)}}};init_esbuild_shims();function preservePlaceholders(value,resolved,original){if(typeof original==="string"&&value===resolved)return original;if(Array.isArray(value)&&Array.isArray(resolved)&&Array.isArray(original)){return value.map((entry,index)=>preservePlaceholders(entry,resolved[index],original[index]))}if(value&&resolved&&original&&typeof value==="object"&&!Array.isArray(value)&&typeof resolved==="object"&&!Array.isArray(resolved)&&typeof original==="object"&&!Array.isArray(original)){return Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,preservePlaceholders(entry,resolved[key],original[key])]))}return value}__name(preservePlaceholders,"preservePlaceholders");function preserveModelProviderPlaceholders(models,provider,resolvedProviders,rawProviders,mapping){const pairs=Object.entries(resolvedProviders).flatMap(([providerId,entries])=>{if(!Array.isArray(entries))return[];return entries.flatMap((entry,index)=>{const resolved=provider==="openai"?getModelsForProviderProtocol({[providerId]:[entry]},"openai",mapping)[0]:providerId===provider?entry:void 0;return resolved?[{providerId,resolved,source:entry,raw:rawProviders[providerId]?.[index]??entry}]:[]})});return models.map(model=>{const matches=pairs.filter(({resolved})=>resolved.id===model.id&&resolved.baseUrl===model.baseUrl&&tryResolveModelProtocol(provider,resolved,mapping)===tryResolveModelProtocol(provider,model,mapping));const sourceMatches=matches.filter(pair=>pair.providerId===matches[0]?.providerId);if(sourceMatches.length>1&&sourceMatches.some(pair=>JSON.stringify(pair.raw)!==JSON.stringify(pair.source))){throw new Error("Cannot preserve placeholders in an ambiguous model configuration. Remove duplicate model entries first.")}const match=matches[0];return match?preservePlaceholders(model,match.resolved,match.raw):model})}__name(preserveModelProviderPlaceholders,"preserveModelProviderPlaceholders");init_esbuild_shims();init_esbuild_shims();var DISCOVERY_TIMEOUT_MS=5e3;var DISCOVERY_MAX_BYTES=1024*1024;var MAX_MODEL_ID_LENGTH=256;var UNSAFE_MODEL_ID_CHARS=/[,\p{C}\p{Zl}\p{Zp}]/u;function readModels(value){if(!value||typeof value!=="object"||!("data"in value)){return null}const data=value.data;if(!Array.isArray(data)){return null}const models=[];const seen=new Set;for(const item of data){if(!item||typeof item!=="object"||!("id"in item)){return null}const id=item.id;if(typeof id!=="string"){return null}const trimmedId=id.trim();if(trimmedId&&trimmedId.length<=MAX_MODEL_ID_LENGTH&&!UNSAFE_MODEL_ID_CHARS.test(trimmedId)&&!seen.has(trimmedId)){seen.add(trimmedId);const created=item.created;const creationTime=typeof created==="number"&&Number.isFinite(created)&&created>=0?created:void 0;models.push({id:trimmedId,...creationTime===void 0?{}:{created:creationTime}})}}return models.length>0?models:null}__name(readModels,"readModels");function mergeModelSpecs(discoveredModels,staticModels){const staticModelsById=new Map(staticModels.map(model=>[model.id,model]));const orderedModels=[...discoveredModels];if(orderedModels.every(model=>model.created!==void 0)){orderedModels.sort((left,right)=>(right.created??0)-(left.created??0))}return orderedModels.map(({id})=>staticModelsById.get(id)??{id})}__name(mergeModelSpecs,"mergeModelSpecs");async function discoverProviderModels({baseUrl,apiKey,staticModels,signal}){const normalizedBaseUrl=baseUrl.trim();const normalizedApiKey=apiKey.trim();if(!normalizedBaseUrl||!normalizedApiKey){return null}try{const modelsUrl=`${normalizedBaseUrl.replace(/\/+$/,"")}/models`;const result=await fetchWithPolicy(modelsUrl,{timeoutMs:DISCOVERY_TIMEOUT_MS,maxBytes:DISCOVERY_MAX_BYTES,maxRedirects:2,headers:{Accept:"application/json",Authorization:`Bearer ${normalizedApiKey}`},signal});if(result.kind!=="response"||result.status<200||result.status>=300){return null}const models=readModels(JSON.parse(result.body.toString("utf8")));return models?mergeModelSpecs(models,staticModels):null}catch{return null}}__name(discoverProviderModels,"discoverProviderModels");init_esbuild_shims();var IMAGE_CAPABILITY=Object.freeze({autoHandlesWrongModel:true,maxBytes:VISION_BRIDGE_MAX_IMAGE_BASE64_BYTES,maxImagesPerTurn:VISION_BRIDGE_MAX_IMAGES});init_esbuild_shims();var debugLogger5=createDebugLogger("SESSION_RECAP");var RECENT_MESSAGE_WINDOW=30;var RECAP_SYSTEM_PROMPT=`You generate session recaps for a programming assistant CLI.
3
+ import{MAX_DROPPED_MSG_IDS,MAX_FRAME_BYTES,MAX_RETAINED_REPLY_TOKEN_CHARS,MAX_SENDER_KEY_CHARS,MAX_SOCKET_PATH_BYTES,SOCKET_DIR_NAME,isLocalIpcPath,parsePeerAuthLine,parsePeerFrame,peerSenderKey,probePeerSocketVerdict,resolvePeerSocketCandidates}from"./chunk-UNDRWCST.js";import{scanForSecrets}from"./chunk-54CHQYA3.js";import{BudgetExhaustedError,IDE_DEFINITIONS,MCP_BUDGET_REARM_FRACTION,MCP_BUDGET_WARN_FRACTION,McpClient,ORPHAN_TOOL_USE_REPAIR_REASON,POOLED_TRANSPORTS_DEFAULT,QWEN_CODE_COMPANION_EXTENSION_NAME,SessionService,StandardFileSystemService,aggregateUsage,buildSessionHistoryFromConversation,buildSyntheticToolResponseParts,classifyShellCommandSafety,classifyShellCommandSafetyInDirectory,coerceMcpFilterEntries,connectionIdOf,convertToFunctionErrorResponse,convertToFunctionResponse,createForkedChat,detectTurnInterruption,discoveryTimeoutFor,estimateContentTokens,evaluateToolInvocationGuard,finalizeToolResponses,getCacheSafeParams,getCacheSafeParamsSessionId,getTimeRangeBounds,isPoolable,listDescendantPids,listExistingSkillDirNames,loadUsageHistoryWithLive,mcpSessionMetadataKey,mcpTransportOf,normalizeMcpIncludeEntry,observeToolResultBoundary,parseConnectionId,recursivelyHydrateStrings,repairOrphanedToolUseTurns,runForkedAgent,runWithForkedChatModel,runWithTimeout,sigtermPids,stripToolResultImages,toolResultBoundaryArtifact,toolResultPartDiagnosticValues,withoutAutoMemorySnapshots}from"./chunk-PFKTTUGS.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{runGit,runGitCapture,streamGitRecords}from"./chunk-I44IFX3I.js";import{hasVerifiableInode,openNoFollow,openSyncNoFollow}from"./chunk-PSKT6KWO.js";import{projectUserTranscriptForDisplay}from"./chunk-UHJUDWBV.js";import{toolSearchBridgeSentence}from"./chunk-DNYXZVBT.js";import{flattenPeerLabel}from"./chunk-VMRQ6FA2.js";import{isPidAlive}from"./chunk-JB3XRNK7.js";import{getProjectSkillsRoot}from"./chunk-NVXFGZ4Z.js";import{parse}from"./chunk-PNF77EBK.js";import{Ns,zs}from"./chunk-TASTRW4D.js";import{fetchWithPolicy}from"./chunk-IUVB7EIZ.js";import{isDeferredToolBridgeAvailable}from"./chunk-T5XGTSQU.js";import{require_picomatch}from"./chunk-THN4FBQ7.js";import{BUILT_IN_OUTPUT_STYLES,getBuiltInOutputStyle}from"./chunk-KVSDMMDD.js";import{NO_EXEC_CONFIG}from"./chunk-744VRMDB.js";import{require_proper_lockfile}from"./chunk-YIW3H46P.js";import{DEFAULT_WRITE_QUEUE_BYTES,collectPtyProcessTree,getPtyBudgetStats,processPtyBudget}from"./chunk-6EDEOERB.js";import{disposeConoutWorker,loadPty,loadXtermHeadless,noteConPtyHostReleased,releaseConPtyHost}from"./chunk-QTCO5I4C.js";import{stripAnsi}from"./chunk-YGLM5XPP.js";import{resolveBundleDir}from"./chunk-4NPYOXJO.js";import{escapeJsonTagCharacters}from"./chunk-NTRFETZB.js";import{COMBINED_PASS_TOLERANCE_FACTOR,TOOL_OUTPUT_TRUNCATED_PREFIX,TRUNCATION_FALLBACK_ENVELOPE_SLACK,addMCPStatusChangeListener,removeMCPStatusChangeListener,updateMCPServerStatus}from"./chunk-MJEL7DIE.js";import{E_TIMEOUT,Mutex,withTimeout}from"./chunk-JEV36CS7.js";import{runSideQuery}from"./chunk-FCQWRGW5.js";import{MEMORY_SECTION_HEADER,VISION_BRIDGE_MAX_IMAGES,VISION_BRIDGE_MAX_IMAGE_BASE64_BYTES,detectFileType,getCurrentMemoryFilename,isCacheableReadResult,isWithinRoot,processSingleFileContent}from"./chunk-6JHMYZNS.js";import{getInvocationContext}from"./chunk-6QJWBGMS.js";import{atomicWriteFile,atomicWriteJSON}from"./chunk-2GF3E5MI.js";import{getModelsForProviderProtocol,tryResolveModelProtocol}from"./chunk-AJ75BPTA.js";import{DEFAULT_IMAGE_TOKEN_ESTIMATE,estimatePartChars}from"./chunk-Q6UAOTP3.js";import{isBinary,normalizeContent,stripAnsiAndControl,stripHtmlComments}from"./chunk-DBRQGEEI.js";import{cloneApiHistory,getFolderStructure,getStartupContextLength,stripSystemReminderBlocks}from"./chunk-DMM5LJWL.js";import{getQwenIgnoreFileNames,require_ignore}from"./chunk-LWVCLDHV.js";import{ToolNames,canonicalToolName}from"./chunk-SBZFGYYS.js";import{createDebugLogger,isDebugLogFileEnabled}from"./chunk-46KPDLFH.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{PATH_ARG_KEYS,QWEN_DIR,tildeifyPath,unescapePath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage,isAbortError,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__require,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonFormatter=class{static{__name(this,"JsonFormatter")}format(response,stats,error){const output={};if(response!==void 0){output.response=stripAnsi(response)}if(stats){output.stats=stats}if(error){output.error=error}return JSON.stringify(output,null,2)}formatError(error,code){const jsonError={type:error.constructor.name,message:stripAnsi(error.message),...code&&{code}};return this.format(void 0,void 0,jsonError)}};init_esbuild_shims();function createPlanId(sessionId,historyLength){return`${sessionId}:${historyLength}`}__name(createPlanId,"createPlanId");function buildVisibleNotice(kind,repairs,historyGaps){if(kind==="clean"){return void 0}if(kind==="degraded_history"){return`Resumed session history is incomplete: detected ${historyGaps.length} missing parent link(s). Automatic continuation is disabled for this recovery.`}if(kind==="interrupted_prompt"){return"Previous session appears to have stopped after user input before the model completed a response."}const synthesized=repairs.filter(repair=>repair.type==="synthesized_tool_result").length;if(synthesized>0){return`Previous session appears to have stopped during tool execution. Synthesized ${synthesized} failed tool result(s) so the history can continue safely.`}return"Previous session appears to have stopped during tool execution."}__name(buildVisibleNotice,"buildVisibleNotice");function buildSessionRecoveryPlan({sessionId,conversation,historyGaps,options}){return buildSessionRecoveryPlanFromApiHistory({sessionId,...buildSessionHistoryFromConversation(conversation),historyGaps,options})}__name(buildSessionRecoveryPlan,"buildSessionRecoveryPlan");function buildSessionRecoveryPlanFromApiHistory({sessionId,apiHistory:inputApiHistory,completedToolCallIds,trailingSystemNotifications,historyGaps,options}){const originalApiHistory=inputApiHistory;const gaps=historyGaps??[];const planId=createPlanId(sessionId,originalApiHistory.length);const apiHistory=cloneApiHistory(originalApiHistory);const repairResult=repairOrphanedToolUseTurns(apiHistory);const repairs=[...repairResult.injected.map(repair=>({type:"synthesized_tool_result",callId:repair.callId,name:repair.name})),...repairResult.droppedDuplicates.map(repair=>({type:"dropped_duplicate_tool_result",callId:repair.callId,name:repair.name})),...gaps.map(gap=>({type:"history_gap",childUuid:gap.childUuid,missingParentUuid:gap.missingParentUuid}))];if(gaps.length>0){return{planId,sessionId,kind:"degraded_history",originalApiHistory,apiHistory,repairs,canContinue:false,canAutoContinue:false,requiresUserConfirmation:true,visibleNotice:buildVisibleNotice("degraded_history",repairs,gaps)}}const interruption=detectTurnInterruption(originalApiHistory,completedToolCallIds,trailingSystemNotifications);if(interruption.kind==="none"){return{planId,sessionId,kind:"clean",originalApiHistory,apiHistory,repairs,canContinue:false,canAutoContinue:false,requiresUserConfirmation:false}}if(interruption.kind==="interrupted_prompt"){const continuation2={mode:"retry_user_parts",parts:interruption.parts,displayText:"Continue interrupted user prompt"};return{planId,sessionId,kind:"interrupted_prompt",originalApiHistory,apiHistory,repairs,canContinue:true,canAutoContinue:options?.allowAutoContinue===true,requiresUserConfirmation:options?.allowAutoContinue!==true,visibleNotice:buildVisibleNotice("interrupted_prompt",repairs,gaps),continuation:continuation2}}const continuation={mode:"tool_result_parts",parts:buildSyntheticToolResponseParts(interruption.danglingCalls,ORPHAN_TOOL_USE_REPAIR_REASON),displayText:"Continue interrupted tool turn"};return{planId,sessionId,kind:"interrupted_turn",originalApiHistory,apiHistory,repairs,canContinue:true,canAutoContinue:false,requiresUserConfirmation:true,visibleNotice:buildVisibleNotice("interrupted_turn",repairs,gaps),continuation}}__name(buildSessionRecoveryPlanFromApiHistory,"buildSessionRecoveryPlanFromApiHistory");init_esbuild_shims();init_esbuild_shims();import{EventEmitter}from"node:events";init_esbuild_shims();var debugLogger=createDebugLogger("McpPool:Entry");function defaultPoolEntryOptions(transport){const isRemote=transport==="http"||transport==="sse"||transport==="websocket";return{drainDelayMs:3e4,maxIdleMs:5*6e4,maxReconnectAttempts:isRemote?5:3,reconnectStrategy:isRemote?{kind:"exponential",baseMs:1e3,capMs:16e3}:{kind:"fixed",delayMs:5e3}}}__name(defaultPoolEntryOptions,"defaultPoolEntryOptions");var PoolEntry=class{constructor(id,serverName,entryIndex,cfg,client,cliConfig,opts,onClosed,aggregateStatusByName){this.id=id;this.serverName=serverName;this.entryIndex=entryIndex;this.cfg=cfg;this.client=client;this.cliConfig=cliConfig;this.opts=opts;this.onClosed=onClosed;this.aggregateStatusByName=aggregateStatusByName;this.transportId=connectionIdOf(serverName,cfg);this.emitter.setMaxListeners(0);this.statusChangeListener=(name,status)=>{if(name!==this.serverName)return;if(status===void 0)return;if(this.suppressNextStatusEcho){this.suppressNextStatusEcho=false;return}if(this.client.getStatus()!==status)return;if(status===this.localStatus)return;this.localStatus=status;if(status==="disconnected"&&(this.state==="active"||this.state==="draining")&&!this.restartInProgress){const wasDraining=this.state==="draining";this.state="failed";if(wasDraining){this.cancelDrainTimer()}if(this.maxIdleTimer){clearTimeout(this.maxIdleTimer);this.maxIdleTimer=void 0}if(this.statusChangeListener){removeMCPStatusChangeListener(this.statusChangeListener);this.statusChangeListener=void 0}debugLogger.error(`PoolEntry ${this.id} silent transport drop (prev state='${wasDraining?"draining":"active"}', localStatus\u2192DISCONNECTED). Transitioning to 'failed'; evicting from pool.entries + pooledConnections (W122 R20).`);const upstreamError=this.client.getLastTransportError();this.emit({kind:"failed",serverName:this.serverName,generation:this._generation,lastError:upstreamError?`transport disconnected (silent transport drop): ${upstreamError.message}`:"transport disconnected (silent transport drop)"});for(const[sid]of[...this.subscribers]){this.detach(sid)}void this.sweepAndDisconnect("silent_drop").then(result=>{const partialSignal=result.descendantsFound!==void 0&&result.descendantsSignaled!==void 0&&result.descendantsSignaled<result.descendantsFound;if(result.pidSweepError!==void 0||partialSignal){debugLogger.warn(`PoolEntry ${this.id} silent-drop sweep observability: descendantsFound=${result.descendantsFound??"unknown"}, descendantsSignaled=${result.descendantsSignaled??"unknown"}, pidSweepError=${result.pidSweepError?.message??"none"}. Possible orphan-process pressure \u2014 operator should check for lingering subprocess descendants of the dead transport.`)}this.updateGlobalStatus()},()=>{this.updateGlobalStatus()});this.updateGlobalStatus();this.onClosed(this.id)}};addMCPStatusChangeListener(this.statusChangeListener)}static{__name(this,"PoolEntry")}localStatus="connecting";state="spawning";_generation=0;refs=new Set;subscribers=new Map;subscriberHandles=new Map;toolsSnapshot=[];promptsSnapshot=[];resourcesSnapshot=[];drainTimer;maxIdleTimer;firstIdleAt;restartInFlight;restartInProgress=false;emitter=new EventEmitter;statusChangeListener;suppressNextStatusEcho=false;transportId;get generation(){return this._generation}get currentState(){return this.state}get transportKind(){return mcpTransportOf(this.cfg)}isTerminated(){return this.state==="closed"||this.state==="failed"}markActive(initialTools,initialPrompts,initialResources){if(this.state==="closed"||this.state==="failed")return;this.toolsSnapshot=initialTools;this.promptsSnapshot=initialPrompts;this.resourcesSnapshot=initialResources;this.state="active";this.localStatus="connected";this.updateGlobalStatus()}attach(sessionId,view,opts){if(this.state==="closed"||this.state==="failed"){throw new Error(`Cannot attach to PoolEntry ${this.id} in state ${this.state}`)}const previousState=this.state;const hadRef=this.refs.has(sessionId);const previousView=this.subscribers.get(sessionId);const previousHandle=this.subscriberHandles.get(sessionId);this.refs.add(sessionId);this.subscribers.set(sessionId,view);this.cancelDrainTimer();if(this.state==="draining")this.state="active";if(this.state==="active"&&opts?.skipReplay!==true){try{view.applyTools(this.toolsSnapshot);view.applyPrompts(this.promptsSnapshot);view.applyResources(this.resourcesSnapshot)}catch(err){if(!hadRef){this.refs.delete(sessionId);this.subscribers.delete(sessionId);this.subscriberHandles.delete(sessionId);try{view.teardown()}catch{}}else if(previousView){this.subscribers.set(sessionId,previousView);if(previousHandle){this.subscriberHandles.set(sessionId,previousHandle)}}if(previousState==="draining"&&this.refs.size===0){this.startDrainTimer(this.opts.drainDelayMs)}else{this.state=previousState}debugLogger.error(`Snapshot replay failed for ${sessionId}/${this.serverName}: ${String(err)}`);throw err}}const handle=new PooledConnectionImpl(this,sessionId,opts?.release);this.subscriberHandles.set(sessionId,handle);return handle}updateSessionConfig(sessionId,cfg){if(this.isTerminated()){throw new Error(`Cannot update config on PoolEntry ${this.id} in state ${this.state}`)}const view=this.subscribers.get(sessionId);if(!view){throw new Error(`Cannot update config for detached session ${sessionId} on PoolEntry ${this.id}`)}if(!view.updateConfig(cfg))return;if(this.state==="active"){view.applyTools(this.toolsSnapshot);view.applyPrompts(this.promptsSnapshot);view.applyResources(this.resourcesSnapshot)}}detach(sessionId){const view=this.subscribers.get(sessionId);if(view){try{view.teardown()}catch(err){debugLogger.error(`View teardown failed for ${sessionId}/${this.serverName}: ${String(err)}`)}}this.subscribers.delete(sessionId);this.subscriberHandles.delete(sessionId);this.refs.delete(sessionId)}startDrainTimer(delayMs){this.cancelDrainTimer();this.state="draining";if(this.firstIdleAt===void 0){this.firstIdleAt=Date.now();this.maxIdleTimer=setTimeout(()=>{if(this.refs.size>0){debugLogger.debug(`PoolEntry ${this.id} max-idle reached but ${this.refs.size} sessions active; deferring close, resetting first-idle window`);this.maxIdleTimer=void 0;this.firstIdleAt=void 0;return}debugLogger.warn(`PoolEntry ${this.id} hit MAX_IDLE_MS (${this.opts.maxIdleMs}ms); force-closing`);void this.forceShutdown("max_idle")},this.opts.maxIdleMs);this.maxIdleTimer.unref?.()}this.drainTimer=setTimeout(()=>{void this.forceShutdown("drain_timer")},delayMs);this.drainTimer.unref?.()}cancelDrainTimer(){if(this.drainTimer){clearTimeout(this.drainTimer);this.drainTimer=void 0}}async forceShutdown(reason){if(this.state==="closed"||this.state==="failed")return;this.state="closed";this.localStatus="disconnected";this.suppressNextStatusEcho=true;this.cancelDrainTimer();if(this.maxIdleTimer){clearTimeout(this.maxIdleTimer);this.maxIdleTimer=void 0}if(this.statusChangeListener){removeMCPStatusChangeListener(this.statusChangeListener);this.statusChangeListener=void 0}this.emit({kind:"disconnected",serverName:this.serverName,generation:this._generation,reason:"transport_closed"});for(const[sid]of this.subscribers){this.detach(sid)}await this.sweepAndDisconnect(reason);this.updateGlobalStatus();this.onClosed(this.id)}async sweepAndDisconnect(reason){const result={};try{const rootPid=this.client.getTransportPid?.();if(rootPid!==void 0){const descendants=await listDescendantPids(rootPid);if(descendants.length>0){result.descendantsFound=descendants.length;result.descendantsSignaled=sigtermPids(descendants);debugLogger.debug(`Sent SIGTERM to ${result.descendantsSignaled}/${descendants.length} descendants of pid ${rootPid} for ${this.id} (${reason})`)}}}catch(err){result.pidSweepError=err instanceof Error?err:new Error(String(err));debugLogger.warn(`Descendant pid sweep failed for ${this.id} (${reason}): ${String(err)}. Proceeding with disconnect.`)}try{await this.client.disconnect()}catch(err){debugLogger.error(`client.disconnect failed for ${this.id} (${reason}): ${String(err)}`)}return result}async restart(){if(this.restartInFlight)return this.restartInFlight;this.restartInFlight=this.doRestart().finally(()=>{this.restartInFlight=void 0});return this.restartInFlight}async doRestart(){if(this.state==="closed"||this.state==="failed"){throw new Error(`Cannot restart PoolEntry ${this.id} in state ${this.state}`)}this.restartInProgress=true;try{return await this.doRestartInner()}finally{this.restartInProgress=false}}async doRestartInner(){this.cancelDrainTimer();if(this.maxIdleTimer){clearTimeout(this.maxIdleTimer);this.maxIdleTimer=void 0}this.firstIdleAt=void 0;if(this.state==="draining"){this.state="active"}const oldGen=this._generation;this._generation+=1;this.emit({kind:"disconnected",serverName:this.serverName,generation:oldGen,reason:"restart"});await this.sweepAndDisconnect("restart");let snap;try{const timeoutMs=discoveryTimeoutFor(this.cfg);snap=await runWithTimeout((async()=>{await this.client.connect();return this.client.discoverAndReturn(this.cliConfig,{applyConfigFilters:false})})(),timeoutMs,`pool restart for ${this.id} (pool will roll back the restart and free its budget slot)`)}catch(err){debugLogger.error(`Restart of ${this.id} failed at connect/discover: ${String(err)}. Transitioning to 'failed'.`);await this.sweepAndDisconnect("restart_failed");this.state="failed";this.localStatus="disconnected";this.suppressNextStatusEcho=true;this.updateGlobalStatus();if(this.statusChangeListener){removeMCPStatusChangeListener(this.statusChangeListener);this.statusChangeListener=void 0}this.emit({kind:"failed",serverName:this.serverName,generation:this._generation,lastError:err instanceof Error?err.message:String(err)});for(const[sid]of this.subscribers){this.detach(sid)}this.onClosed(this.id);throw err}if(oldGen+1!==this._generation){await this.sweepAndDisconnect("restart_superseded");throw new Error(`Restart of ${this.id} superseded by newer generation; discarded stale snapshot + swept new transport.`)}const currentState=this.state;if(currentState==="closed"||currentState==="failed"){await this.sweepAndDisconnect("restart_superseded");throw new Error(`Restart of ${this.id} aborted: entry state is ${currentState} (forceShutdown ran concurrently mid-restart). Snapshot discarded; new transport swept.`)}this.toolsSnapshot=snap.tools;this.promptsSnapshot=snap.prompts;if(snap.resources.length>0){this.resourcesSnapshot=snap.resources}for(const[sid,view]of this.subscribers){try{view.applyTools(this.toolsSnapshot);view.applyPrompts(this.promptsSnapshot);view.applyResources(this.resourcesSnapshot)}catch(err){debugLogger.error(`Restart fan-out to view ${sid}/${this.serverName} failed: ${String(err)}`)}}this.localStatus="connected";this.suppressNextStatusEcho=true;this.updateGlobalStatus();this.emit({kind:"reconnected",serverName:this.serverName,generation:this._generation});this.emit({kind:"toolsChanged",serverName:this.serverName,snapshot:this.toolsSnapshot,generation:this._generation});this.emit({kind:"promptsChanged",serverName:this.serverName,snapshot:this.promptsSnapshot,generation:this._generation});this.emit({kind:"resourcesChanged",serverName:this.serverName,snapshot:this.resourcesSnapshot,generation:this._generation})}emit(event){const listeners=this.emitter.listeners("event");for(const listener of listeners){try{listener(event)}catch(err){debugLogger.error(`PoolEntry listener error for ${this.id} (event.kind=${event.kind}): ${err instanceof Error?err.message:String(err)}`)}}}internalOn(listener){this.emitter.on("event",listener)}internalOff(listener){this.emitter.off("event",listener)}updateGlobalStatus(){const aggregated=this.aggregateStatusByName(this.serverName);updateMCPServerStatus(this.serverName,aggregated)}getLocalStatus(){return this.localStatus}};var PooledConnectionImpl=class{constructor(entry,sessionId,releaseCallback){this.entry=entry;this.sessionId=sessionId;this.releaseCallback=releaseCallback}static{__name(this,"PooledConnectionImpl")}listeners=new Set;released=false;get id(){return this.entry.id}get transportId(){return this.entry.transportId}get serverName(){return this.entry.serverName}get entryIndex(){return this.entry.entryIndex}get client(){return this.entry.client}get toolsSnapshot(){return this.entry.toolsSnapshot}get promptsSnapshot(){return this.entry.promptsSnapshot}get resourcesSnapshot(){return this.entry.resourcesSnapshot}updateConfig(cfg){if(this.released){throw new Error(`Cannot update config on released MCP connection ${this.id}`)}this.entry.updateSessionConfig(this.sessionId,cfg)}on(event,listener){if(event!=="event")return this;if(this.listeners.has(listener))return this;this.listeners.add(listener);this.entry.internalOn(listener);return this}off(event,listener){if(event!=="event")return this;this.listeners.delete(listener);this.entry.internalOff(listener);return this}release(){if(this.released)return;this.released=true;for(const l of this.listeners){this.entry.internalOff(l)}this.listeners.clear();this.releaseCallback?.()}};init_esbuild_shims();var debugLogger2=createDebugLogger("McpPool:View");function compileNameFilter(includeTools,excludeTools){return{excludeSet:excludeTools?new Set(coerceMcpFilterEntries(excludeTools)):void 0,includeSet:includeTools!=null?new Set(coerceMcpFilterEntries(includeTools).map(normalizeMcpIncludeEntry)):void 0}}__name(compileNameFilter,"compileNameFilter");function compiledFilterAccepts(filter2,name){if(filter2.excludeSet?.has(name))return false;if(!filter2.includeSet)return true;return filter2.includeSet.has(name)}__name(compiledFilterAccepts,"compiledFilterAccepts");var SessionMcpView=class{constructor(sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry,sessionId,serverName,cfg){this.sessionToolRegistry=sessionToolRegistry;this.sessionPromptRegistry=sessionPromptRegistry;this.sessionResourceRegistry=sessionResourceRegistry;this.sessionId=sessionId;this.serverName=serverName;this.cfg=cfg;this.metadataKey=mcpSessionMetadataKey(cfg)}static{__name(this,"SessionMcpView")}metadataKey;applyTools(snapshot){this.sessionToolRegistry.removeMcpToolsByServer(this.serverName);const filter2=compileNameFilter(this.cfg.includeTools,this.cfg.excludeTools);let registered=0;for(const tool of snapshot){if(!compiledFilterAccepts(filter2,tool.serverToolName)){continue}const sessionTool=tool.withSessionConfig(this.cfg.trust,this.cfg.alwaysLoadTools===true);try{this.sessionToolRegistry.registerTool(sessionTool);registered+=1}catch(err){debugLogger2.error(`SessionMcpView[${this.sessionId}/${this.serverName}] failed to register tool ${tool.serverToolName}: ${String(err instanceof Error?err.message:err)}`)}}debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] applied ${snapshot.length} tools (filtered to ${registered} registered)`)}applyPrompts(snapshot){this.sessionPromptRegistry.removePromptsByServer(this.serverName);const filter2=compileNameFilter(this.cfg.includeTools,this.cfg.excludeTools);let registered=0;for(const prompt of snapshot){if(!compiledFilterAccepts(filter2,prompt.name)){continue}try{this.sessionPromptRegistry.registerPrompt(prompt);registered+=1}catch(err){debugLogger2.error(`SessionMcpView[${this.sessionId}/${this.serverName}] failed to register prompt ${prompt.name}: ${String(err instanceof Error?err.message:err)}`)}}debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] applied ${snapshot.length} prompts (filtered to ${registered} registered)`)}applyResources(snapshot){if(snapshot.length===0){return}this.sessionResourceRegistry.removeResourcesByServer(this.serverName);for(const resource of snapshot){try{this.sessionResourceRegistry.registerResource(resource)}catch(err){debugLogger2.error(`SessionMcpView[${this.sessionId}/${this.serverName}] failed to register resource ${resource.uri}: ${String(err instanceof Error?err.message:err)}`)}}debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] applied ${snapshot.length} resources`)}updateConfig(cfg){const nextKey=mcpSessionMetadataKey(cfg);const changed=this.metadataKey!==nextKey;this.cfg=cfg;this.metadataKey=nextKey;return changed}teardown(){this.sessionToolRegistry.removeMcpToolsByServer(this.serverName);this.sessionPromptRegistry.removePromptsByServer(this.serverName);this.sessionResourceRegistry.removeResourcesByServer(this.serverName);debugLogger2.debug(`SessionMcpView[${this.sessionId}/${this.serverName}] torn down`)}};var debugLogger3=createDebugLogger("McpPool");var McpTransportPool=class{constructor(cliConfig,options){this.cliConfig=cliConfig;this.opts={workspaceContext:options.workspaceContext,debugMode:options.debugMode,sendSdkMcpMessage:options.sendSdkMcpMessage,pooledTransports:options.pooledTransports??POOLED_TRANSPORTS_DEFAULT,drainDelayMs:options.drainDelayMs??3e4,entryOptions:options.entryOptions??defaultPoolEntryOptions,budget:options.budget}}static{__name(this,"McpTransportPool")}entries=new Map;unpooledIds=new Set;spawnInFlight=new Map;sessionToEntries=new Map;draining=false;nextIndexByName=new Map;opts;getBudget(){return this.opts.budget}hasNameSibling(serverName){for(const e of this.entries.values()){if(e.serverName===serverName)return true}for(const id of this.spawnInFlight.keys()){try{if(parseConnectionId(id).serverName===serverName)return true}catch{}}return false}async acquire(serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry){if(this.draining){throw new Error(`McpTransportPool is draining; refusing acquire for ${serverName} (session ${sessionId})`)}const poolable=isPoolable(cfg,this.opts.pooledTransports);const id=poolable?connectionIdOf(serverName,cfg):void 0;if(id!==void 0){const existing=this.entries.get(id);if(existing&&!existing.isTerminated()){try{const conn=this.attachPooledSession(existing,id,serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry);this.indexAttach(sessionId,id);return conn}catch(err){if(existing.isTerminated()){this.evictEntry(id,existing);debugLogger3.warn(`pool self-heal: evicted terminal entry ${id} (state='${existing.currentState}', serverName='${serverName}') mid-attach race; falling through to spawn fresh entry`)}else{throw err}}}else if(existing&&existing.isTerminated()){this.evictEntry(id,existing);debugLogger3.warn(`pool self-heal: evicted stale terminal entry ${id} (state='${existing.currentState}', serverName='${serverName}') before fast-path attach; falling through to spawn fresh entry`)}}let reservationResult;if(this.opts.budget!==void 0){const reservation=this.opts.budget.tryReserve(serverName);if(reservation==="refused"){const transport=mcpTransportOf(cfg);this.opts.budget.recordRefusal(serverName,transport);throw new BudgetExhaustedError(serverName,this.opts.budget.getBudget()??0,this.opts.budget.getReservedCount())}reservationResult=reservation}if(!poolable){try{return await this.createUnpooledConnection(serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry)}catch(err){this.rollbackReservationOnSpawnFailure(reservationResult,serverName);throw err}}if(id===void 0){throw new Error("unreachable: poolable && id === undefined")}let inFlight=this.spawnInFlight.get(id);if(!inFlight){const spawnPromise=this.spawnEntry(serverName,cfg,id);inFlight=spawnPromise.finally(()=>{this.spawnInFlight.delete(id)}).catch(err=>{this.rollbackReservationOnSpawnFailure(reservationResult,serverName);throw err});this.spawnInFlight.set(id,inFlight)}this.indexAttach(sessionId,id);let entry;try{entry=await inFlight}catch(err){this.indexDetach(sessionId,id);throw err}if(!this.entries.has(id)||entry.isTerminated()){this.indexDetach(sessionId,id);throw new Error(`PoolEntry ${id} torn down before attach (concurrent release)`)}try{const conn=this.attachPooledSession(entry,id,serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry);this.indexAttach(sessionId,id);return conn}catch(err){this.indexDetach(sessionId,id);throw err}}release(id,sessionId){const entry=this.entries.get(id);if(!entry)return;entry.detach(sessionId);this.indexDetach(sessionId,id);if(entry.refs.size===0){if(this.unpooledIds.has(id)){void entry.forceShutdown("manual");return}entry.startDrainTimer(this.opts.drainDelayMs)}}releaseSession(sessionId){const ids=this.sessionToEntries.get(sessionId);if(!ids)return;const idList=[...ids];for(const id of idList){const entry=this.entries.get(id);if(!entry)continue;entry.detach(sessionId);if(entry.refs.size===0){if(this.unpooledIds.has(id)){void entry.forceShutdown("manual");continue}entry.startDrainTimer(this.opts.drainDelayMs)}}this.sessionToEntries.delete(sessionId)}async restartByName(serverName,opts){if(this.draining)return[];const matching=[...this.entries.values()].filter(e=>e.serverName===serverName&&(opts?.entryIndex===void 0||e.entryIndex===opts.entryIndex));if(matching.length===0)return[];return Promise.all(matching.map(async entry=>{const started=Date.now();try{await entry.restart();if(entry.refs.size===0&&!this.unpooledIds.has(entry.id)){entry.startDrainTimer(this.opts.drainDelayMs)}return{entryIndex:entry.entryIndex,restarted:true,durationMs:Date.now()-started}}catch(err){return{entryIndex:entry.entryIndex,restarted:false,reason:String(err instanceof Error?err.message:err)}}}))}getSnapshot(){const byName=new Map;let total=0;let subprocessCount=0;for(const entry of this.entries.values()){const status=entry.getLocalStatus();if(status==="connected"){total+=1;if(entry.transportKind==="stdio"){subprocessCount+=1}}const row=byName.get(entry.serverName)??{entryCount:0,entrySummary:[]};row.entryCount+=1;row.entrySummary.push({entryIndex:entry.entryIndex,refs:entry.refs.size,status});byName.set(entry.serverName,row)}return{total,subprocessCount,byName:Object.fromEntries(byName.entries())}}aggregateStatusByName(serverName){let sawConnecting=false;for(const entry of this.entries.values()){if(entry.serverName!==serverName)continue;const s=entry.getLocalStatus();if(s==="connected")return"connected";if(s==="connecting")sawConnecting=true}return sawConnecting?"connecting":"disconnected"}async drainAll(opts){const timeoutMs=opts?.timeoutMs??1e4;const force=opts?.force??false;this.draining=true;const deadline=Date.now()+timeoutMs;if(this.spawnInFlight.size>0){const spawnWait=Promise.allSettled([...this.spawnInFlight.values()]);let inflightTimer;await Promise.race([spawnWait.then(()=>{if(inflightTimer)clearTimeout(inflightTimer)}),new Promise(resolve9=>{inflightTimer=setTimeout(()=>{const stuckIds=[...this.spawnInFlight.keys()];debugLogger3.warn(`drainAll: spawnInFlight wait timed out after ${timeoutMs}ms; ${stuckIds.length} spawn(s) still in-flight: ${stuckIds.join(", ")}. Proceeding with drain.`);resolve9()},Math.max(0,deadline-Date.now()));inflightTimer.unref?.()})])}const entries=[...this.entries.values()];const drained=[];const errors=[];const shutdownPromises=entries.map(entry=>entry.forceShutdown(force?"manual":"drain_timer").then(()=>drained.push(entry.entryIndex)).catch(err=>{errors.push({entryIndex:entry.entryIndex,serverName:entry.serverName,error:String(err instanceof Error?err.message:err)})}));let drainTimer;const remaining=Math.max(0,deadline-Date.now());await Promise.race([Promise.all(shutdownPromises).then(()=>{if(drainTimer)clearTimeout(drainTimer)}),new Promise(resolve9=>{drainTimer=setTimeout(()=>resolve9(),remaining);drainTimer.unref?.()})]);const drainedCount=drained.length;const errorsCount=errors.length;const forced=Math.max(0,entries.length-drainedCount-errorsCount);const errorsCopy=[...errors];this.entries.clear();this.unpooledIds.clear();this.sessionToEntries.clear();this.spawnInFlight.clear();return{drained:drainedCount,forced,errors:errorsCopy}}attachPooledSession(entry,id,serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry){const view=new SessionMcpView(sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry,sessionId,serverName,cfg);return entry.attach(sessionId,view,{release:__name(()=>this.release(id,sessionId),"release")})}rollbackReservationOnSpawnFailure(reservationResult,serverName){if(this.opts.budget!==void 0&&reservationResult==="reserved"&&!this.hasNameSibling(serverName)){this.opts.budget.release(serverName)}}evictEntry(id,entry){if(entry===void 0)return;const current=this.entries.get(id);if(current!==entry)return;this.entries.delete(id);if(this.opts.budget!==void 0){if(!this.hasNameSibling(entry.serverName)){this.opts.budget.release(entry.serverName)}}}async spawnEntry(serverName,cfg,id){const entryIndex=this.allocateEntryIndex(serverName);const transport=mcpTransportOf(cfg);const entryOpts=this.opts.entryOptions(transport);const client=new McpClient(serverName,cfg,poisonedToolRegistry(serverName),poisonedPromptRegistry(serverName),this.opts.workspaceContext,this.opts.debugMode,this.opts.sendSdkMcpMessage);const entryRef={current:void 0};const onClosedForThisEntry=__name(closedId=>{this.evictEntry(closedId,entryRef.current)},"onClosedForThisEntry");const entry=new PoolEntry(id,serverName,entryIndex,cfg,client,this.cliConfig,entryOpts,onClosedForThisEntry,name=>this.aggregateStatusByName(name));entryRef.current=entry;try{const timeoutMs=discoveryTimeoutFor(cfg);const snap=await runWithTimeout((async()=>{await client.connect();return client.discoverAndReturn(this.cliConfig,{applyConfigFilters:false})})(),timeoutMs,`pool spawn for ${id} (pool will roll back the spawn and free its budget slot)`);if(this.draining){debugLogger3.warn(`Spawn for ${id} completed while pool is draining; discarding entry`);try{await entry.forceShutdown("manual")}catch{}throw new Error(`McpTransportPool is draining; discarded spawn ${id}`)}this.entries.set(id,entry);entry.markActive(snap.tools,snap.prompts,snap.resources);debugLogger3.info(`Spawned pool entry ${id} (entryIndex=${entryIndex}, transport=${transport})`);return entry}catch(err){debugLogger3.error(`Failed to spawn pool entry for '${serverName}' (id=${id}, transport=${transport}): ${String(err)}`);try{await entry.forceShutdown("manual")}catch{}this.entries.delete(id);try{await client.disconnect()}catch{}throw err}}allocateEntryIndex(serverName){const next=this.nextIndexByName.get(serverName)??0;this.nextIndexByName.set(serverName,next+1);return next}indexAttach(sessionId,id){let ids=this.sessionToEntries.get(sessionId);if(!ids){ids=new Set;this.sessionToEntries.set(sessionId,ids)}ids.add(id)}indexDetach(sessionId,id){const ids=this.sessionToEntries.get(sessionId);if(!ids)return;ids.delete(id);if(ids.size===0)this.sessionToEntries.delete(sessionId)}async createUnpooledConnection(serverName,cfg,sessionId,sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry){const entryIndex=this.allocateEntryIndex(serverName);const id=`${serverName}::unpooled-${entryIndex}`;const transport=mcpTransportOf(cfg);const entryOpts=this.opts.entryOptions(transport);const client=new McpClient(serverName,cfg,sessionToolRegistry,sessionPromptRegistry,this.opts.workspaceContext,this.opts.debugMode,this.opts.sendSdkMcpMessage);const view=new SessionMcpView(sessionToolRegistry,sessionPromptRegistry,sessionResourceRegistry,sessionId,serverName,cfg);const entry=new PoolEntry(id,serverName,entryIndex,cfg,client,this.cliConfig,entryOpts,closedId=>{this.entries.delete(closedId);this.unpooledIds.delete(closedId);if(this.opts.budget!==void 0){if(!this.hasNameSibling(serverName)){this.opts.budget.release(serverName)}}},()=>client.getStatus());try{this.entries.set(id,entry);this.unpooledIds.add(id);this.indexAttach(sessionId,id);const timeoutMs=discoveryTimeoutFor(cfg);const snap=await runWithTimeout((async()=>{await client.connect();return await client.discoverAndReturn(this.cliConfig,{applyConfigFilters:false})})(),timeoutMs,`unpooled spawn for ${id} (pool will roll back the spawn and free its budget slot)`);if(this.draining||!this.entries.has(id)||entry.isTerminated()){try{view.teardown()}catch{}try{await entry.forceShutdown("manual")}catch{}this.indexDetach(sessionId,id);throw new Error(`McpTransportPool is draining or unpooled ${id} was cancelled`)}entry.markActive(snap.tools,snap.prompts,snap.resources);const conn=entry.attach(sessionId,view,{release:__name(()=>{this.indexDetach(sessionId,id);void entry.forceShutdown("manual")},"release")});return conn}catch(err){try{await entry.forceShutdown("manual")}catch{}this.entries.delete(id);this.unpooledIds.delete(id);this.indexDetach(sessionId,id);try{await client.disconnect()}catch{}throw err}}};function poisonedToolRegistry(serverName){return{registerTool(){throw new Error(`Pool invariant violated: poisoned ToolRegistry for ${serverName} received registerTool. A pool path must use discoverAndReturn, not discover.`)}}}__name(poisonedToolRegistry,"poisonedToolRegistry");function poisonedPromptRegistry(serverName){return{registerPrompt(){throw new Error(`Pool invariant violated: poisoned PromptRegistry for ${serverName} received registerPrompt. A pool path must use discoverAndReturn.`)}}}__name(poisonedPromptRegistry,"poisonedPromptRegistry");init_esbuild_shims();var debugLogger4=createDebugLogger("McpPool:Budget");var WorkspaceMcpBudget=class{static{__name(this,"WorkspaceMcpBudget")}clientBudget;mode;onEvent;reservedSlots=new Set;pendingRefusalNames=new Set;pendingRefusalTransports=new Map;lastRefusedServerNames=[];warnArmed=true;bulkPassDepth=0;constructor(opts){this.clientBudget=opts.clientBudget;this.mode=opts.mode;this.onEvent=opts.mode==="off"?void 0:opts.onEvent}getMode(){return this.mode}getBudget(){return this.clientBudget}getReservedSlots(){return Array.from(this.reservedSlots)}getRefusedServerNames(){return this.lastRefusedServerNames}getReservedCount(){return this.reservedSlots.size}tryReserve(serverName){if(this.reservedSlots.has(serverName))return"already_held";if(this.clientBudget===void 0||this.mode==="off"){return"reserved"}if(this.mode==="enforce"&&this.reservedSlots.size>=this.clientBudget){return"refused"}this.reservedSlots.add(serverName);this.evaluateState();return"reserved"}release(serverName){const had=this.reservedSlots.delete(serverName);if(had)this.evaluateState();return had}recordRefusal(serverName,transport){if(this.mode!=="enforce")return;this.pendingRefusalNames.add(serverName);this.pendingRefusalTransports.set(serverName,transport);debugLogger4.warn(`MCP server '${serverName}' refused at pool acquire (budget exhausted, budget=${this.clientBudget}, mode=${this.mode})`);if(this.bulkPassDepth===0){this.flushRefusedBatch()}}beginBulkPass(){if(this.bulkPassDepth===0){this.lastRefusedServerNames=[]}this.bulkPassDepth+=1}endBulkPass(){if(this.bulkPassDepth===0){debugLogger4.warn("WorkspaceMcpBudget.endBulkPass called without matching beginBulkPass; ignoring");return}this.bulkPassDepth-=1;if(this.bulkPassDepth>0)return;this.flushRefusedBatch()}flushRefusedBatch(){if(this.pendingRefusalNames.size===0)return;if(this.clientBudget===void 0||this.mode!=="enforce"){this.pendingRefusalNames.clear();this.pendingRefusalTransports.clear();return}const refusedServers=[];const names=[];for(const name of this.pendingRefusalNames){const transport=this.pendingRefusalTransports.get(name)??"unknown";refusedServers.push({name,transport,reason:"budget_exhausted"});names.push(name)}this.lastRefusedServerNames=Object.freeze(names);this.pendingRefusalNames.clear();this.pendingRefusalTransports.clear();if(this.onEvent){try{this.onEvent({kind:"refused_batch",refusedServers,budget:this.clientBudget,liveCount:this.reservedSlots.size,reservedCount:this.reservedSlots.size,mode:"enforce"})}catch(err){debugLogger4.error(`WorkspaceMcpBudget refused_batch event delivery failed: ${err instanceof Error?err.message:String(err)}`)}}}evaluateState(){if(this.mode==="off"||this.clientBudget===void 0)return;const ratio=this.reservedSlots.size/this.clientBudget;if(this.warnArmed&&ratio>=MCP_BUDGET_WARN_FRACTION){this.warnArmed=false;debugLogger4.info(`MCP workspace budget warning fired (ratio=${ratio.toFixed(2)}, reservedCount=${this.reservedSlots.size}, budget=${this.clientBudget}, mode=${this.mode})`);if(this.onEvent){try{this.onEvent({kind:"budget_warning",liveCount:this.reservedSlots.size,reservedCount:this.reservedSlots.size,budget:this.clientBudget,thresholdRatio:MCP_BUDGET_WARN_FRACTION,mode:this.mode})}catch(err){debugLogger4.error(`WorkspaceMcpBudget budget_warning event delivery failed: ${err instanceof Error?err.message:String(err)}`)}}}else if(!this.warnArmed&&ratio<MCP_BUDGET_REARM_FRACTION){this.warnArmed=true;debugLogger4.info(`MCP workspace budget warning re-armed (ratio=${ratio.toFixed(2)}, budget=${this.clientBudget}; next 75% crossing will fire)`)}}};init_esbuild_shims();function preservePlaceholders(value,resolved,original){if(typeof original==="string"&&value===resolved)return original;if(Array.isArray(value)&&Array.isArray(resolved)&&Array.isArray(original)){return value.map((entry,index)=>preservePlaceholders(entry,resolved[index],original[index]))}if(value&&resolved&&original&&typeof value==="object"&&!Array.isArray(value)&&typeof resolved==="object"&&!Array.isArray(resolved)&&typeof original==="object"&&!Array.isArray(original)){return Object.fromEntries(Object.entries(value).map(([key,entry])=>[key,preservePlaceholders(entry,resolved[key],original[key])]))}return value}__name(preservePlaceholders,"preservePlaceholders");function preserveModelProviderPlaceholders(models,provider,resolvedProviders,rawProviders,mapping){const pairs=Object.entries(resolvedProviders).flatMap(([providerId,entries])=>{if(!Array.isArray(entries))return[];return entries.flatMap((entry,index)=>{const resolved=provider==="openai"?getModelsForProviderProtocol({[providerId]:[entry]},"openai",mapping)[0]:providerId===provider?entry:void 0;return resolved?[{providerId,resolved,source:entry,raw:rawProviders[providerId]?.[index]??entry}]:[]})});return models.map(model=>{const matches=pairs.filter(({resolved})=>resolved.id===model.id&&resolved.baseUrl===model.baseUrl&&tryResolveModelProtocol(provider,resolved,mapping)===tryResolveModelProtocol(provider,model,mapping));const sourceMatches=matches.filter(pair=>pair.providerId===matches[0]?.providerId);if(sourceMatches.length>1&&sourceMatches.some(pair=>JSON.stringify(pair.raw)!==JSON.stringify(pair.source))){throw new Error("Cannot preserve placeholders in an ambiguous model configuration. Remove duplicate model entries first.")}const match=matches[0];return match?preservePlaceholders(model,match.resolved,match.raw):model})}__name(preserveModelProviderPlaceholders,"preserveModelProviderPlaceholders");init_esbuild_shims();init_esbuild_shims();var DISCOVERY_TIMEOUT_MS=5e3;var DISCOVERY_MAX_BYTES=1024*1024;var MAX_MODEL_ID_LENGTH=256;var UNSAFE_MODEL_ID_CHARS=/[,\p{C}\p{Zl}\p{Zp}]/u;function readModels(value){if(!value||typeof value!=="object"||!("data"in value)){return null}const data=value.data;if(!Array.isArray(data)){return null}const models=[];const seen=new Set;for(const item of data){if(!item||typeof item!=="object"||!("id"in item)){return null}const id=item.id;if(typeof id!=="string"){return null}const trimmedId=id.trim();if(trimmedId&&trimmedId.length<=MAX_MODEL_ID_LENGTH&&!UNSAFE_MODEL_ID_CHARS.test(trimmedId)&&!seen.has(trimmedId)){seen.add(trimmedId);const created=item.created;const creationTime=typeof created==="number"&&Number.isFinite(created)&&created>=0?created:void 0;models.push({id:trimmedId,...creationTime===void 0?{}:{created:creationTime}})}}return models.length>0?models:null}__name(readModels,"readModels");function mergeModelSpecs(discoveredModels,staticModels){const staticModelsById=new Map(staticModels.map(model=>[model.id,model]));const orderedModels=[...discoveredModels];if(orderedModels.every(model=>model.created!==void 0)){orderedModels.sort((left,right)=>(right.created??0)-(left.created??0))}return orderedModels.map(({id})=>staticModelsById.get(id)??{id})}__name(mergeModelSpecs,"mergeModelSpecs");async function discoverProviderModels({baseUrl,apiKey,staticModels,signal}){const normalizedBaseUrl=baseUrl.trim();const normalizedApiKey=apiKey.trim();if(!normalizedBaseUrl||!normalizedApiKey){return null}try{const modelsUrl=`${normalizedBaseUrl.replace(/\/+$/,"")}/models`;const result=await fetchWithPolicy(modelsUrl,{timeoutMs:DISCOVERY_TIMEOUT_MS,maxBytes:DISCOVERY_MAX_BYTES,maxRedirects:2,headers:{Accept:"application/json",Authorization:`Bearer ${normalizedApiKey}`},signal});if(result.kind!=="response"||result.status<200||result.status>=300){return null}const models=readModels(JSON.parse(result.body.toString("utf8")));return models?mergeModelSpecs(models,staticModels):null}catch{return null}}__name(discoverProviderModels,"discoverProviderModels");init_esbuild_shims();var IMAGE_CAPABILITY=Object.freeze({autoHandlesWrongModel:true,maxBytes:VISION_BRIDGE_MAX_IMAGE_BASE64_BYTES,maxImagesPerTurn:VISION_BRIDGE_MAX_IMAGES});init_esbuild_shims();var debugLogger5=createDebugLogger("SESSION_RECAP");var RECENT_MESSAGE_WINDOW=30;var RECAP_SYSTEM_PROMPT=`You generate session recaps for a programming assistant CLI.
4
4
 
5
5
  The user stepped away and is coming back. Recap in under 40 words, 1-2 plain sentences, no markdown. Lead with the overall goal and current task, then the one next action. Skip root-cause narrative, fix internals, secondary to-dos, and em-dash tangents.
6
6
 
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{formatUnsupportedVoiceModelMessage,isTranscribableVoiceModel,readVoiceLanguage,resolveVoiceTransport}from"./chunk-T2O3JMRH.js";import{resolvePath}from"./chunk-CFIGRBWA.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{isSubpath}from"./chunk-2ZK2FGZQ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import process from"node:process";import{lookup as dnsLookup}from"node:dns/promises";import{BlockList,isIP}from"node:net";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var GLOBAL_KEYTERMS=["Qwen","MCP","grep","regex","localhost","codebase","TypeScript","JavaScript","JSON","YAML","OAuth","webhook","gRPC","dotfiles","subagent","worktree","stdout","stderr","async","await","API","CLI","npm","pnpm","commit","rebase","refactor","endpoint","middleware","schema","tokenizer"];var DEFAULT_KEYTERMS_FILENAME="voice-keyterms.txt";var MAX_KEYTERMS=200;var MAX_KEYTERMS_BYTES=2e3;var MAX_KEYTERMS_FILE_BYTES=64*1024;function buildVoiceKeyterms(settings){const userTerms=settings?readUserKeyterms(settings):[];return capKeyterms(dedupeKeyterms([...GLOBAL_KEYTERMS,...userTerms]))}__name(buildVoiceKeyterms,"buildVoiceKeyterms");function dedupeKeyterms(terms){const seen=new Set;const out=[];for(const term of terms){const key=term.toLowerCase();if(seen.has(key)){continue}seen.add(key);out.push(term)}return out}__name(dedupeKeyterms,"dedupeKeyterms");function capKeyterms(terms){const out=[];let bytes=0;for(const term of terms){if(out.length>=MAX_KEYTERMS){break}const next=bytes+Buffer.byteLength(term,"utf8")+(out.length>0?1:0);if(next>MAX_KEYTERMS_BYTES){continue}out.push(term);bytes=next}return out}__name(capKeyterms,"capKeyterms");function readUserKeyterms(settings){if(!settings.isTrusted){return[]}for(const resolved of resolveKeytermsFiles(settings)){try{const file=canonicalizeKeytermsFile(resolved);if(!file){continue}const content=readRegularFileNoFollow(file);if(content===void 0){continue}const parsed=parseKeyterms(content);if(parsed.length>0){return parsed}}catch{}}return[]}__name(readUserKeyterms,"readUserKeyterms");function resolveKeytermsFiles(settings){const workspacePath=settings.workspace?.path;if(!workspacePath){return[]}const qwenDir=path.dirname(workspacePath);const workspaceRoot=path.dirname(qwenDir);const configured=readKeytermsFileSettings(settings);if(configured.length>0){return configured.map(({path:configuredPath,scope})=>{const expanded=resolvePath(configuredPath);const isAbsolute2=path.isAbsolute(expanded);return{filePath:isAbsolute2?expanded:path.resolve(workspaceRoot,expanded),workspaceRoot,mustBeInWorkspace:scope==="system"||!isAbsolute2}})}return[{filePath:path.join(qwenDir,DEFAULT_KEYTERMS_FILENAME),workspaceRoot,mustBeInWorkspace:true}]}__name(resolveKeytermsFiles,"resolveKeytermsFiles");function canonicalizeKeytermsFile({filePath,workspaceRoot,mustBeInWorkspace}){const stat=fs.lstatSync(filePath,{throwIfNoEntry:false});if(!stat||stat.isSymbolicLink()||!stat.isFile()||stat.nlink>1||stat.size>MAX_KEYTERMS_FILE_BYTES){return void 0}const realFilePath=fs.realpathSync(filePath);if(mustBeInWorkspace){const realWorkspaceRoot=fs.realpathSync(workspaceRoot);if(!isSubpath(realWorkspaceRoot,realFilePath)){return void 0}}return{filePath:realFilePath,stat}}__name(canonicalizeKeytermsFile,"canonicalizeKeytermsFile");function readRegularFileNoFollow({filePath,stat:expectedStat}){let fd;try{let flags=fs.constants.O_RDONLY;if(typeof fs.constants.O_NOFOLLOW==="number"){flags|=fs.constants.O_NOFOLLOW}if(typeof fs.constants.O_NONBLOCK==="number"){flags|=fs.constants.O_NONBLOCK}fd=fs.openSync(filePath,flags);const stat=fs.fstatSync(fd);if(stat.dev!==expectedStat.dev||stat.ino!==expectedStat.ino||stat.mode!==expectedStat.mode||stat.size!==expectedStat.size||stat.mtimeMs!==expectedStat.mtimeMs||stat.ctimeMs!==expectedStat.ctimeMs||!stat.isFile()||stat.nlink>1||stat.size>MAX_KEYTERMS_FILE_BYTES){return void 0}const content=fs.readFileSync(fd,"utf-8");if(Buffer.byteLength(content,"utf8")>MAX_KEYTERMS_FILE_BYTES){return void 0}return content}finally{if(fd!==void 0){fs.closeSync(fd)}}}__name(readRegularFileNoFollow,"readRegularFileNoFollow");function parseKeyterms(content){return content.split(/\r?\n/).map(line=>line.replace(/^\s*#.*$/,"").trim()).filter(line=>line.length>0)}__name(parseKeyterms,"parseKeyterms");function readKeytermsFileSettings(settings){const out=[];const system=readKeytermsFileSettingFromScope(settings.system?.settings);if(system){out.push({path:system,scope:"system"})}const user=readKeytermsFileSettingFromScope(settings.user?.settings);if(user){out.push({path:user,scope:"user"})}return out}__name(readKeytermsFileSettings,"readKeytermsFileSettings");function readKeytermsFileSettingFromScope(settings){const value=settings?.general?.voice?.keytermsFile;if(typeof value!=="string"){return void 0}const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}__name(readKeytermsFileSettingFromScope,"readKeytermsFileSettingFromScope");var DEFAULT_OPENAI_API_KEY="OPENAI_API_KEY";var INFERENCE_TIMEOUT_MS=6e4;var MIN_KEYTERM_ECHO_TOKENS=8;var MIN_ABSOLUTE_KEYTERM_ECHO_TOKENS=10;var MIN_KEYTERM_SET_ECHO_RATIO=.3;var debugLogger=createDebugLogger("VOICE_TRANSCRIBER");var BLOCKED_TRANSITION_IPV6_ADDRESSES=new BlockList;for(const[address,prefix]of[["64:ff9b:1::",48],["2001::",23],["2002::",16]]){BLOCKED_TRANSITION_IPV6_ADDRESSES.addSubnet(address,prefix,"ipv6")}function trimTrailingSlashes(value){return value.replace(/\/+$/,"")}__name(trimTrailingSlashes,"trimTrailingSlashes");function readSettingsEnv(settings,envKey){const env=settings.merged.env;const value=env?.[envKey];return typeof value==="string"&&value.trim().length>0?value.trim():void 0}__name(readSettingsEnv,"readSettingsEnv");function isQwenBaseUrl(baseUrl){try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname==="dashscope.aliyuncs.com"||hostname==="dashscope-intl.aliyuncs.com"||hostname==="dashscope-us.aliyuncs.com"||hostname.endsWith(".dashscope.aliyuncs.com")||hostname.endsWith(".dashscope-intl.aliyuncs.com")||hostname.endsWith(".dashscope-us.aliyuncs.com")}catch{return false}}__name(isQwenBaseUrl,"isQwenBaseUrl");function normalizeBaseUrl(baseUrl,modelName){let url;try{url=new URL(baseUrl)}catch{throw new Error(`Voice model '${modelName}' has an invalid baseUrl.`)}if(url.username||url.password){throw new Error(`Voice model '${modelName}' baseUrl must not contain embedded credentials.`)}return trimTrailingSlashes(url.toString())}__name(normalizeBaseUrl,"normalizeBaseUrl");function normalizeAllowedVoiceBaseUrl(baseUrl){try{const url=new URL(baseUrl.trim());if(url.username||url.password){return void 0}return trimTrailingSlashes(url.toString())}catch{return void 0}}__name(normalizeAllowedVoiceBaseUrl,"normalizeAllowedVoiceBaseUrl");function isInsecureVoiceBaseUrlAllowed(settings,normalizedBaseUrl){const allowed=settings.merged.security?.allowedInsecureVoiceBaseUrls;return Array.isArray(allowed)&&allowed.some(candidate=>typeof candidate==="string"&&normalizeAllowedVoiceBaseUrl(candidate)===normalizedBaseUrl)}__name(isInsecureVoiceBaseUrlAllowed,"isInsecureVoiceBaseUrlAllowed");function normalizeHostname(hostname){return hostname.toLowerCase().replace(/^\[|\]$/g,"")}__name(normalizeHostname,"normalizeHostname");function normalizeIpAddress(address){const host=normalizeHostname(address);if(isIP(host)!==6){return host}try{return normalizeHostname(new URL(`http://[${host}]/`).hostname)}catch{return host}}__name(normalizeIpAddress,"normalizeIpAddress");function isLoopbackHost(hostname){const host=normalizeHostname(hostname);return host==="localhost"||host==="127.0.0.1"||host==="::1"}__name(isLoopbackHost,"isLoopbackHost");function isAwsIpv6MetadataAddress(hostname){const host=normalizeHostname(hostname);if(isIP(host)!==6){return false}try{return normalizeHostname(new URL(`http://[${host}]/`).hostname)==="fd00:ec2::254"}catch{return false}}__name(isAwsIpv6MetadataAddress,"isAwsIpv6MetadataAddress");function readIpv4CompatibleIpv6(host){if(!host.startsWith("::")||host.startsWith("::ffff:")){return void 0}const parts=host.slice(2).split(":");if(parts.length===0||parts.length>2||parts.some(part=>!part)){return void 0}if(parts.some(part=>!/^[0-9a-f]{1,4}$/i.test(part))){return void 0}const hextets=parts.map(part=>Number.parseInt(part,16));const value=hextets.length===1?hextets[0]:hextets[0]<<16|hextets[1];return[value>>>24&255,value>>>16&255,value>>>8&255,value&255].join(".")}__name(readIpv4CompatibleIpv6,"readIpv4CompatibleIpv6");function readIpv4MappedIpv6(host){const dotted=host.match(/^::ffff:(\d+(?:\.\d+){3})$/i);if(dotted&&isIP(dotted[1])===4){return dotted[1]}const hex=host.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!hex){return void 0}return readIpv4HexPair(hex[1],hex[2])}__name(readIpv4MappedIpv6,"readIpv4MappedIpv6");function readIpv4HexPair(highHex,lowHex){const high=Number.parseInt(highHex,16);const low=Number.parseInt(lowHex,16);return[high>>>8,high&255,low>>>8,low&255].join(".")}__name(readIpv4HexPair,"readIpv4HexPair");function readWellKnownNat64Ipv6(host){const prefix="64:ff9b::";if(!host.startsWith(prefix)){return void 0}const suffix=host.slice(prefix.length);if(!suffix){return"0.0.0.0"}const groups=suffix.split(":");if(groups.length>2||groups.some(group=>!/^[0-9a-f]{1,4}$/i.test(group))){return void 0}return groups.length===1?readIpv4HexPair("0",groups[0]):readIpv4HexPair(groups[0],groups[1])}__name(readWellKnownNat64Ipv6,"readWellKnownNat64Ipv6");function isBlockedTransitionIpv6Address(host){return isIP(host)===6&&BLOCKED_TRANSITION_IPV6_ADDRESSES.check(host,"ipv6")}__name(isBlockedTransitionIpv6Address,"isBlockedTransitionIpv6Address");function unwrapIpv6TransitionStep(host){const ipv4Mapped=readIpv4MappedIpv6(host);if(ipv4Mapped){return{address:ipv4Mapped}}const ipv4Compatible=readIpv4CompatibleIpv6(host);if(ipv4Compatible){return{address:ipv4Compatible}}const nat64=readWellKnownNat64Ipv6(host);if(nat64){return{address:nat64}}if(host.startsWith("::ffff:")){return"blocked"}return void 0}__name(unwrapIpv6TransitionStep,"unwrapIpv6TransitionStep");function isPrivateNetworkIp(hostname){const host=normalizeIpAddress(hostname);if(isBlockedTransitionIpv6Address(host)){return true}if(isLoopbackHost(host)){return false}const step=unwrapIpv6TransitionStep(host);if(step==="blocked"){return true}if(step){return isPrivateNetworkIp(step.address)}if(isIP(host)===4){const[first=0,second=0]=host.split(".").map(Number);return first===0||first===10||first===127||first===169&&second===254||first===172&&second>=16&&second<=31||first===192&&second===168||first===100&&second>=64&&second<=127}if(isIP(host)===6){const firstHextet=Number.parseInt(host.split(":",1)[0]||"0",16);return host==="::"||(firstHextet&65472)===65152||(firstHextet&65024)===64512}return false}__name(isPrivateNetworkIp,"isPrivateNetworkIp");function isAlwaysBlockedVoiceAddress(address){const host=normalizeIpAddress(address);if(isBlockedTransitionIpv6Address(host)){return true}if(isLoopbackHost(host)){return true}const step=unwrapIpv6TransitionStep(host);if(step==="blocked"){return true}if(step){return isAlwaysBlockedVoiceAddress(step.address)}if(isIP(host)===4){const[first=0,second=0]=host.split(".").map(Number);return first===0||first===127||first===169&&second===254||host==="100.100.100.200"}if(isIP(host)===6){const firstHextet=Number.parseInt(host.split(":",1)[0]||"0",16);return host==="::"||isAwsIpv6MetadataAddress(host)||(firstHextet&65472)===65152}return false}__name(isAlwaysBlockedVoiceAddress,"isAlwaysBlockedVoiceAddress");function isLoopbackVoiceAddress(address){const host=normalizeIpAddress(address);if(isLoopbackHost(host)){return true}const step=unwrapIpv6TransitionStep(host);if(step&&step!=="blocked"){return isLoopbackVoiceAddress(step.address)}if(isIP(host)===4){return host.startsWith("127.")}return false}__name(isLoopbackVoiceAddress,"isLoopbackVoiceAddress");async function defaultLookupHost(hostname){return dnsLookup(hostname,{all:true})}__name(defaultLookupHost,"defaultLookupHost");async function assertVoiceBaseUrlNetworkAllowed(voiceConfig,lookupHost,abortSignal){const hostname=normalizeHostname(new URL(voiceConfig.baseUrl).hostname);if(isLoopbackHost(hostname)){return}if(isIP(hostname)!==0){if(isAlwaysBlockedVoiceAddress(hostname)||!voiceConfig.allowInsecureBaseUrl&&isPrivateNetworkIp(hostname)){throw new Error(isLoopbackVoiceAddress(hostname)?`Voice model '${voiceConfig.model}' uses a loopback address outside the accepted spellings. To use a local ASR endpoint, set the baseUrl to http://localhost, http://127.0.0.1, or http://[::1].`:`Voice model '${voiceConfig.model}' resolved to a private-network address.`)}return}let result;let onAbort;try{if(abortSignal?.aborted){throw abortSignal.reason}const lookup=(lookupHost??defaultLookupHost)(hostname);result=abortSignal?await Promise.race([lookup,new Promise((_resolve,reject)=>{onAbort=__name(()=>reject(abortSignal.reason),"onAbort");if(abortSignal.aborted)onAbort();else abortSignal.addEventListener("abort",onAbort,{once:true})})]):await lookup}catch{if(abortSignal?.aborted){throw abortSignal.reason instanceof Error?abortSignal.reason:new Error("Voice request was aborted.")}throw new Error(`Voice model '${voiceConfig.model}': DNS lookup failed for ${hostname}. Cannot verify network safety.`)}finally{if(onAbort)abortSignal?.removeEventListener("abort",onAbort)}const records=Array.isArray(result)?result:[result];if(records.some(record=>isAlwaysBlockedVoiceAddress(record.address)||!voiceConfig.allowInsecureBaseUrl&&isPrivateNetworkIp(record.address))){throw new Error(records.some(record=>isLoopbackVoiceAddress(record.address))?`Voice model '${voiceConfig.model}' resolved to a loopback address. Loopback DNS results are always blocked; to use a local ASR endpoint, configure an explicit loopback baseUrl: http://localhost, http://127.0.0.1, or http://[::1].`:voiceConfig.allowInsecureBaseUrl&&records.some(record=>isAlwaysBlockedVoiceAddress(record.address))?`Voice model '${voiceConfig.model}' resolved to an address that is always blocked (metadata, link-local, or transition range), even when the baseUrl is listed in security.allowedInsecureVoiceBaseUrls.`:`Voice model '${voiceConfig.model}' resolved to a private-network address.`)}}__name(assertVoiceBaseUrlNetworkAllowed,"assertVoiceBaseUrlNetworkAllowed");function readApiKey(settings,model,baseUrl,env){if(!model.envKey&&!isQwenBaseUrl(baseUrl)){return void 0}const envKey=model.envKey??DEFAULT_OPENAI_API_KEY;const envSource=env??process.env;const envValue=Object.hasOwn(envSource,envKey)?envSource[envKey]:void 0;if(envValue&&envValue.trim().length>0){return envValue.trim()}const settingsEnvValue=readSettingsEnv(settings,envKey);if(settingsEnvValue){return settingsEnvValue}if(!model.envKey&&isQwenBaseUrl(baseUrl)){const authApiKey=settings.merged.security?.auth?.apiKey;return typeof authApiKey==="string"&&authApiKey.trim().length>0?authApiKey.trim():void 0}return void 0}__name(readApiKey,"readApiKey");function resolveVoiceTranscriptionConfig({config,settings,voiceModel,env}){const matches=config.getAllConfiguredModels().filter(model2=>model2.id===voiceModel);if(matches.length===0){throw new Error(`Voice model '${voiceModel}' is not configured. Run /model --voice to choose a configured model.`)}if(matches.length>1){throw new Error(`Voice model '${voiceModel}' is ambiguous.`)}const model=matches[0];if(!isTranscribableVoiceModel(model)){throw new Error(formatUnsupportedVoiceModelMessage(voiceModel))}const baseUrl=model.baseUrl?.trim();if(!baseUrl){throw new Error(`Voice model '${voiceModel}' does not define a baseUrl.`)}const normalizedBaseUrl=normalizeBaseUrl(baseUrl,voiceModel);const parsedBaseUrl=new URL(normalizedBaseUrl);const isLocalhost=isLoopbackHost(parsedBaseUrl.hostname);const allowInsecureBaseUrl=isInsecureVoiceBaseUrlAllowed(settings,normalizedBaseUrl);if(parsedBaseUrl.protocol!=="http:"&&parsedBaseUrl.protocol!=="https:"){throw new Error(`Voice model '${voiceModel}' must use an http or https baseUrl.`)}if(!isLocalhost&&isAlwaysBlockedVoiceAddress(parsedBaseUrl.hostname)){throw new Error(isLoopbackVoiceAddress(parsedBaseUrl.hostname)?`Voice model '${voiceModel}' uses a loopback address outside the accepted spellings. To use a local ASR endpoint, set the baseUrl to http://localhost, http://127.0.0.1, or http://[::1].`:`Voice model '${voiceModel}' must not use a private-network baseUrl.`)}if(parsedBaseUrl.protocol!=="https:"&&!isLocalhost&&!allowInsecureBaseUrl){throw new Error(`Voice model '${voiceModel}' must use an https baseUrl. Voice audio must not be transmitted in cleartext. To trust this managed endpoint, add its exact complete normalized URL (${normalizedBaseUrl}) to security.allowedInsecureVoiceBaseUrls. This setting is only honored from User, System, or SystemDefaults scope settings; Workspace entries are ignored.`)}if(!isLocalhost&&!allowInsecureBaseUrl&&isPrivateNetworkIp(parsedBaseUrl.hostname)){throw new Error(`Voice model '${voiceModel}' must not use a private-network baseUrl. To trust this managed endpoint, add its exact complete normalized URL (${normalizedBaseUrl}) to security.allowedInsecureVoiceBaseUrls. This setting is only honored from User, System, or SystemDefaults scope settings; Workspace entries are ignored.`)}const apiKey=readApiKey(settings,model,normalizedBaseUrl,env);if(model.envKey&&!apiKey){throw new Error(`Voice model '${voiceModel}' requires ${model.envKey}.`)}return{model:voiceModel,baseUrl:normalizedBaseUrl,...apiKey?{apiKey}:{},...allowInsecureBaseUrl?{allowInsecureBaseUrl:true}:{}}}__name(resolveVoiceTranscriptionConfig,"resolveVoiceTranscriptionConfig");function isStreamingVoiceModel(model){const transport=resolveVoiceTransport(model);return transport==="qwen-asr-realtime"||transport==="dashscope-task-realtime"}__name(isStreamingVoiceModel,"isStreamingVoiceModel");function resolveVoiceStreamConfig(args){const base=resolveVoiceTranscriptionConfig(args);const transport=resolveVoiceTransport(base.model);if(transport!=="qwen-asr-realtime"&&transport!=="dashscope-task-realtime"){throw new Error(`Voice model '${base.model}' does not support streaming transcription.`)}const language=resolveLanguageCode(readVoiceLanguage(args.settings));const keytermsContext=transport==="qwen-asr-realtime"?buildKeytermsContext(args.settings):void 0;return{transport,baseUrl:base.baseUrl,model:base.model,...base.apiKey?{apiKey:base.apiKey}:{},...base.allowInsecureBaseUrl?{allowInsecureBaseUrl:true}:{},...language?{language}:{},...keytermsContext?{keytermsContext}:{}}}__name(resolveVoiceStreamConfig,"resolveVoiceStreamConfig");var LANGUAGE_CODES={english:"en",chinese:"zh",mandarin:"zh",cantonese:"yue",japanese:"ja",korean:"ko",french:"fr",german:"de",spanish:"es",italian:"it",portuguese:"pt",russian:"ru",arabic:"ar"};function resolveLanguageCode(language){if(!language){return void 0}const lower=language.toLowerCase();if(LANGUAGE_CODES[lower]){return LANGUAGE_CODES[lower]}return/^[a-z]{2,3}$/.test(lower)?lower:void 0}__name(resolveLanguageCode,"resolveLanguageCode");function buildKeytermsContext(settings){try{const keyterms=buildVoiceKeyterms(settings);return keyterms.length>0?keyterms.join(" "):void 0}catch{return void 0}}__name(buildKeytermsContext,"buildKeytermsContext");function tokenize(value){return value.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(Boolean)}__name(tokenize,"tokenize");function isKeytermEcho(transcript,keytermsContext){if(!keytermsContext){return false}const tokens=tokenize(transcript);if(tokens.length<4){return false}const keyset=new Set(tokenize(keytermsContext));const overlap=tokens.filter(t=>keyset.has(t)).length;const transcriptRatio=overlap/tokens.length;const keytermRatio=overlap/keyset.size;const isEcho=overlap>=MIN_KEYTERM_ECHO_TOKENS&&transcriptRatio>=.9&&(keytermRatio>=MIN_KEYTERM_SET_ECHO_RATIO||overlap>=MIN_ABSOLUTE_KEYTERM_ECHO_TOKENS);if(isEcho){const branch=keytermRatio>=MIN_KEYTERM_SET_ECHO_RATIO?"ratio":"absolute";debugLogger.debug(`[voice] dropped likely keyterm echo (${branch}): overlap=${overlap} keysetSize=${keyset.size} transcriptRatio=${transcriptRatio.toFixed(2)} keytermRatio=${keytermRatio.toFixed(2)} text="${transcript}"`)}return isEcho}__name(isKeytermEcho,"isKeytermEcho");var MAX_AUDIO_BYTES=10*1024*1024;var MAX_TRANSCRIPTION_ERROR_LENGTH=200;function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}__name(escapeRegExp,"escapeRegExp");function sanitizeVoiceErrorMessage(raw,apiKey){let redacted=raw.replace(/Authorization:\s*(?:Bearer|ApiKey|Basic|Token)?\s*\S+/gi,"Authorization: [REDACTED]").replace(/Bearer\s+\S+/gi,"Bearer [REDACTED]").replace(/\b(?:api[-_ ]?key|token|secret)=\S+/gi,"[REDACTED]").replace(/\bsk-[A-Za-z0-9._-]{4,}\b/g,"[REDACTED]");if(apiKey){redacted=redacted.replace(new RegExp(escapeRegExp(apiKey),"g"),"[REDACTED]")}return redacted.length>MAX_TRANSCRIPTION_ERROR_LENGTH?`${redacted.slice(0,MAX_TRANSCRIPTION_ERROR_LENGTH)}...`:redacted}__name(sanitizeVoiceErrorMessage,"sanitizeVoiceErrorMessage");function inputAudioFormat(mimeType){const subtype=mimeType.split(";",1)[0]?.trim().toLowerCase()??"";return subtype.startsWith("audio/")?subtype.slice("audio/".length)||"wav":"wav"}__name(inputAudioFormat,"inputAudioFormat");function transcriptionAbortSignal(abortSignal){const timeoutSignal=AbortSignal.timeout(INFERENCE_TIMEOUT_MS);return abortSignal?AbortSignal.any([abortSignal,timeoutSignal]):timeoutSignal}__name(transcriptionAbortSignal,"transcriptionAbortSignal");async function transcribeViaQwenAsr(audio,voiceConfig,options,fetchFn){if(audio.data.byteLength>MAX_AUDIO_BYTES){throw new Error("Recording is too long for transcription (max ~5 minutes / 10 MB). Try a shorter dictation.")}const dataUrl=`data:${audio.mimeType};base64,${Buffer.from(audio.data).toString("base64")}`;const messages=[];if(options.keytermsContext){messages.push({role:"system",content:[{type:"text",text:options.keytermsContext}]})}messages.push({role:"user",content:[{type:"input_audio",input_audio:{data:dataUrl,format:inputAudioFormat(audio.mimeType)}}]});const asrOptions={enable_itn:true};if(options.language){asrOptions["language"]=options.language}const headers={"Content-Type":"application/json"};if(voiceConfig.apiKey){headers["Authorization"]=`Bearer ${voiceConfig.apiKey}`}let response;try{options.onEgress?.();response=await fetchFn(`${trimTrailingSlashes(voiceConfig.baseUrl)}/chat/completions`,{method:"POST",headers,redirect:"manual",body:JSON.stringify({model:voiceConfig.model,messages,asr_options:asrOptions}),signal:transcriptionAbortSignal(options.abortSignal)})}catch(error){if(error instanceof DOMException&&error.name==="TimeoutError"){throw new Error(`Voice transcription timed out after ${INFERENCE_TIMEOUT_MS/1e3}s. Check ASR service health and retry.`)}throw error}if(response.status>=300&&response.status<400){throw new Error("Voice transcription request redirected.")}if(!response.ok){let details="";try{details=sanitizeVoiceErrorMessage(await response.text(),voiceConfig.apiKey)}catch{details=""}if(/model_not_supported|unsupported model/i.test(details)){throw new Error("This voice model cannot be used for batch transcription. Use qwen3-asr-flash for batch or choose a realtime voice model such as qwen3-asr-flash-realtime / fun-asr-realtime / paraformer-realtime-v2.")}const suffix=details?`: ${details}`:"";throw new Error(`Voice transcription request failed (${response.status} ${response.statusText})${suffix}`)}const json=await response.json();const content=json.choices?.[0]?.message?.content;if(typeof content!=="string"){throw new Error("Voice transcription response did not include text.")}const text=content.trim();if(isKeytermEcho(text,options.keytermsContext)){return""}return text}__name(transcribeViaQwenAsr,"transcribeViaQwenAsr");async function transcribeVoiceAudio(audio,args){const voiceConfig=resolveVoiceTranscriptionConfig(args);await assertVoiceBaseUrlNetworkAllowed(voiceConfig,args.lookupHost,args.abortSignal);const fetchFn=args.fetchFn??fetch;const language=resolveLanguageCode(readVoiceLanguage(args.settings));const keytermsContext=buildKeytermsContext(args.settings);const transport=resolveVoiceTransport(voiceConfig.model);switch(transport){case"qwen-asr-chat":return transcribeViaQwenAsr(audio,voiceConfig,{language,keytermsContext,abortSignal:args.abortSignal,...args.onEgress?{onEgress:args.onEgress}:{}},fetchFn);case"qwen-asr-realtime":case"dashscope-task-realtime":throw new Error(`Voice model '${voiceConfig.model}' requires streaming transcription.`);case"unsupported":default:throw new Error(`Voice model '${voiceConfig.model}' is not a supported transcription model.`)}}__name(transcribeVoiceAudio,"transcribeVoiceAudio");export{assertVoiceBaseUrlNetworkAllowed,resolveVoiceTranscriptionConfig,isStreamingVoiceModel,resolveVoiceStreamConfig,isKeytermEcho,MAX_AUDIO_BYTES,sanitizeVoiceErrorMessage,transcribeVoiceAudio};
3
+ import{formatUnsupportedVoiceModelMessage,isTranscribableVoiceModel,readVoiceLanguage,resolveVoiceTransport}from"./chunk-FS67DOZQ.js";import{resolvePath}from"./chunk-CFIGRBWA.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{isSubpath}from"./chunk-2ZK2FGZQ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import process from"node:process";import{lookup as dnsLookup}from"node:dns/promises";import{BlockList,isIP}from"node:net";init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var GLOBAL_KEYTERMS=["Qwen","MCP","grep","regex","localhost","codebase","TypeScript","JavaScript","JSON","YAML","OAuth","webhook","gRPC","dotfiles","subagent","worktree","stdout","stderr","async","await","API","CLI","npm","pnpm","commit","rebase","refactor","endpoint","middleware","schema","tokenizer"];var DEFAULT_KEYTERMS_FILENAME="voice-keyterms.txt";var MAX_KEYTERMS=200;var MAX_KEYTERMS_BYTES=2e3;var MAX_KEYTERMS_FILE_BYTES=64*1024;function buildVoiceKeyterms(settings){const userTerms=settings?readUserKeyterms(settings):[];return capKeyterms(dedupeKeyterms([...GLOBAL_KEYTERMS,...userTerms]))}__name(buildVoiceKeyterms,"buildVoiceKeyterms");function dedupeKeyterms(terms){const seen=new Set;const out=[];for(const term of terms){const key=term.toLowerCase();if(seen.has(key)){continue}seen.add(key);out.push(term)}return out}__name(dedupeKeyterms,"dedupeKeyterms");function capKeyterms(terms){const out=[];let bytes=0;for(const term of terms){if(out.length>=MAX_KEYTERMS){break}const next=bytes+Buffer.byteLength(term,"utf8")+(out.length>0?1:0);if(next>MAX_KEYTERMS_BYTES){continue}out.push(term);bytes=next}return out}__name(capKeyterms,"capKeyterms");function readUserKeyterms(settings){if(!settings.isTrusted){return[]}for(const resolved of resolveKeytermsFiles(settings)){try{const file=canonicalizeKeytermsFile(resolved);if(!file){continue}const content=readRegularFileNoFollow(file);if(content===void 0){continue}const parsed=parseKeyterms(content);if(parsed.length>0){return parsed}}catch{}}return[]}__name(readUserKeyterms,"readUserKeyterms");function resolveKeytermsFiles(settings){const workspacePath=settings.workspace?.path;if(!workspacePath){return[]}const qwenDir=path.dirname(workspacePath);const workspaceRoot=path.dirname(qwenDir);const configured=readKeytermsFileSettings(settings);if(configured.length>0){return configured.map(({path:configuredPath,scope})=>{const expanded=resolvePath(configuredPath);const isAbsolute2=path.isAbsolute(expanded);return{filePath:isAbsolute2?expanded:path.resolve(workspaceRoot,expanded),workspaceRoot,mustBeInWorkspace:scope==="system"||!isAbsolute2}})}return[{filePath:path.join(qwenDir,DEFAULT_KEYTERMS_FILENAME),workspaceRoot,mustBeInWorkspace:true}]}__name(resolveKeytermsFiles,"resolveKeytermsFiles");function canonicalizeKeytermsFile({filePath,workspaceRoot,mustBeInWorkspace}){const stat=fs.lstatSync(filePath,{throwIfNoEntry:false});if(!stat||stat.isSymbolicLink()||!stat.isFile()||stat.nlink>1||stat.size>MAX_KEYTERMS_FILE_BYTES){return void 0}const realFilePath=fs.realpathSync(filePath);if(mustBeInWorkspace){const realWorkspaceRoot=fs.realpathSync(workspaceRoot);if(!isSubpath(realWorkspaceRoot,realFilePath)){return void 0}}return{filePath:realFilePath,stat}}__name(canonicalizeKeytermsFile,"canonicalizeKeytermsFile");function readRegularFileNoFollow({filePath,stat:expectedStat}){let fd;try{let flags=fs.constants.O_RDONLY;if(typeof fs.constants.O_NOFOLLOW==="number"){flags|=fs.constants.O_NOFOLLOW}if(typeof fs.constants.O_NONBLOCK==="number"){flags|=fs.constants.O_NONBLOCK}fd=fs.openSync(filePath,flags);const stat=fs.fstatSync(fd);if(stat.dev!==expectedStat.dev||stat.ino!==expectedStat.ino||stat.mode!==expectedStat.mode||stat.size!==expectedStat.size||stat.mtimeMs!==expectedStat.mtimeMs||stat.ctimeMs!==expectedStat.ctimeMs||!stat.isFile()||stat.nlink>1||stat.size>MAX_KEYTERMS_FILE_BYTES){return void 0}const content=fs.readFileSync(fd,"utf-8");if(Buffer.byteLength(content,"utf8")>MAX_KEYTERMS_FILE_BYTES){return void 0}return content}finally{if(fd!==void 0){fs.closeSync(fd)}}}__name(readRegularFileNoFollow,"readRegularFileNoFollow");function parseKeyterms(content){return content.split(/\r?\n/).map(line=>line.replace(/^\s*#.*$/,"").trim()).filter(line=>line.length>0)}__name(parseKeyterms,"parseKeyterms");function readKeytermsFileSettings(settings){const out=[];const system=readKeytermsFileSettingFromScope(settings.system?.settings);if(system){out.push({path:system,scope:"system"})}const user=readKeytermsFileSettingFromScope(settings.user?.settings);if(user){out.push({path:user,scope:"user"})}return out}__name(readKeytermsFileSettings,"readKeytermsFileSettings");function readKeytermsFileSettingFromScope(settings){const value=settings?.general?.voice?.keytermsFile;if(typeof value!=="string"){return void 0}const trimmed=value.trim();return trimmed.length>0?trimmed:void 0}__name(readKeytermsFileSettingFromScope,"readKeytermsFileSettingFromScope");var DEFAULT_OPENAI_API_KEY="OPENAI_API_KEY";var INFERENCE_TIMEOUT_MS=6e4;var MIN_KEYTERM_ECHO_TOKENS=8;var MIN_ABSOLUTE_KEYTERM_ECHO_TOKENS=10;var MIN_KEYTERM_SET_ECHO_RATIO=.3;var debugLogger=createDebugLogger("VOICE_TRANSCRIBER");var BLOCKED_TRANSITION_IPV6_ADDRESSES=new BlockList;for(const[address,prefix]of[["64:ff9b:1::",48],["2001::",23],["2002::",16]]){BLOCKED_TRANSITION_IPV6_ADDRESSES.addSubnet(address,prefix,"ipv6")}function trimTrailingSlashes(value){return value.replace(/\/+$/,"")}__name(trimTrailingSlashes,"trimTrailingSlashes");function readSettingsEnv(settings,envKey){const env=settings.merged.env;const value=env?.[envKey];return typeof value==="string"&&value.trim().length>0?value.trim():void 0}__name(readSettingsEnv,"readSettingsEnv");function isQwenBaseUrl(baseUrl){try{const hostname=new URL(baseUrl).hostname.toLowerCase();return hostname==="dashscope.aliyuncs.com"||hostname==="dashscope-intl.aliyuncs.com"||hostname==="dashscope-us.aliyuncs.com"||hostname.endsWith(".dashscope.aliyuncs.com")||hostname.endsWith(".dashscope-intl.aliyuncs.com")||hostname.endsWith(".dashscope-us.aliyuncs.com")}catch{return false}}__name(isQwenBaseUrl,"isQwenBaseUrl");function normalizeBaseUrl(baseUrl,modelName){let url;try{url=new URL(baseUrl)}catch{throw new Error(`Voice model '${modelName}' has an invalid baseUrl.`)}if(url.username||url.password){throw new Error(`Voice model '${modelName}' baseUrl must not contain embedded credentials.`)}return trimTrailingSlashes(url.toString())}__name(normalizeBaseUrl,"normalizeBaseUrl");function normalizeAllowedVoiceBaseUrl(baseUrl){try{const url=new URL(baseUrl.trim());if(url.username||url.password){return void 0}return trimTrailingSlashes(url.toString())}catch{return void 0}}__name(normalizeAllowedVoiceBaseUrl,"normalizeAllowedVoiceBaseUrl");function isInsecureVoiceBaseUrlAllowed(settings,normalizedBaseUrl){const allowed=settings.merged.security?.allowedInsecureVoiceBaseUrls;return Array.isArray(allowed)&&allowed.some(candidate=>typeof candidate==="string"&&normalizeAllowedVoiceBaseUrl(candidate)===normalizedBaseUrl)}__name(isInsecureVoiceBaseUrlAllowed,"isInsecureVoiceBaseUrlAllowed");function normalizeHostname(hostname){return hostname.toLowerCase().replace(/^\[|\]$/g,"")}__name(normalizeHostname,"normalizeHostname");function normalizeIpAddress(address){const host=normalizeHostname(address);if(isIP(host)!==6){return host}try{return normalizeHostname(new URL(`http://[${host}]/`).hostname)}catch{return host}}__name(normalizeIpAddress,"normalizeIpAddress");function isLoopbackHost(hostname){const host=normalizeHostname(hostname);return host==="localhost"||host==="127.0.0.1"||host==="::1"}__name(isLoopbackHost,"isLoopbackHost");function isAwsIpv6MetadataAddress(hostname){const host=normalizeHostname(hostname);if(isIP(host)!==6){return false}try{return normalizeHostname(new URL(`http://[${host}]/`).hostname)==="fd00:ec2::254"}catch{return false}}__name(isAwsIpv6MetadataAddress,"isAwsIpv6MetadataAddress");function readIpv4CompatibleIpv6(host){if(!host.startsWith("::")||host.startsWith("::ffff:")){return void 0}const parts=host.slice(2).split(":");if(parts.length===0||parts.length>2||parts.some(part=>!part)){return void 0}if(parts.some(part=>!/^[0-9a-f]{1,4}$/i.test(part))){return void 0}const hextets=parts.map(part=>Number.parseInt(part,16));const value=hextets.length===1?hextets[0]:hextets[0]<<16|hextets[1];return[value>>>24&255,value>>>16&255,value>>>8&255,value&255].join(".")}__name(readIpv4CompatibleIpv6,"readIpv4CompatibleIpv6");function readIpv4MappedIpv6(host){const dotted=host.match(/^::ffff:(\d+(?:\.\d+){3})$/i);if(dotted&&isIP(dotted[1])===4){return dotted[1]}const hex=host.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!hex){return void 0}return readIpv4HexPair(hex[1],hex[2])}__name(readIpv4MappedIpv6,"readIpv4MappedIpv6");function readIpv4HexPair(highHex,lowHex){const high=Number.parseInt(highHex,16);const low=Number.parseInt(lowHex,16);return[high>>>8,high&255,low>>>8,low&255].join(".")}__name(readIpv4HexPair,"readIpv4HexPair");function readWellKnownNat64Ipv6(host){const prefix="64:ff9b::";if(!host.startsWith(prefix)){return void 0}const suffix=host.slice(prefix.length);if(!suffix){return"0.0.0.0"}const groups=suffix.split(":");if(groups.length>2||groups.some(group=>!/^[0-9a-f]{1,4}$/i.test(group))){return void 0}return groups.length===1?readIpv4HexPair("0",groups[0]):readIpv4HexPair(groups[0],groups[1])}__name(readWellKnownNat64Ipv6,"readWellKnownNat64Ipv6");function isBlockedTransitionIpv6Address(host){return isIP(host)===6&&BLOCKED_TRANSITION_IPV6_ADDRESSES.check(host,"ipv6")}__name(isBlockedTransitionIpv6Address,"isBlockedTransitionIpv6Address");function unwrapIpv6TransitionStep(host){const ipv4Mapped=readIpv4MappedIpv6(host);if(ipv4Mapped){return{address:ipv4Mapped}}const ipv4Compatible=readIpv4CompatibleIpv6(host);if(ipv4Compatible){return{address:ipv4Compatible}}const nat64=readWellKnownNat64Ipv6(host);if(nat64){return{address:nat64}}if(host.startsWith("::ffff:")){return"blocked"}return void 0}__name(unwrapIpv6TransitionStep,"unwrapIpv6TransitionStep");function isPrivateNetworkIp(hostname){const host=normalizeIpAddress(hostname);if(isBlockedTransitionIpv6Address(host)){return true}if(isLoopbackHost(host)){return false}const step=unwrapIpv6TransitionStep(host);if(step==="blocked"){return true}if(step){return isPrivateNetworkIp(step.address)}if(isIP(host)===4){const[first=0,second=0]=host.split(".").map(Number);return first===0||first===10||first===127||first===169&&second===254||first===172&&second>=16&&second<=31||first===192&&second===168||first===100&&second>=64&&second<=127}if(isIP(host)===6){const firstHextet=Number.parseInt(host.split(":",1)[0]||"0",16);return host==="::"||(firstHextet&65472)===65152||(firstHextet&65024)===64512}return false}__name(isPrivateNetworkIp,"isPrivateNetworkIp");function isAlwaysBlockedVoiceAddress(address){const host=normalizeIpAddress(address);if(isBlockedTransitionIpv6Address(host)){return true}if(isLoopbackHost(host)){return true}const step=unwrapIpv6TransitionStep(host);if(step==="blocked"){return true}if(step){return isAlwaysBlockedVoiceAddress(step.address)}if(isIP(host)===4){const[first=0,second=0]=host.split(".").map(Number);return first===0||first===127||first===169&&second===254||host==="100.100.100.200"}if(isIP(host)===6){const firstHextet=Number.parseInt(host.split(":",1)[0]||"0",16);return host==="::"||isAwsIpv6MetadataAddress(host)||(firstHextet&65472)===65152}return false}__name(isAlwaysBlockedVoiceAddress,"isAlwaysBlockedVoiceAddress");function isLoopbackVoiceAddress(address){const host=normalizeIpAddress(address);if(isLoopbackHost(host)){return true}const step=unwrapIpv6TransitionStep(host);if(step&&step!=="blocked"){return isLoopbackVoiceAddress(step.address)}if(isIP(host)===4){return host.startsWith("127.")}return false}__name(isLoopbackVoiceAddress,"isLoopbackVoiceAddress");async function defaultLookupHost(hostname){return dnsLookup(hostname,{all:true})}__name(defaultLookupHost,"defaultLookupHost");async function assertVoiceBaseUrlNetworkAllowed(voiceConfig,lookupHost,abortSignal){const hostname=normalizeHostname(new URL(voiceConfig.baseUrl).hostname);if(isLoopbackHost(hostname)){return}if(isIP(hostname)!==0){if(isAlwaysBlockedVoiceAddress(hostname)||!voiceConfig.allowInsecureBaseUrl&&isPrivateNetworkIp(hostname)){throw new Error(isLoopbackVoiceAddress(hostname)?`Voice model '${voiceConfig.model}' uses a loopback address outside the accepted spellings. To use a local ASR endpoint, set the baseUrl to http://localhost, http://127.0.0.1, or http://[::1].`:`Voice model '${voiceConfig.model}' resolved to a private-network address.`)}return}let result;let onAbort;try{if(abortSignal?.aborted){throw abortSignal.reason}const lookup=(lookupHost??defaultLookupHost)(hostname);result=abortSignal?await Promise.race([lookup,new Promise((_resolve,reject)=>{onAbort=__name(()=>reject(abortSignal.reason),"onAbort");if(abortSignal.aborted)onAbort();else abortSignal.addEventListener("abort",onAbort,{once:true})})]):await lookup}catch{if(abortSignal?.aborted){throw abortSignal.reason instanceof Error?abortSignal.reason:new Error("Voice request was aborted.")}throw new Error(`Voice model '${voiceConfig.model}': DNS lookup failed for ${hostname}. Cannot verify network safety.`)}finally{if(onAbort)abortSignal?.removeEventListener("abort",onAbort)}const records=Array.isArray(result)?result:[result];if(records.some(record=>isAlwaysBlockedVoiceAddress(record.address)||!voiceConfig.allowInsecureBaseUrl&&isPrivateNetworkIp(record.address))){throw new Error(records.some(record=>isLoopbackVoiceAddress(record.address))?`Voice model '${voiceConfig.model}' resolved to a loopback address. Loopback DNS results are always blocked; to use a local ASR endpoint, configure an explicit loopback baseUrl: http://localhost, http://127.0.0.1, or http://[::1].`:voiceConfig.allowInsecureBaseUrl&&records.some(record=>isAlwaysBlockedVoiceAddress(record.address))?`Voice model '${voiceConfig.model}' resolved to an address that is always blocked (metadata, link-local, or transition range), even when the baseUrl is listed in security.allowedInsecureVoiceBaseUrls.`:`Voice model '${voiceConfig.model}' resolved to a private-network address.`)}}__name(assertVoiceBaseUrlNetworkAllowed,"assertVoiceBaseUrlNetworkAllowed");function readApiKey(settings,model,baseUrl,env){if(!model.envKey&&!isQwenBaseUrl(baseUrl)){return void 0}const envKey=model.envKey??DEFAULT_OPENAI_API_KEY;const envSource=env??process.env;const envValue=Object.hasOwn(envSource,envKey)?envSource[envKey]:void 0;if(envValue&&envValue.trim().length>0){return envValue.trim()}const settingsEnvValue=readSettingsEnv(settings,envKey);if(settingsEnvValue){return settingsEnvValue}if(!model.envKey&&isQwenBaseUrl(baseUrl)){const authApiKey=settings.merged.security?.auth?.apiKey;return typeof authApiKey==="string"&&authApiKey.trim().length>0?authApiKey.trim():void 0}return void 0}__name(readApiKey,"readApiKey");function resolveVoiceTranscriptionConfig({config,settings,voiceModel,env}){const matches=config.getAllConfiguredModels().filter(model2=>model2.id===voiceModel);if(matches.length===0){throw new Error(`Voice model '${voiceModel}' is not configured. Run /model --voice to choose a configured model.`)}if(matches.length>1){throw new Error(`Voice model '${voiceModel}' is ambiguous.`)}const model=matches[0];if(!isTranscribableVoiceModel(model)){throw new Error(formatUnsupportedVoiceModelMessage(voiceModel))}const baseUrl=model.baseUrl?.trim();if(!baseUrl){throw new Error(`Voice model '${voiceModel}' does not define a baseUrl.`)}const normalizedBaseUrl=normalizeBaseUrl(baseUrl,voiceModel);const parsedBaseUrl=new URL(normalizedBaseUrl);const isLocalhost=isLoopbackHost(parsedBaseUrl.hostname);const allowInsecureBaseUrl=isInsecureVoiceBaseUrlAllowed(settings,normalizedBaseUrl);if(parsedBaseUrl.protocol!=="http:"&&parsedBaseUrl.protocol!=="https:"){throw new Error(`Voice model '${voiceModel}' must use an http or https baseUrl.`)}if(!isLocalhost&&isAlwaysBlockedVoiceAddress(parsedBaseUrl.hostname)){throw new Error(isLoopbackVoiceAddress(parsedBaseUrl.hostname)?`Voice model '${voiceModel}' uses a loopback address outside the accepted spellings. To use a local ASR endpoint, set the baseUrl to http://localhost, http://127.0.0.1, or http://[::1].`:`Voice model '${voiceModel}' must not use a private-network baseUrl.`)}if(parsedBaseUrl.protocol!=="https:"&&!isLocalhost&&!allowInsecureBaseUrl){throw new Error(`Voice model '${voiceModel}' must use an https baseUrl. Voice audio must not be transmitted in cleartext. To trust this managed endpoint, add its exact complete normalized URL (${normalizedBaseUrl}) to security.allowedInsecureVoiceBaseUrls. This setting is only honored from User, System, or SystemDefaults scope settings; Workspace entries are ignored.`)}if(!isLocalhost&&!allowInsecureBaseUrl&&isPrivateNetworkIp(parsedBaseUrl.hostname)){throw new Error(`Voice model '${voiceModel}' must not use a private-network baseUrl. To trust this managed endpoint, add its exact complete normalized URL (${normalizedBaseUrl}) to security.allowedInsecureVoiceBaseUrls. This setting is only honored from User, System, or SystemDefaults scope settings; Workspace entries are ignored.`)}const apiKey=readApiKey(settings,model,normalizedBaseUrl,env);if(model.envKey&&!apiKey){throw new Error(`Voice model '${voiceModel}' requires ${model.envKey}.`)}return{model:voiceModel,baseUrl:normalizedBaseUrl,...apiKey?{apiKey}:{},...allowInsecureBaseUrl?{allowInsecureBaseUrl:true}:{}}}__name(resolveVoiceTranscriptionConfig,"resolveVoiceTranscriptionConfig");function isStreamingVoiceModel(model){const transport=resolveVoiceTransport(model);return transport==="qwen-asr-realtime"||transport==="dashscope-task-realtime"}__name(isStreamingVoiceModel,"isStreamingVoiceModel");function resolveVoiceStreamConfig(args){const base=resolveVoiceTranscriptionConfig(args);const transport=resolveVoiceTransport(base.model);if(transport!=="qwen-asr-realtime"&&transport!=="dashscope-task-realtime"){throw new Error(`Voice model '${base.model}' does not support streaming transcription.`)}const language=resolveLanguageCode(readVoiceLanguage(args.settings));const keytermsContext=transport==="qwen-asr-realtime"?buildKeytermsContext(args.settings):void 0;return{transport,baseUrl:base.baseUrl,model:base.model,...base.apiKey?{apiKey:base.apiKey}:{},...base.allowInsecureBaseUrl?{allowInsecureBaseUrl:true}:{},...language?{language}:{},...keytermsContext?{keytermsContext}:{}}}__name(resolveVoiceStreamConfig,"resolveVoiceStreamConfig");var LANGUAGE_CODES={english:"en",chinese:"zh",mandarin:"zh",cantonese:"yue",japanese:"ja",korean:"ko",french:"fr",german:"de",spanish:"es",italian:"it",portuguese:"pt",russian:"ru",arabic:"ar"};function resolveLanguageCode(language){if(!language){return void 0}const lower=language.toLowerCase();if(LANGUAGE_CODES[lower]){return LANGUAGE_CODES[lower]}return/^[a-z]{2,3}$/.test(lower)?lower:void 0}__name(resolveLanguageCode,"resolveLanguageCode");function buildKeytermsContext(settings){try{const keyterms=buildVoiceKeyterms(settings);return keyterms.length>0?keyterms.join(" "):void 0}catch{return void 0}}__name(buildKeytermsContext,"buildKeytermsContext");function tokenize(value){return value.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu," ").split(/\s+/).filter(Boolean)}__name(tokenize,"tokenize");function isKeytermEcho(transcript,keytermsContext){if(!keytermsContext){return false}const tokens=tokenize(transcript);if(tokens.length<4){return false}const keyset=new Set(tokenize(keytermsContext));const overlap=tokens.filter(t=>keyset.has(t)).length;const transcriptRatio=overlap/tokens.length;const keytermRatio=overlap/keyset.size;const isEcho=overlap>=MIN_KEYTERM_ECHO_TOKENS&&transcriptRatio>=.9&&(keytermRatio>=MIN_KEYTERM_SET_ECHO_RATIO||overlap>=MIN_ABSOLUTE_KEYTERM_ECHO_TOKENS);if(isEcho){const branch=keytermRatio>=MIN_KEYTERM_SET_ECHO_RATIO?"ratio":"absolute";debugLogger.debug(`[voice] dropped likely keyterm echo (${branch}): overlap=${overlap} keysetSize=${keyset.size} transcriptRatio=${transcriptRatio.toFixed(2)} keytermRatio=${keytermRatio.toFixed(2)} text="${transcript}"`)}return isEcho}__name(isKeytermEcho,"isKeytermEcho");var MAX_AUDIO_BYTES=10*1024*1024;var MAX_TRANSCRIPTION_ERROR_LENGTH=200;function escapeRegExp(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}__name(escapeRegExp,"escapeRegExp");function sanitizeVoiceErrorMessage(raw,apiKey){let redacted=raw.replace(/Authorization:\s*(?:Bearer|ApiKey|Basic|Token)?\s*\S+/gi,"Authorization: [REDACTED]").replace(/Bearer\s+\S+/gi,"Bearer [REDACTED]").replace(/\b(?:api[-_ ]?key|token|secret)=\S+/gi,"[REDACTED]").replace(/\bsk-[A-Za-z0-9._-]{4,}\b/g,"[REDACTED]");if(apiKey){redacted=redacted.replace(new RegExp(escapeRegExp(apiKey),"g"),"[REDACTED]")}return redacted.length>MAX_TRANSCRIPTION_ERROR_LENGTH?`${redacted.slice(0,MAX_TRANSCRIPTION_ERROR_LENGTH)}...`:redacted}__name(sanitizeVoiceErrorMessage,"sanitizeVoiceErrorMessage");function inputAudioFormat(mimeType){const subtype=mimeType.split(";",1)[0]?.trim().toLowerCase()??"";return subtype.startsWith("audio/")?subtype.slice("audio/".length)||"wav":"wav"}__name(inputAudioFormat,"inputAudioFormat");function transcriptionAbortSignal(abortSignal){const timeoutSignal=AbortSignal.timeout(INFERENCE_TIMEOUT_MS);return abortSignal?AbortSignal.any([abortSignal,timeoutSignal]):timeoutSignal}__name(transcriptionAbortSignal,"transcriptionAbortSignal");async function transcribeViaQwenAsr(audio,voiceConfig,options,fetchFn){if(audio.data.byteLength>MAX_AUDIO_BYTES){throw new Error("Recording is too long for transcription (max ~5 minutes / 10 MB). Try a shorter dictation.")}const dataUrl=`data:${audio.mimeType};base64,${Buffer.from(audio.data).toString("base64")}`;const messages=[];if(options.keytermsContext){messages.push({role:"system",content:[{type:"text",text:options.keytermsContext}]})}messages.push({role:"user",content:[{type:"input_audio",input_audio:{data:dataUrl,format:inputAudioFormat(audio.mimeType)}}]});const asrOptions={enable_itn:true};if(options.language){asrOptions["language"]=options.language}const headers={"Content-Type":"application/json"};if(voiceConfig.apiKey){headers["Authorization"]=`Bearer ${voiceConfig.apiKey}`}let response;try{options.onEgress?.();response=await fetchFn(`${trimTrailingSlashes(voiceConfig.baseUrl)}/chat/completions`,{method:"POST",headers,redirect:"manual",body:JSON.stringify({model:voiceConfig.model,messages,asr_options:asrOptions}),signal:transcriptionAbortSignal(options.abortSignal)})}catch(error){if(error instanceof DOMException&&error.name==="TimeoutError"){throw new Error(`Voice transcription timed out after ${INFERENCE_TIMEOUT_MS/1e3}s. Check ASR service health and retry.`)}throw error}if(response.status>=300&&response.status<400){throw new Error("Voice transcription request redirected.")}if(!response.ok){let details="";try{details=sanitizeVoiceErrorMessage(await response.text(),voiceConfig.apiKey)}catch{details=""}if(/model_not_supported|unsupported model/i.test(details)){throw new Error("This voice model cannot be used for batch transcription. Use qwen3-asr-flash for batch or choose a realtime voice model such as qwen3-asr-flash-realtime / fun-asr-realtime / paraformer-realtime-v2.")}const suffix=details?`: ${details}`:"";throw new Error(`Voice transcription request failed (${response.status} ${response.statusText})${suffix}`)}const json=await response.json();const content=json.choices?.[0]?.message?.content;if(typeof content!=="string"){throw new Error("Voice transcription response did not include text.")}const text=content.trim();if(isKeytermEcho(text,options.keytermsContext)){return""}return text}__name(transcribeViaQwenAsr,"transcribeViaQwenAsr");async function transcribeVoiceAudio(audio,args){const voiceConfig=resolveVoiceTranscriptionConfig(args);await assertVoiceBaseUrlNetworkAllowed(voiceConfig,args.lookupHost,args.abortSignal);const fetchFn=args.fetchFn??fetch;const language=resolveLanguageCode(readVoiceLanguage(args.settings));const keytermsContext=buildKeytermsContext(args.settings);const transport=resolveVoiceTransport(voiceConfig.model);switch(transport){case"qwen-asr-chat":return transcribeViaQwenAsr(audio,voiceConfig,{language,keytermsContext,abortSignal:args.abortSignal,...args.onEgress?{onEgress:args.onEgress}:{}},fetchFn);case"qwen-asr-realtime":case"dashscope-task-realtime":throw new Error(`Voice model '${voiceConfig.model}' requires streaming transcription.`);case"unsupported":default:throw new Error(`Voice model '${voiceConfig.model}' is not a supported transcription model.`)}}__name(transcribeVoiceAudio,"transcribeVoiceAudio");export{assertVoiceBaseUrlNetworkAllowed,resolveVoiceTranscriptionConfig,isStreamingVoiceModel,resolveVoiceStreamConfig,isKeytermEcho,MAX_AUDIO_BYTES,sanitizeVoiceErrorMessage,transcribeVoiceAudio};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{resolveLandlockRunner,resolveStdinBridge}from"./chunk-4ZRCV3JY.js";import{executeSandboxRelay,sandboxAsset}from"./chunk-FCB7X7TI.js";import{ShellExecutionService}from"./chunk-MEUP65FI.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{realpathSync}from"node:fs";import path from"node:path";async function probeLandlock(policy,signal){if(policy.network!=="open"){throw new Error("Landlock cannot enforce network: closed.")}if(policy.maskedPaths?.length)throw new Error("Landlock cannot enforce masked paths.");const runner=resolveLandlockRunner(policy.landlockPath);const handle=await ShellExecutionService.executeLaunch({executable:runner,args:["--probe"],cwd:policy.workspace,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8"}},()=>{},signal,false,{});const result=await handle.result;if(result.error||result.aborted||result.exitCode!==0){throw new Error(`Landlock capability probe failed: ${result.error?.message??(result.output||`exit ${result.exitCode}`)}`)}let parsed;try{parsed=JSON.parse(result.output.trim())}catch{throw new Error("Landlock capability probe returned an invalid report.")}if(typeof parsed["abi"]!=="number"||!Number.isInteger(parsed["abi"])||parsed["abi"]<3||parsed["enforcement"]!=="partial"){throw new Error("Landlock capability probe returned an invalid report.")}const policyProbe=await executeLandlock(policy,{executable:"/usr/bin/true",args:[],cwd:policy.workspace,env:{PATH:"/usr/bin:/bin"}},()=>{},signal);const policyResult=await policyProbe.result;if(policyResult.sandboxStatus.state!=="confirmed"||policyResult.sandboxStatus.exitCode!==0||policyResult.error||policyResult.aborted){throw new Error(`Landlock policy probe failed: ${policyResult.error?.message||policyResult.output||policyResult.sandboxStatus.state}`)}return{abi:parsed["abi"],enforcement:"partial"}}__name(probeLandlock,"probeLandlock");async function executeLandlock(policy,payload,onOutput,signal,usePty=false,config={},options={}){if(policy.network!=="open")throw new Error("Landlock cannot enforce network: closed.");if(policy.maskedPaths?.length)throw new Error("Landlock cannot enforce masked paths.");const runner=resolveLandlockRunner(policy.landlockPath);const relay=sandboxAsset("landlock-relay");const inputBridge=payload.inheritStdin?resolveStdinBridge(policy.landlockPath):void 0;const interpreter=realpathSync(getJsInterpreterCommand(import.meta.url).command);return executeSandboxRelay(policy,payload,[path.dirname(runner),path.dirname(relay),path.dirname(interpreter),...inputBridge?[path.dirname(inputBridge)]:[]],({workspace,cwd,executable,args,filesystem,scratch,statusPath,payloadEnvPath,env,stdin,inheritStdin})=>{const runnerArgs=["--status-fd","3","--ro","/","--rw","/dev/null","--rw",scratch];if(filesystem==="workspace-write")runnerArgs.push("--rw",workspace);runnerArgs.push("--",executable,...args);return{executable:interpreter,args:[relay,String(process.pid),statusPath,payloadEnvPath,inputBridge??"",runner,...runnerArgs],cwd,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8",PWD:cwd,TERM:env["TERM"]||"xterm-256color"},stdin,inheritStdin}},onOutput,signal,usePty,config,options)}__name(executeLandlock,"executeLandlock");export{probeLandlock,executeLandlock};
3
+ import{resolveLandlockRunner,resolveStdinBridge}from"./chunk-4ZRCV3JY.js";import{executeSandboxRelay,sandboxAsset}from"./chunk-NCBA52SB.js";import{ShellExecutionService}from"./chunk-QTCO5I4C.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{realpathSync}from"node:fs";import path from"node:path";async function probeLandlock(policy,signal){if(policy.network!=="open"){throw new Error("Landlock cannot enforce network: closed.")}if(policy.maskedPaths?.length)throw new Error("Landlock cannot enforce masked paths.");const runner=resolveLandlockRunner(policy.landlockPath);const handle=await ShellExecutionService.executeLaunch({executable:runner,args:["--probe"],cwd:policy.workspace,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8"}},()=>{},signal,false,{});const result=await handle.result;if(result.error||result.aborted||result.exitCode!==0){throw new Error(`Landlock capability probe failed: ${result.error?.message??(result.output||`exit ${result.exitCode}`)}`)}let parsed;try{parsed=JSON.parse(result.output.trim())}catch{throw new Error("Landlock capability probe returned an invalid report.")}if(typeof parsed["abi"]!=="number"||!Number.isInteger(parsed["abi"])||parsed["abi"]<3||parsed["enforcement"]!=="partial"){throw new Error("Landlock capability probe returned an invalid report.")}const policyProbe=await executeLandlock(policy,{executable:"/usr/bin/true",args:[],cwd:policy.workspace,env:{PATH:"/usr/bin:/bin"}},()=>{},signal);const policyResult=await policyProbe.result;if(policyResult.sandboxStatus.state!=="confirmed"||policyResult.sandboxStatus.exitCode!==0||policyResult.error||policyResult.aborted){throw new Error(`Landlock policy probe failed: ${policyResult.error?.message||policyResult.output||policyResult.sandboxStatus.state}`)}return{abi:parsed["abi"],enforcement:"partial"}}__name(probeLandlock,"probeLandlock");async function executeLandlock(policy,payload,onOutput,signal,usePty=false,config={},options={}){if(policy.network!=="open")throw new Error("Landlock cannot enforce network: closed.");if(policy.maskedPaths?.length)throw new Error("Landlock cannot enforce masked paths.");const runner=resolveLandlockRunner(policy.landlockPath);const relay=sandboxAsset("landlock-relay");const inputBridge=payload.inheritStdin?resolveStdinBridge(policy.landlockPath):void 0;const interpreter=realpathSync(getJsInterpreterCommand(import.meta.url).command);return executeSandboxRelay(policy,payload,[path.dirname(runner),path.dirname(relay),path.dirname(interpreter),...inputBridge?[path.dirname(inputBridge)]:[]],({workspace,cwd,executable,args,filesystem,scratch,statusPath,payloadEnvPath,env,stdin,inheritStdin})=>{const runnerArgs=["--status-fd","3","--ro","/","--rw","/dev/null","--rw",scratch];if(filesystem==="workspace-write")runnerArgs.push("--rw",workspace);runnerArgs.push("--",executable,...args);return{executable:interpreter,args:[relay,String(process.pid),statusPath,payloadEnvPath,inputBridge??"",runner,...runnerArgs],cwd,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8",PWD:cwd,TERM:env["TERM"]||"xterm-256color"},stdin,inheritStdin}},onOutput,signal,usePty,config,options)}__name(executeLandlock,"executeLandlock");export{probeLandlock,executeLandlock};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team