@hostclubeos/miraos 0.0.7-beta → 0.0.9-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 (239) hide show
  1. package/chunks/{MaxSizedBox-CBUPHLMW.js → MaxSizedBox-6CGCRBRO.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-EXZJQKTK.js → StandaloneSessionPicker-7VQOS4TU.js} +1 -1
  3. package/chunks/{acp-subagent-executor-BMIXP52W.js → acp-subagent-executor-BFQRCU7R.js} +1 -1
  4. package/chunks/{acpAgent-JC4KGTLW.js → acpAgent-PCXQRPNU.js} +3 -3
  5. package/chunks/{advisor-5RUG3VFZ.js → advisor-WDZ5N5ZP.js} +1 -1
  6. package/chunks/{agent-SGQ7AEZI.js → agent-I7Q3IPSS.js} +1 -1
  7. package/chunks/{agent-headless-ZGCZ2DA7.js → agent-headless-6LOYWI5T.js} +1 -1
  8. package/chunks/{agent-host-client-HY5GPSHM.js → agent-host-client-PZZKCNQF.js} +1 -1
  9. package/chunks/{agent-host-connections-KGTBS37X.js → agent-host-connections-TWWSRTKJ.js} +1 -1
  10. package/chunks/{autofix-pr-E62FC67X.js → autofix-pr-RQPGPQ4D.js} +1 -1
  11. package/chunks/{batch-OUC6FGCQ.js → batch-UJD5TSBN.js} +1 -1
  12. package/chunks/{bridge-FLEIBB5V.js → bridge-4TYLRPXZ.js} +1 -1
  13. package/chunks/{channel-settings-store-QG6HREVH.js → channel-settings-store-RENJMOQ5.js} +1 -1
  14. package/chunks/{chunk-K7VOBDFT.js → chunk-24PHAWM3.js} +1 -1
  15. package/chunks/{chunk-7F5IYTVE.js → chunk-26JPBN6V.js} +1 -1
  16. package/chunks/{chunk-V5Z6OEKJ.js → chunk-2MQH3J4U.js} +1 -1
  17. package/chunks/{chunk-UOYXBAN7.js → chunk-2RXOWQSQ.js} +1 -1
  18. package/chunks/{chunk-H2QXWIRZ.js → chunk-323HUW2T.js} +1 -1
  19. package/chunks/{chunk-KNW2OD46.js → chunk-3BHXE7CB.js} +1 -1
  20. package/chunks/{chunk-RWFOQXPU.js → chunk-3GYAEXAA.js} +1 -1
  21. package/chunks/{chunk-W6IOHGWW.js → chunk-3YBZW4HP.js} +1 -1
  22. package/chunks/{chunk-23543L6E.js → chunk-4RJ2RRGZ.js} +1 -1
  23. package/chunks/{chunk-2PB6TEZU.js → chunk-5DIW4X4P.js} +1 -1
  24. package/chunks/{chunk-4346FNTB.js → chunk-5GB6JNJX.js} +1 -1
  25. package/chunks/{chunk-VRAHMOQQ.js → chunk-5HSNCG73.js} +2 -2
  26. package/chunks/{chunk-PQOQONLN.js → chunk-6HDMM7TJ.js} +1 -1
  27. package/chunks/{chunk-K7KY7FIB.js → chunk-6STNGEYC.js} +1 -1
  28. package/chunks/{chunk-7VP4KALB.js → chunk-7EFWNFJJ.js} +1 -1
  29. package/chunks/{chunk-ATVRF62A.js → chunk-7EWIKIJI.js} +1 -1
  30. package/chunks/{chunk-T5PDEAU5.js → chunk-7TB6VG72.js} +1 -1
  31. package/chunks/{chunk-4WYKHP7Q.js → chunk-7TLL4JLR.js} +1 -1
  32. package/chunks/{chunk-JDABSS6M.js → chunk-AOMXZNMX.js} +1 -1
  33. package/chunks/{chunk-FK5L2WVV.js → chunk-AUM57JI2.js} +1 -1
  34. package/chunks/{chunk-KK6SQPYG.js → chunk-AW5UCOZO.js} +1 -1
  35. package/chunks/{chunk-WC72OWF2.js → chunk-C6HVNDQT.js} +2 -2
  36. package/chunks/{chunk-BSLIVO6O.js → chunk-CC6E5CQV.js} +1 -1
  37. package/chunks/{chunk-AIAYQAPA.js → chunk-CLKUQP27.js} +1 -1
  38. package/chunks/{chunk-2QYFSBJY.js → chunk-DFMQQM4M.js} +1 -1
  39. package/chunks/{chunk-MMGNOY3U.js → chunk-DP7LJTG2.js} +5 -5
  40. package/chunks/{chunk-MYS5NQXO.js → chunk-DQT5VL7G.js} +1 -1
  41. package/chunks/{chunk-FC7SJIAS.js → chunk-E4QOAV5O.js} +1 -1
  42. package/chunks/{chunk-3MBYQYPC.js → chunk-E4REGDEZ.js} +1 -1
  43. package/chunks/{chunk-WCLAVBNR.js → chunk-EAG7VZJJ.js} +1 -1
  44. package/chunks/{chunk-GQ24VFGQ.js → chunk-EFO6J22W.js} +1 -1
  45. package/chunks/{chunk-6RDYPRV6.js → chunk-EMR4QK2F.js} +1 -1
  46. package/chunks/{chunk-WZTO3EYG.js → chunk-EYECE2PH.js} +1 -1
  47. package/chunks/{chunk-UWMLSAQY.js → chunk-EZDXHUHB.js} +1 -1
  48. package/chunks/{chunk-T3A53XMM.js → chunk-FJFTKA4H.js} +1 -1
  49. package/chunks/{chunk-W2ZVZ6LS.js → chunk-FSLDNLNU.js} +1 -1
  50. package/chunks/{chunk-O6Z3KO6R.js → chunk-FSRXTX3N.js} +1 -1
  51. package/chunks/{chunk-TFITRCIC.js → chunk-FWSXFRIQ.js} +1 -1
  52. package/chunks/{chunk-TU5QHOJC.js → chunk-G4ATLMDH.js} +1 -1
  53. package/chunks/{chunk-DF6TBGS2.js → chunk-GAS3HKRX.js} +1 -1
  54. package/chunks/{chunk-YVN32EUM.js → chunk-GFFL2LR2.js} +1 -1
  55. package/chunks/{chunk-TLZM3DMY.js → chunk-GYFIY7TD.js} +1 -1
  56. package/chunks/{chunk-PGKFDR73.js → chunk-GYXRI4P5.js} +1 -1
  57. package/chunks/{chunk-3KFLO5W3.js → chunk-H3U7DXIU.js} +1 -1
  58. package/chunks/{chunk-YN6WXB6B.js → chunk-HEDVPRMD.js} +1 -1
  59. package/chunks/{chunk-JJDF5FHA.js → chunk-HI3644FQ.js} +1 -1
  60. package/chunks/{chunk-HASJX2YS.js → chunk-HTHYLMBO.js} +1 -1
  61. package/chunks/{chunk-4MGTY3CJ.js → chunk-IW7RPDV2.js} +1 -1
  62. package/chunks/{chunk-SCHCTQCG.js → chunk-IXQI4K6O.js} +1 -1
  63. package/chunks/chunk-IYH3IZL4.js +13 -0
  64. package/chunks/{chunk-EF3HUB7S.js → chunk-J52J35K4.js} +1 -1
  65. package/chunks/{chunk-TXL535SJ.js → chunk-J7L5IHLG.js} +1 -1
  66. package/chunks/{chunk-N7WQH6L4.js → chunk-JHS5B4N7.js} +2 -2
  67. package/chunks/{chunk-P5543CFV.js → chunk-JRSO5ZGU.js} +1 -1
  68. package/chunks/{chunk-G35E5UB3.js → chunk-JS6VAGRQ.js} +1 -1
  69. package/chunks/{chunk-Z4JY3HGO.js → chunk-KAFPULGU.js} +1 -1
  70. package/chunks/{chunk-RNPVWQ3V.js → chunk-LDP47G5M.js} +1 -1
  71. package/chunks/{chunk-EW3EVEYN.js → chunk-LMZZWPKA.js} +1 -1
  72. package/chunks/{chunk-5RYDKYIR.js → chunk-LNCELICB.js} +1 -1
  73. package/chunks/{chunk-JDHMSERR.js → chunk-LY2DRNTZ.js} +1 -1
  74. package/chunks/{chunk-7W5DOBKY.js → chunk-MMGGGYSJ.js} +1 -1
  75. package/chunks/{chunk-CUY6CVSL.js → chunk-MTBU2ZIM.js} +1 -1
  76. package/chunks/{chunk-TWJ4XBED.js → chunk-N27KICJQ.js} +1 -1
  77. package/chunks/{chunk-JQOLNQQN.js → chunk-NHYFTK4O.js} +1 -1
  78. package/chunks/{chunk-NGH27AWP.js → chunk-NRDHXSEE.js} +1 -1
  79. package/chunks/{chunk-3GJ56V2J.js → chunk-NV5VVTYQ.js} +1 -1
  80. package/chunks/{chunk-VJUTDS6C.js → chunk-OEDMFKZL.js} +1 -1
  81. package/chunks/{chunk-PVHBBTAU.js → chunk-OQAVMR6K.js} +1 -1
  82. package/chunks/{chunk-IF3SWUYT.js → chunk-OY3Y6EMV.js} +1 -1
  83. package/chunks/{chunk-SOCXRMZM.js → chunk-OZL4ZMGQ.js} +2 -2
  84. package/chunks/{chunk-GLQWA4W2.js → chunk-PKSPKVFH.js} +1 -1
  85. package/chunks/{chunk-KYK53GFP.js → chunk-PNFKCYZT.js} +1 -1
  86. package/chunks/{chunk-7SAR6NXA.js → chunk-PTWHFVGG.js} +2 -2
  87. package/chunks/{chunk-RBA3TP7L.js → chunk-QJ6ZTZFC.js} +1 -1
  88. package/chunks/{chunk-PFECH6U6.js → chunk-QRGWB7IX.js} +1 -1
  89. package/chunks/{chunk-VBJV7T47.js → chunk-QRP2GXQD.js} +1 -1
  90. package/chunks/{chunk-WJLHLFIR.js → chunk-RES5ET63.js} +1 -1
  91. package/chunks/{chunk-GY4ID3EB.js → chunk-ROSJCTWB.js} +1 -1
  92. package/chunks/{chunk-4KIFAVR2.js → chunk-RR3NFNWL.js} +1 -1
  93. package/chunks/{chunk-2ZWVSKPK.js → chunk-RYQDRFLW.js} +1 -1
  94. package/chunks/{chunk-NVD63O5H.js → chunk-S7CWSAUQ.js} +1 -1
  95. package/chunks/{chunk-66DZADDA.js → chunk-SAJKF4WS.js} +1 -1
  96. package/chunks/chunk-SINRWOVD.js +36 -0
  97. package/chunks/{chunk-HSN5QUS7.js → chunk-SJNQ6I23.js} +1 -1
  98. package/chunks/{chunk-3NB3FFLR.js → chunk-T2GM4S4G.js} +3 -3
  99. package/chunks/{chunk-GN7ODRDE.js → chunk-TCQJO42E.js} +1 -1
  100. package/chunks/{chunk-67PM7M5R.js → chunk-TIIDF23U.js} +2 -2
  101. package/chunks/{chunk-USR2Y7B3.js → chunk-TKH5R7RZ.js} +1 -1
  102. package/chunks/{chunk-GTQULDIL.js → chunk-TSRTZD3X.js} +1 -1
  103. package/chunks/{chunk-GXNGLDUN.js → chunk-UXSXKLRH.js} +1 -1
  104. package/chunks/{chunk-JJQJFMPL.js → chunk-UYI5AMPI.js} +1 -1
  105. package/chunks/{chunk-SHKSVOTG.js → chunk-VO6SPDH4.js} +1 -1
  106. package/chunks/{chunk-AE6E2YKY.js → chunk-VRIHYTDI.js} +1 -1
  107. package/chunks/{chunk-6T25QVBX.js → chunk-VT47A26Q.js} +1 -1
  108. package/chunks/{chunk-2VW4HXVF.js → chunk-VZOZUCZX.js} +1 -1
  109. package/chunks/{chunk-724YPZRX.js → chunk-WLEGTKGA.js} +1 -1
  110. package/chunks/{chunk-ZOWMHZWO.js → chunk-XHCJN4A2.js} +1 -1
  111. package/chunks/{chunk-J773THNP.js → chunk-XTRZ5PHG.js} +1 -1
  112. package/chunks/{chunk-H65ZVST6.js → chunk-Y4GZOZWD.js} +1 -1
  113. package/chunks/{chunk-E6LRCLLE.js → chunk-YUCAGV52.js} +2 -2
  114. package/chunks/{chunk-FS67DOZQ.js → chunk-YWQM4TSO.js} +1 -1
  115. package/chunks/{chunk-P42MFWO2.js → chunk-YYTOHY4V.js} +1 -1
  116. package/chunks/{chunk-PSSJDUZB.js → chunk-Z25W2S5N.js} +1 -1
  117. package/chunks/{chunk-VF2UWWI2.js → chunk-Z6GECBAJ.js} +1 -1
  118. package/chunks/{chunk-HZ4L4MDM.js → chunk-ZJU4B4WX.js} +1 -1
  119. package/chunks/{chunk-RRMTSVGU.js → chunk-ZSHDQPAO.js} +1 -1
  120. package/chunks/{chunk-PFKTTUGS.js → chunk-ZUWLTGSR.js} +6 -6
  121. package/chunks/{codex-subagent-executor-UCDGQFTR.js → codex-subagent-executor-2V4NB7IR.js} +1 -1
  122. package/chunks/{config-utils-Z6F4DVLG.js → config-utils-5B2LYCON.js} +1 -1
  123. package/chunks/{contextCommand-HMVZT56Y.js → contextCommand-UPQGRXWK.js} +1 -1
  124. package/chunks/{core-runtime-AV7CJXOL.js → core-runtime-DPMH2BXK.js} +1 -1
  125. package/chunks/{create-sub-session-NNKVHZKT.js → create-sub-session-EJVB3FE5.js} +1 -1
  126. package/chunks/{cron-create-HWZDFVPA.js → cron-create-V2A7PMQC.js} +1 -1
  127. package/chunks/{daemon-git-worktree-guard-Q3C45X7T.js → daemon-git-worktree-guard-YEIMR2X7.js} +1 -1
  128. package/chunks/{daemon-status-provider-UX574XBB.js → daemon-status-provider-6BRB5TG3.js} +1 -1
  129. package/chunks/{daemon-trust-policy-6D4KJANB.js → daemon-trust-policy-BEXVFO4M.js} +1 -1
  130. package/chunks/{daemon-trust-policy-monitor-BZ46W4IA.js → daemon-trust-policy-monitor-BVS6LXBX.js} +1 -1
  131. package/chunks/{deferred-core-runtime-YC5XIWEI.js → deferred-core-runtime-NTKFHL5J.js} +1 -1
  132. package/chunks/{edit-LOWDEKPX.js → edit-LRG3TMHP.js} +1 -1
  133. package/chunks/{enterPlanMode-NGSATDRH.js → enterPlanMode-KOUSHJHR.js} +1 -1
  134. package/chunks/{environment-CVIB5DW4.js → environment-54CM3OXE.js} +1 -1
  135. package/chunks/{errors-USKSVZFO.js → errors-D6XR3NH4.js} +1 -1
  136. package/chunks/{execution-tool-QSJLRU5N.js → execution-tool-7RZ2JLEK.js} +1 -1
  137. package/chunks/{execution-worker-TQEIC4AJ.js → execution-worker-LXQ7WAFG.js} +1 -1
  138. package/chunks/{exitPlanMode-AW2HOTIK.js → exitPlanMode-4FGFA2QC.js} +1 -1
  139. package/chunks/{fast-path-OQWHYDXC.js → fast-path-4B7OKPYK.js} +1 -1
  140. package/chunks/{glob-7U6FQSWZ.js → glob-N2D7SY23.js} +1 -1
  141. package/chunks/{goal-tools-5ZB6GPCJ.js → goal-tools-7RNSDRFO.js} +1 -1
  142. package/chunks/{handleAutoUpdate-MLUFTWFP.js → handleAutoUpdate-PKKJQAKG.js} +1 -1
  143. package/chunks/{i18n-QAPQLOC3.js → i18n-F3OAHCLJ.js} +1 -1
  144. package/chunks/{initializer-B27IZ7K4.js → initializer-OL3DDWR7.js} +1 -1
  145. package/chunks/{installationInfo-SAMHABWV.js → installationInfo-D2L743RV.js} +1 -1
  146. package/chunks/{interactive-mod-session-7LQ5CYUR.js → interactive-mod-session-2GXRCQKR.js} +1 -1
  147. package/chunks/{list-TDMJQDQO.js → list-PU7ZXBY5.js} +1 -1
  148. package/chunks/{llm-R2RFT63S.js → llm-V42HGUVH.js} +4 -4
  149. package/chunks/{loadedSettingsAdapter-ZQK5KMEW.js → loadedSettingsAdapter-KAEVWWRX.js} +1 -1
  150. package/chunks/{local-AONDQYFL.js → local-KM5F5RAB.js} +1 -1
  151. package/chunks/{local-execution-environment-WJVCE26F.js → local-execution-environment-OEO2KW3M.js} +1 -1
  152. package/chunks/{loggingContentGenerator-ALSG42YA.js → loggingContentGenerator-DQLXSDZR.js} +1 -1
  153. package/chunks/{loop-wakeup-LFU4LDJM.js → loop-wakeup-CJICM24Y.js} +1 -1
  154. package/chunks/{manage-memory-FBL6CHX2.js → manage-memory-7CV6LF4C.js} +1 -1
  155. package/chunks/{managed-execution-engine-FX7FDAWW.js → managed-execution-engine-JEAIQ7L4.js} +1 -1
  156. package/chunks/{managed-local-serve-DRNC6PTL.js → managed-local-serve-KA37YWRW.js} +1 -1
  157. package/chunks/{managed-npm-update-2MKV7UOI.js → managed-npm-update-TSUUH3NN.js} +1 -1
  158. package/chunks/{managed-runtime-attestation-worker-DBAHM5MN.js → managed-runtime-attestation-worker-PUZ2ECM5.js} +1 -1
  159. package/chunks/{managed-runtime-bootstrap-K3GRKDNQ.js → managed-runtime-bootstrap-SERIRKPD.js} +1 -1
  160. package/chunks/{managed-runtime-session-worker-YN4KML7A.js → managed-runtime-session-worker-UOXK63YX.js} +1 -1
  161. package/chunks/{managed-runtime-ssh-worker-AVNBWFYC.js → managed-runtime-ssh-worker-VKZYIX6R.js} +1 -1
  162. package/chunks/{managed-session-authority-MFEINLXC.js → managed-session-authority-5FYS3G3M.js} +1 -1
  163. package/chunks/{mcp-TS5PX5FY.js → mcp-TRPV3K74.js} +1 -1
  164. package/chunks/{memory-JVT5LAWJ.js → memory-5CMNRPM2.js} +1 -1
  165. package/chunks/{model-call-collection-TNBMD3YL.js → model-call-collection-S4JKVFUO.js} +1 -1
  166. package/chunks/{model-configuration-6KTQQTMO.js → model-configuration-NEIDLKWQ.js} +1 -1
  167. package/chunks/{modelConfigUtils-LCZZ3EQU.js → modelConfigUtils-LZLQOZKJ.js} +1 -1
  168. package/chunks/{monitor-KCCNIKLE.js → monitor-5MNKK5AO.js} +1 -1
  169. package/chunks/{nonInteractiveCli-2GHQYHGW.js → nonInteractiveCli-DDTGU2ER.js} +1 -1
  170. package/chunks/{nonInteractiveToolExecutor-R5CTTWKD.js → nonInteractiveToolExecutor-N7PCYCKO.js} +1 -1
  171. package/chunks/{notebook-edit-KIWE2XOA.js → notebook-edit-7HIBTFFW.js} +1 -1
  172. package/chunks/{omni-IFTMWBMU.js → omni-MX7BMOL5.js} +1 -1
  173. package/chunks/{openaiContentGenerator-XP3VPU6C.js → openaiContentGenerator-NOIIZNRX.js} +1 -1
  174. package/chunks/{openaiResponsesContentGenerator-ZJ6C22EA.js → openaiResponsesContentGenerator-5JJ6G7RS.js} +1 -1
  175. package/chunks/{pidfile-42P24JIA.js → pidfile-OHAGZOTV.js} +1 -1
  176. package/chunks/{processUtils-I2XOO5U2.js → processUtils-TCDNCYVB.js} +1 -1
  177. package/chunks/{prompt-terminal-ledger-7EW46VQ4.js → prompt-terminal-ledger-4ZUOCMOS.js} +1 -1
  178. package/chunks/{reactive-degrade-O4JO7MOX.js → reactive-degrade-C7CGUJNP.js} +1 -1
  179. package/chunks/{read-file-VGC4O7F2.js → read-file-L4ZF6VDG.js} +1 -1
  180. package/chunks/{resumeHistoryUtils-QMVIHQRW.js → resumeHistoryUtils-WK3I4OIL.js} +1 -1
  181. package/chunks/{review-NDK2B7XI.js → review-F6JGI2LP.js} +1 -1
  182. package/chunks/{ripGrep-JY4PZABK.js → ripGrep-L6M2GPCM.js} +1 -1
  183. package/chunks/{run-qwen-serve-P5X5OZUH.js → run-qwen-serve-D5HB55SC.js} +1 -1
  184. package/chunks/{runtime-OL7B72CH.js → runtime-CH3RAOQL.js} +1 -1
  185. package/chunks/{sandboxConfig-EJTMWZHD.js → sandboxConfig-EADWCO37.js} +1 -1
  186. package/chunks/{scheduled-tasks-XQSZWZXG.js → scheduled-tasks-PBKD4BHY.js} +1 -1
  187. package/chunks/{scheduler-3TIRZEVB.js → scheduler-U5K3523K.js} +1 -1
  188. package/chunks/{search-memory-P5KOTUVV.js → search-memory-Y2IPKBDP.js} +1 -1
  189. package/chunks/{send-message-KFSKFXLX.js → send-message-JJQG2S6D.js} +1 -1
  190. package/chunks/{serve-UHEH433U.js → serve-2ZYS47MO.js} +1 -1
  191. package/chunks/{server-ARYDETSZ.js → server-5GMO4IHU.js} +3 -3
  192. package/chunks/{session-HKWGCZF2.js → session-LLOOVSHK.js} +1 -1
  193. package/chunks/{session-attachments-root-O3YQ7HWD.js → session-attachments-root-XCLXH2XO.js} +1 -1
  194. package/chunks/{session-execution-engine-selector-LZBHS3UO.js → session-execution-engine-selector-5QPWJZSF.js} +1 -1
  195. package/chunks/{session-pr-refresh-L5Z5WCXS.js → session-pr-refresh-MDBOAN3R.js} +1 -1
  196. package/chunks/{sessionService-MMPZUN5X.js → sessionService-VKAHCTCC.js} +1 -1
  197. package/chunks/{settings-7PYHXPN4.js → settings-ULEB2IYZ.js} +1 -1
  198. package/chunks/{shell-E6QLKRVU.js → shell-RBEKIYKU.js} +1 -1
  199. package/chunks/{skill-55IZUUM5.js → skill-GEVOEFMZ.js} +1 -1
  200. package/chunks/{skill-settings-A2M5BPH7.js → skill-settings-4IMGLYJW.js} +1 -1
  201. package/chunks/{spawnChannel-KWU26CB7.js → spawnChannel-B7L5PWQ6.js} +1 -1
  202. package/chunks/{standalone-update-32WYZ3BJ.js → standalone-update-SYQM6NOC.js} +1 -1
  203. package/chunks/{start-opentui-ui-S7A4FBGP.js → start-opentui-ui-N427PLF4.js} +2 -2
  204. package/chunks/{startInteractiveUI-DY6DWFW7.js → startInteractiveUI-AS6GZKJJ.js} +1 -1
  205. package/chunks/{team-create-ARICYIQB.js → team-create-MN6FHUHU.js} +1 -1
  206. package/chunks/{team-plan-approval-JPRE6Q3R.js → team-plan-approval-OUYBIT7H.js} +1 -1
  207. package/chunks/{terminal-image-renderer-HVIZ2VNE.js → terminal-image-renderer-MXZDUEOS.js} +1 -1
  208. package/chunks/{theme-manager-UEPLIBUP.js → theme-manager-QOYSKWFK.js} +1 -1
  209. package/chunks/{tool-call-EFJKXI3Z.js → tool-call-Q5NLEQFD.js} +1 -1
  210. package/chunks/{tool-result-media-LMIYNXSD.js → tool-result-media-NZJZTOBQ.js} +1 -1
  211. package/chunks/{tool-search-D7HQTRQG.js → tool-search-D6Y45RNQ.js} +1 -1
  212. package/chunks/{total-session-admission-67QMR44O.js → total-session-admission-36W7MDHP.js} +1 -1
  213. package/chunks/{trustedFolders-HARYVS3F.js → trustedFolders-XW5VH6HK.js} +1 -1
  214. package/chunks/{update-relaunch-NVNPOK5J.js → update-relaunch-KQPR2HAP.js} +1 -1
  215. package/chunks/{updateCheck-7NMXUCTN.js → updateCheck-SRW67WAX.js} +1 -1
  216. package/chunks/{upload-config-W2SICJ32.js → upload-config-BTJNYMRX.js} +1 -1
  217. package/chunks/{useAutoAcceptIndicator-ELMIP4TJ.js → useAutoAcceptIndicator-N3RRUBSL.js} +1 -1
  218. package/chunks/{validateNonInterActiveAuth-P2F6MYO6.js → validateNonInterActiveAuth-SWNH4FY4.js} +1 -1
  219. package/chunks/{version-2ZFKVIIW.js → version-6R6LSGXO.js} +1 -1
  220. package/chunks/{web-fetch-537RS6IX.js → web-fetch-Y7LBAU3R.js} +1 -1
  221. package/chunks/{web-search-O27MYFSW.js → web-search-IB4NYYUH.js} +1 -1
  222. package/chunks/{workflow-6QF4RMYM.js → workflow-TR4YIPJO.js} +1 -1
  223. package/chunks/{workflow-ancestor-trust-CABLU3VV.js → workflow-ancestor-trust-AHDUBOR7.js} +1 -1
  224. package/chunks/{workspace-agents-5WP3PY7W.js → workspace-agents-MY2NFL6A.js} +1 -1
  225. package/chunks/{workspace-providers-status-7G2EJJEO.js → workspace-providers-status-DNCCKFVE.js} +1 -1
  226. package/chunks/{workspace-recovery-worker-ICCIDEWU.js → workspace-recovery-worker-22VK4T4R.js} +1 -1
  227. package/chunks/{workspace-registration-store-WHXMNQQQ.js → workspace-registration-store-64TGRRGC.js} +1 -1
  228. package/chunks/{workspace-registry-NXBODLYH.js → workspace-registry-E6LFL5GL.js} +1 -1
  229. package/chunks/{workspace-runtime-coordinator-CJXS273B.js → workspace-runtime-coordinator-UHJHBIQT.js} +1 -1
  230. package/chunks/{workspace-service-HUDE2RXN.js → workspace-service-OVEYIQOC.js} +1 -1
  231. package/chunks/{workspace-skills-status-FJC6U62F.js → workspace-skills-status-3NKXA5SK.js} +1 -1
  232. package/chunks/{workspace-trust-reconciler-ZIQ3A5ZB.js → workspace-trust-reconciler-JF7YHR52.js} +1 -1
  233. package/chunks/{write-file-652YGG7I.js → write-file-FSTHYKKZ.js} +1 -1
  234. package/chunks/{zoom-image-YEH4O74G.js → zoom-image-JP3EUDXE.js} +1 -1
  235. package/cli.js +2 -2
  236. package/execution-worker.js +1 -1
  237. package/package.json +2 -2
  238. package/chunks/chunk-56PVVXUG.js +0 -8
  239. package/chunks/chunk-AJ75BPTA.js +0 -31
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{effectiveSessionScope,multiSessionCompatibilityError,parseMessageRoutingConfig,parseSessionRotationConfig}from"./chunk-TDCBXYAI.js";import{UNSAFE_OBJECT_KEYS,getPlugin}from"./chunk-5KDLWYZV.js";import{CHANNEL_OUTPUT_MODE_FIELD,parseChannelOutputMode}from"./chunk-EL6TIJSV.js";import{loadSettings,saveSettings}from"./chunk-23543L6E.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import{isDeepStrictEqual}from"node:util";var ChannelSettingsError=class extends Error{constructor(code,message){super(message);this.code=code;this.name="ChannelSettingsError"}static{__name(this,"ChannelSettingsError")}};function revisionOf(channels,startupNames){return createHash("sha256").update(JSON.stringify({channels,startupNames})).digest("hex")}__name(revisionOf,"revisionOf");function applySecretUpdate(current,update){validateSecretUpdate(update);if(update.operation==="preserve")return current;if(update.operation==="clear")return void 0;if(typeof update.value!=="string"||update.value.length===0){throw invalidSecret("Secret replacements must be non-empty strings.")}return update.value}__name(applySecretUpdate,"applySecretUpdate");function invalidSecret(message){return new ChannelSettingsError("channel_settings_invalid_secret",message)}__name(invalidSecret,"invalidSecret");function invalidConfig(message){return new ChannelSettingsError("channel_settings_invalid_config",message)}__name(invalidConfig,"invalidConfig");function assertSafeChannelName(name){if(UNSAFE_OBJECT_KEYS.has(name)){throw new ChannelSettingsError("channel_settings_invalid_name",`Channel name ${JSON.stringify(name)} is not allowed.`)}}__name(assertSafeChannelName,"assertSafeChannelName");function assertUpsertChannelName(name){assertSafeChannelName(name);if(isAllStartupName(name)){throw new ChannelSettingsError("channel_settings_invalid_name",`Channel name ${JSON.stringify(name)} is reserved for startup selection.`)}}__name(assertUpsertChannelName,"assertUpsertChannelName");function isAllStartupName(name){return name.trim()==="all"}__name(isAllStartupName,"isAllStartupName");function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(isRecord,"isRecord");function isEnvironmentReference(value){return/^\$[A-Za-z_][A-Za-z0-9_]*$/.test(value)}__name(isEnvironmentReference,"isEnvironmentReference");function assertStringRecord(key,value,allowedKeys){if(!isRecord(value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}for(const[nestedKey,nestedValue]of Object.entries(value)){if(!allowedKeys.has(nestedKey)||typeof nestedValue!=="string"){throw invalidConfig(`Channel field "${key}.${nestedKey}" is invalid.`)}}}__name(assertStringRecord,"assertStringRecord");function assertSharedField(key,value,previous,channelType){if(key==="messageRoutes"||key==="defaultMessageRoute"){return true}if(key==="multiSession"){if(typeof value!=="boolean"){throw invalidConfig(`Channel field "${key}" must be a boolean.`)}return true}if(key==="sessionRotation"){try{parseSessionRotationConfig("settings",value)}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}return true}if(key==="groupSenderPolicy"||key==="allowedGroupUsers"){throw invalidConfig(`Channel field "${key}" moved to groups["*"].${key==="groupSenderPolicy"?"senders":"allowedUsers"}.`)}const enumValues={privatePolicy:new Set(["disabled","allowlist","pairing","open"]),senderPolicy:new Set(["allowlist","pairing","open"]),dmPolicy:new Set(["open","disabled"]),groupPolicy:new Set(["disabled","allowlist","pairing","open"]),sessionScope:new Set(["user","thread","chat_thread","single"]),dispatchMode:new Set(["steer","followup","collect"])};if(Object.hasOwn(enumValues,key)){if(typeof value!=="string"||!enumValues[key].has(value)){throw invalidConfig(`Channel field "${key}" has an invalid value.`)}return true}if(["model","cwd","approvalMode","instructions"].includes(key)){if(typeof value!=="string"){throw invalidConfig(`Channel field "${key}" must be a string.`)}return true}if(key==="allowedUsers"||key==="operators"){if(!Array.isArray(value)||value.some(item=>typeof item!=="string")){throw invalidConfig(`Channel field "${key}" must be a string array.`)}return true}if(key==="groups"){if(!isRecord(value)){if(containsUnsafeObjectKey(value)||!isDeepStrictEqual(previous,value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}return true}const previousGroups=isRecord(previous)?previous:{};for(const[groupId,groupConfig]of Object.entries(value)){if(UNSAFE_OBJECT_KEYS.has(groupId)||!isRecord(groupConfig)){throw invalidConfig(`Channel field "${key}.${groupId}" is invalid.`)}let previousGroup=isRecord(previousGroups[groupId])?previousGroups[groupId]:void 0;const foldsGroupKeyCase=channelType==="github"||channelType==="gitlab";if(previousGroup===void 0&&foldsGroupKeyCase){const normalizedId=groupId.toLowerCase();for(const[storedId,storedConfig]of Object.entries(previousGroups)){if(storedId.toLowerCase()===normalizedId&&isRecord(storedConfig)){previousGroup=storedConfig;break}}}const previousGroupRecord=previousGroup??{};for(const[nestedKey,nestedValue]of Object.entries(groupConfig)){const known=["requireMention","dispatchMode","groupHistoryLimit","senders","allowedUsers"].includes(nestedKey);const valid=nestedKey==="requireMention"&&typeof nestedValue==="boolean"||nestedKey==="dispatchMode"&&typeof nestedValue==="string"&&["collect","steer","followup"].includes(nestedValue)||nestedKey==="groupHistoryLimit"&&typeof nestedValue==="number"&&Number.isFinite(nestedValue)||nestedKey==="senders"&&typeof nestedValue==="string"&&["open","allowlist"].includes(nestedValue)||nestedKey==="allowedUsers"&&Array.isArray(nestedValue)&&nestedValue.every(item=>typeof item==="string");if(known&&!valid&&!(nestedKey!=="senders"&&Object.hasOwn(previousGroupRecord,nestedKey)&&isDeepStrictEqual(previousGroupRecord[nestedKey],nestedValue)&&!containsUnsafeObjectKey(nestedValue))){throw invalidConfig(`Channel field "${key}.${groupId}.${nestedKey}" is invalid.`)}if(!known){assertPreservedUnknownField(`${key}.${groupId}`,nestedKey,nestedValue,previousGroupRecord)}}}return true}if(key==="groupHistoryLimit"){if(typeof value!=="number"||!Number.isFinite(value)){throw invalidConfig(`Channel field "${key}" must be a number.`)}return true}if(key==="identity"){assertStringRecord(key,value,new Set(["id","displayName","description"]));return true}if(key==="memoryScope"){if(!isRecord(value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}for(const[nestedKey,nestedValue]of Object.entries(value)){const valid=nestedKey==="namespace"&&typeof nestedValue==="string"||nestedKey==="mode"&&nestedValue==="metadata-only";if(!valid){throw invalidConfig(`Channel field "${key}.${nestedKey}" is invalid.`)}}return true}return false}__name(assertSharedField,"assertSharedField");function containsUnsafeObjectKey(value){if(Array.isArray(value)){return value.some(item=>containsUnsafeObjectKey(item))}if(!isRecord(value))return false;return Object.entries(value).some(([key,nested])=>UNSAFE_OBJECT_KEYS.has(key)||containsUnsafeObjectKey(nested))}__name(containsUnsafeObjectKey,"containsUnsafeObjectKey");function assertDescriptorValue(field,value,path=field.key,previous){if(field.kind==="object"){if(isDeepStrictEqual(previous,value)&&!containsUnsafeObjectKey(value)){return}if(!isRecord(value)){throw invalidConfig(`Channel field "${path}" has an invalid value.`)}const previousRecord=isRecord(previous)?previous:{};const properties=new Map(field.properties.map(property=>[property.key,property]));for(const[key,nestedValue]of Object.entries(value)){const property=properties.get(key);if(!property){assertPreservedUnknownField(path,key,nestedValue,previousRecord);continue}assertDescriptorValue(property,nestedValue,`${path}.${key}`,Object.hasOwn(previousRecord,key)?previousRecord[key]:void 0)}assertRequiredFields(field.properties,value,path);return}const invalidEnvironment=typeof value==="string"&&isEnvironmentReference(value)&&!field.envResolvable;if(invalidEnvironment){throw invalidConfig(`Channel field "${path}" does not support environment references.`)}const valid=(field.kind==="string"||field.kind==="secret")&&typeof value==="string"&&value.length>0||field.kind==="boolean"&&typeof value==="boolean"||field.kind==="number"&&typeof value==="number"&&Number.isFinite(value)&&((field.exclusiveMinimum===void 0||value>field.exclusiveMinimum)&&(field.minimum===void 0||value>=field.minimum)&&(field.maximum===void 0||value<=field.maximum)||isDeepStrictEqual(previous,value))||field.kind==="enum"&&typeof value==="string"&&(field.options?.some(option=>option.value===value)===true||isDeepStrictEqual(previous,value))||field.kind==="string-list"&&Array.isArray(value)&&value.every(item=>typeof item==="string")||field.kind==="record"&&isRecord(value)&&Object.values(value).every(v=>typeof v==="string")&&!containsUnsafeObjectKey(value);if(!valid){throw invalidConfig(`Channel field "${path}" has an invalid value.`)}}__name(assertDescriptorValue,"assertDescriptorValue");function assertRequiredFields(fields,values,path){for(const field of fields){if(!field.required)continue;const value=Object.hasOwn(values,field.key)?values[field.key]:void 0;if(value===void 0||value===null||value===""){const fieldPath=path?`${path}.${field.key}`:field.key;throw invalidConfig(`Channel field "${fieldPath}" is required.`)}}}__name(assertRequiredFields,"assertRequiredFields");function assertPreservedUnknownField(path,key,value,previous){const fieldPath=path?`${path}.${key}`:key;if(UNSAFE_OBJECT_KEYS.has(key)){throw invalidConfig(`Channel field "${fieldPath}" is not manageable.`)}if(containsUnsafeObjectKey(value)){throw invalidConfig(`Channel field "${fieldPath}" cannot use a reserved key.`)}if(Object.hasOwn(previous,key)&&isDeepStrictEqual(previous[key],value)){return}throw invalidConfig(`Channel field "${fieldPath}" is not manageable.`)}__name(assertPreservedUnknownField,"assertPreservedUnknownField");function assertManagedConfig(config,previous,fields){const descriptorFields=new Map(fields.map(field=>[field.key,field]));for(const[key,value]of Object.entries(config)){if(key==="type")continue;const field=descriptorFields.get(key);if(field){assertDescriptorValue(field,value,field.key,Object.hasOwn(previous,key)?previous[key]:void 0);continue}if(assertSharedField(key,value,Object.hasOwn(previous,key)?previous[key]:void 0,config["type"])){continue}assertPreservedUnknownField(void 0,key,value,previous)}assertRequiredFields(fields,config)}__name(assertManagedConfig,"assertManagedConfig");function validateSecretUpdate(update){if(!isRecord(update)){throw invalidSecret("Secret updates must be objects.")}const operation=update["operation"];const keys=Object.keys(update).sort();const valid=(operation==="preserve"||operation==="clear")&&keys.length===1&&keys[0]==="operation"||operation==="replace"&&keys.length===2&&keys[0]==="operation"&&keys[1]==="value"&&typeof update["value"]==="string"&&update["value"].length>0;if(!valid){throw invalidSecret("Secret updates contain an invalid operation.")}}__name(validateSecretUpdate,"validateSecretUpdate");function assertValidChannelSecretUpdates(updates){if(!isRecord(updates)){throw invalidSecret("Secret updates must be objects.")}for(const[key,update]of Object.entries(updates)){if(UNSAFE_OBJECT_KEYS.has(key)){throw invalidSecret(`Secret update ${JSON.stringify(key)} is invalid.`)}validateSecretUpdate(update)}}__name(assertValidChannelSecretUpdates,"assertValidChannelSecretUpdates");function channelSettingsScope(workspaceCwd){const loaded=loadSettings(workspaceCwd,{skipLoadEnvironment:true});return loaded.workspaceSettingsActive?loaded.workspace:loaded.user}__name(channelSettingsScope,"channelSettingsScope");function channelRecordMap(value){const rawChannels=isRecord(value)?value:{};const channels={};for(const[name,config]of Object.entries(rawChannels)){if(UNSAFE_OBJECT_KEYS.has(name))continue;if(isRecord(config))channels[name]=config}return channels}__name(channelRecordMap,"channelRecordMap");function snapshotFrom(values){return{revision:revisionOf(values.channels,values.startupNames),channels:{...values.channels},startupNames:[...values.startupNames]}}__name(snapshotFrom,"snapshotFrom");function workspaceValues(workspaceCwd){const scope=channelSettingsScope(workspaceCwd);const settings=scope.settings;const startupNames=Array.isArray(settings.serve?.channels)?settings.serve.channels.filter(name=>typeof name==="string"):[];return{channels:channelRecordMap(settings.channels),storedChannels:channelRecordMap(scope.originalSettings.channels),startupNames}}__name(workspaceValues,"workspaceValues");var WorkspaceChannelSettingsStore=class{constructor(workspaceCwd){this.workspaceCwd=workspaceCwd}static{__name(this,"WorkspaceChannelSettingsStore")}snapshot(){return snapshotFrom(workspaceValues(this.workspaceCwd))}async upsert(name,options){assertUpsertChannelName(name);const secretUpdates=options.secrets===void 0?{}:options.secrets;assertValidChannelSecretUpdates(secretUpdates);const plugin=await getPlugin(options.config.type);if(!plugin?.management){throw new ChannelSettingsError("channel_settings_unmanageable",`Channel type "${options.config.type}" does not provide safe management metadata.`)}const secretKeys=new Set(plugin.management.fields.filter(field=>field.kind==="secret").map(field=>field.key));const envResolvableKeys=new Set(plugin.management.fields.filter(field=>field.envResolvable).map(field=>field.key));for(const key of Object.keys(secretUpdates)){if(!secretKeys.has(key)){throw invalidSecret(`Channel type "${options.config.type}" does not declare "${key}" as a secret.`)}}for(const key of secretKeys){if(Object.hasOwn(options.config,key)){throw invalidSecret(`Secret "${key}" must use an explicit preserve, replace, or clear operation.`)}}const{current,storedChannels}=this.assertRevision(options.expectedRevision);const storedPrevious=current.channels[name]??{};const hasPreviousOfType=storedPrevious["type"]===options.config.type;const previous=hasPreviousOfType?storedPrevious:{};const storedOnDisk=storedChannels[name]??{};const previousOnDisk=hasPreviousOfType?storedOnDisk:{};const nextConfig={...options.config};const storedReferences={};for(const key of secretKeys){const update=secretUpdates[key]??{operation:"preserve"};const value=applySecretUpdate(previous[key],update);if(value!==void 0)nextConfig[key]=value;if(update.operation==="preserve"&&previousOnDisk[key]!==void 0&&envResolvableKeys.has(key)){storedReferences[key]=previousOnDisk[key]}}for(const field of plugin.management.fields){const key=field.key;if(!field.envResolvable||secretKeys.has(key))continue;const onDisk=previousOnDisk[key];if(typeof onDisk!=="string"||!isEnvironmentReference(onDisk)){continue}if(nextConfig[key]!==previous[key])continue;storedReferences[key]=onDisk}try{parseChannelOutputMode(name,nextConfig["outputMode"],plugin.supportsOutputMode===true)}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}assertManagedConfig(nextConfig,previous,plugin.supportsOutputMode===true?[...plugin.management.fields,CHANNEL_OUTPUT_MODE_FIELD]:plugin.management.fields);const multiSessionError=multiSessionCompatibilityError(name,{multiSession:nextConfig["multiSession"]===true,sessionRotation:parseSessionRotationConfig(name,nextConfig["sessionRotation"]),sessionScope:effectiveSessionScope(nextConfig,nextConfig["multiSession"]===true,plugin),groupHistoryLimit:nextConfig["groupHistoryLimit"],groups:isRecord(nextConfig["groups"])?nextConfig["groups"]:{},webhooks:nextConfig["webhooks"]});if(multiSessionError)throw invalidConfig(multiSessionError);try{const routing=parseMessageRoutingConfig(name,nextConfig);if(routing.messageRoutes!==void 0)nextConfig["messageRoutes"]=routing.messageRoutes;if(routing.defaultMessageRoute!==void 0)nextConfig["defaultMessageRoute"]=routing.defaultMessageRoute}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}let crossFieldError;try{crossFieldError=plugin.management.validateConfig?.(nextConfig);if(crossFieldError instanceof Promise){void crossFieldError.catch(()=>{})}}catch(error){throw invalidConfig(`Channel validateConfig failed: ${error instanceof Error?error.message:String(error)}`)}if(crossFieldError!==void 0){throw invalidConfig(typeof crossFieldError==="string"?crossFieldError:"Channel validateConfig must return a string error message.")}const channels={...storedChannels,[name]:{...nextConfig,...storedReferences}};saveSettings(channelSettingsScope(this.workspaceCwd),{channels},["channels"],{throwOnWriteFailure:true});return this.snapshot()}async remove(name,options){assertSafeChannelName(name);const{current,storedChannels}=this.assertRevision(options.expectedRevision);const configured=Object.hasOwn(current.channels,name);if(!configured){if(!current.startupNames.includes(name))return current;saveSettings(channelSettingsScope(this.workspaceCwd),{serve:{channels:current.startupNames.filter(startupName=>startupName!==name)}},["serve","channels"],{throwOnWriteFailure:true});return this.snapshot()}const channels={...storedChannels};delete channels[name];const hasAllSentinel=current.startupNames.some(isAllStartupName);const startupNames=hasAllSentinel?Object.keys(channels).some(channelName=>!isAllStartupName(channelName))?["all"]:[]:current.startupNames.filter(startupName=>startupName!==name);saveSettings(channelSettingsScope(this.workspaceCwd),{channels,serve:{channels:startupNames}},["channels"],{throwOnWriteFailure:true});return this.snapshot()}async setStartupNames(names,options){for(const name of names){assertSafeChannelName(name)}this.assertRevision(options.expectedRevision);saveSettings(channelSettingsScope(this.workspaceCwd),{serve:{channels:[...names]}},["serve","channels"],{throwOnWriteFailure:true});return this.snapshot()}assertRevision(expectedRevision){const values=workspaceValues(this.workspaceCwd);const current=snapshotFrom(values);if(current.revision!==expectedRevision){throw new ChannelSettingsError("channel_settings_conflict","Channel settings changed; reload before trying again.")}return{current,storedChannels:values.storedChannels}}};export{ChannelSettingsError,assertValidChannelSecretUpdates,WorkspaceChannelSettingsStore};
3
+ import{effectiveSessionScope,multiSessionCompatibilityError,parseMessageRoutingConfig,parseSessionRotationConfig}from"./chunk-TDCBXYAI.js";import{UNSAFE_OBJECT_KEYS,getPlugin}from"./chunk-5KDLWYZV.js";import{CHANNEL_OUTPUT_MODE_FIELD,parseChannelOutputMode}from"./chunk-EL6TIJSV.js";import{loadSettings,saveSettings}from"./chunk-4RJ2RRGZ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";import{isDeepStrictEqual}from"node:util";var ChannelSettingsError=class extends Error{constructor(code,message){super(message);this.code=code;this.name="ChannelSettingsError"}static{__name(this,"ChannelSettingsError")}};function revisionOf(channels,startupNames){return createHash("sha256").update(JSON.stringify({channels,startupNames})).digest("hex")}__name(revisionOf,"revisionOf");function applySecretUpdate(current,update){validateSecretUpdate(update);if(update.operation==="preserve")return current;if(update.operation==="clear")return void 0;if(typeof update.value!=="string"||update.value.length===0){throw invalidSecret("Secret replacements must be non-empty strings.")}return update.value}__name(applySecretUpdate,"applySecretUpdate");function invalidSecret(message){return new ChannelSettingsError("channel_settings_invalid_secret",message)}__name(invalidSecret,"invalidSecret");function invalidConfig(message){return new ChannelSettingsError("channel_settings_invalid_config",message)}__name(invalidConfig,"invalidConfig");function assertSafeChannelName(name){if(UNSAFE_OBJECT_KEYS.has(name)){throw new ChannelSettingsError("channel_settings_invalid_name",`Channel name ${JSON.stringify(name)} is not allowed.`)}}__name(assertSafeChannelName,"assertSafeChannelName");function assertUpsertChannelName(name){assertSafeChannelName(name);if(isAllStartupName(name)){throw new ChannelSettingsError("channel_settings_invalid_name",`Channel name ${JSON.stringify(name)} is reserved for startup selection.`)}}__name(assertUpsertChannelName,"assertUpsertChannelName");function isAllStartupName(name){return name.trim()==="all"}__name(isAllStartupName,"isAllStartupName");function isRecord(value){return value!==null&&typeof value==="object"&&!Array.isArray(value)}__name(isRecord,"isRecord");function isEnvironmentReference(value){return/^\$[A-Za-z_][A-Za-z0-9_]*$/.test(value)}__name(isEnvironmentReference,"isEnvironmentReference");function assertStringRecord(key,value,allowedKeys){if(!isRecord(value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}for(const[nestedKey,nestedValue]of Object.entries(value)){if(!allowedKeys.has(nestedKey)||typeof nestedValue!=="string"){throw invalidConfig(`Channel field "${key}.${nestedKey}" is invalid.`)}}}__name(assertStringRecord,"assertStringRecord");function assertSharedField(key,value,previous,channelType){if(key==="messageRoutes"||key==="defaultMessageRoute"){return true}if(key==="multiSession"){if(typeof value!=="boolean"){throw invalidConfig(`Channel field "${key}" must be a boolean.`)}return true}if(key==="sessionRotation"){try{parseSessionRotationConfig("settings",value)}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}return true}if(key==="groupSenderPolicy"||key==="allowedGroupUsers"){throw invalidConfig(`Channel field "${key}" moved to groups["*"].${key==="groupSenderPolicy"?"senders":"allowedUsers"}.`)}const enumValues={privatePolicy:new Set(["disabled","allowlist","pairing","open"]),senderPolicy:new Set(["allowlist","pairing","open"]),dmPolicy:new Set(["open","disabled"]),groupPolicy:new Set(["disabled","allowlist","pairing","open"]),sessionScope:new Set(["user","thread","chat_thread","single"]),dispatchMode:new Set(["steer","followup","collect"])};if(Object.hasOwn(enumValues,key)){if(typeof value!=="string"||!enumValues[key].has(value)){throw invalidConfig(`Channel field "${key}" has an invalid value.`)}return true}if(["model","cwd","approvalMode","instructions"].includes(key)){if(typeof value!=="string"){throw invalidConfig(`Channel field "${key}" must be a string.`)}return true}if(key==="allowedUsers"||key==="operators"){if(!Array.isArray(value)||value.some(item=>typeof item!=="string")){throw invalidConfig(`Channel field "${key}" must be a string array.`)}return true}if(key==="groups"){if(!isRecord(value)){if(containsUnsafeObjectKey(value)||!isDeepStrictEqual(previous,value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}return true}const previousGroups=isRecord(previous)?previous:{};for(const[groupId,groupConfig]of Object.entries(value)){if(UNSAFE_OBJECT_KEYS.has(groupId)||!isRecord(groupConfig)){throw invalidConfig(`Channel field "${key}.${groupId}" is invalid.`)}let previousGroup=isRecord(previousGroups[groupId])?previousGroups[groupId]:void 0;const foldsGroupKeyCase=channelType==="github"||channelType==="gitlab";if(previousGroup===void 0&&foldsGroupKeyCase){const normalizedId=groupId.toLowerCase();for(const[storedId,storedConfig]of Object.entries(previousGroups)){if(storedId.toLowerCase()===normalizedId&&isRecord(storedConfig)){previousGroup=storedConfig;break}}}const previousGroupRecord=previousGroup??{};for(const[nestedKey,nestedValue]of Object.entries(groupConfig)){const known=["requireMention","dispatchMode","groupHistoryLimit","senders","allowedUsers"].includes(nestedKey);const valid=nestedKey==="requireMention"&&typeof nestedValue==="boolean"||nestedKey==="dispatchMode"&&typeof nestedValue==="string"&&["collect","steer","followup"].includes(nestedValue)||nestedKey==="groupHistoryLimit"&&typeof nestedValue==="number"&&Number.isFinite(nestedValue)||nestedKey==="senders"&&typeof nestedValue==="string"&&["open","allowlist"].includes(nestedValue)||nestedKey==="allowedUsers"&&Array.isArray(nestedValue)&&nestedValue.every(item=>typeof item==="string");if(known&&!valid&&!(nestedKey!=="senders"&&Object.hasOwn(previousGroupRecord,nestedKey)&&isDeepStrictEqual(previousGroupRecord[nestedKey],nestedValue)&&!containsUnsafeObjectKey(nestedValue))){throw invalidConfig(`Channel field "${key}.${groupId}.${nestedKey}" is invalid.`)}if(!known){assertPreservedUnknownField(`${key}.${groupId}`,nestedKey,nestedValue,previousGroupRecord)}}}return true}if(key==="groupHistoryLimit"){if(typeof value!=="number"||!Number.isFinite(value)){throw invalidConfig(`Channel field "${key}" must be a number.`)}return true}if(key==="identity"){assertStringRecord(key,value,new Set(["id","displayName","description"]));return true}if(key==="memoryScope"){if(!isRecord(value)){throw invalidConfig(`Channel field "${key}" must be an object.`)}for(const[nestedKey,nestedValue]of Object.entries(value)){const valid=nestedKey==="namespace"&&typeof nestedValue==="string"||nestedKey==="mode"&&nestedValue==="metadata-only";if(!valid){throw invalidConfig(`Channel field "${key}.${nestedKey}" is invalid.`)}}return true}return false}__name(assertSharedField,"assertSharedField");function containsUnsafeObjectKey(value){if(Array.isArray(value)){return value.some(item=>containsUnsafeObjectKey(item))}if(!isRecord(value))return false;return Object.entries(value).some(([key,nested])=>UNSAFE_OBJECT_KEYS.has(key)||containsUnsafeObjectKey(nested))}__name(containsUnsafeObjectKey,"containsUnsafeObjectKey");function assertDescriptorValue(field,value,path=field.key,previous){if(field.kind==="object"){if(isDeepStrictEqual(previous,value)&&!containsUnsafeObjectKey(value)){return}if(!isRecord(value)){throw invalidConfig(`Channel field "${path}" has an invalid value.`)}const previousRecord=isRecord(previous)?previous:{};const properties=new Map(field.properties.map(property=>[property.key,property]));for(const[key,nestedValue]of Object.entries(value)){const property=properties.get(key);if(!property){assertPreservedUnknownField(path,key,nestedValue,previousRecord);continue}assertDescriptorValue(property,nestedValue,`${path}.${key}`,Object.hasOwn(previousRecord,key)?previousRecord[key]:void 0)}assertRequiredFields(field.properties,value,path);return}const invalidEnvironment=typeof value==="string"&&isEnvironmentReference(value)&&!field.envResolvable;if(invalidEnvironment){throw invalidConfig(`Channel field "${path}" does not support environment references.`)}const valid=(field.kind==="string"||field.kind==="secret")&&typeof value==="string"&&value.length>0||field.kind==="boolean"&&typeof value==="boolean"||field.kind==="number"&&typeof value==="number"&&Number.isFinite(value)&&((field.exclusiveMinimum===void 0||value>field.exclusiveMinimum)&&(field.minimum===void 0||value>=field.minimum)&&(field.maximum===void 0||value<=field.maximum)||isDeepStrictEqual(previous,value))||field.kind==="enum"&&typeof value==="string"&&(field.options?.some(option=>option.value===value)===true||isDeepStrictEqual(previous,value))||field.kind==="string-list"&&Array.isArray(value)&&value.every(item=>typeof item==="string")||field.kind==="record"&&isRecord(value)&&Object.values(value).every(v=>typeof v==="string")&&!containsUnsafeObjectKey(value);if(!valid){throw invalidConfig(`Channel field "${path}" has an invalid value.`)}}__name(assertDescriptorValue,"assertDescriptorValue");function assertRequiredFields(fields,values,path){for(const field of fields){if(!field.required)continue;const value=Object.hasOwn(values,field.key)?values[field.key]:void 0;if(value===void 0||value===null||value===""){const fieldPath=path?`${path}.${field.key}`:field.key;throw invalidConfig(`Channel field "${fieldPath}" is required.`)}}}__name(assertRequiredFields,"assertRequiredFields");function assertPreservedUnknownField(path,key,value,previous){const fieldPath=path?`${path}.${key}`:key;if(UNSAFE_OBJECT_KEYS.has(key)){throw invalidConfig(`Channel field "${fieldPath}" is not manageable.`)}if(containsUnsafeObjectKey(value)){throw invalidConfig(`Channel field "${fieldPath}" cannot use a reserved key.`)}if(Object.hasOwn(previous,key)&&isDeepStrictEqual(previous[key],value)){return}throw invalidConfig(`Channel field "${fieldPath}" is not manageable.`)}__name(assertPreservedUnknownField,"assertPreservedUnknownField");function assertManagedConfig(config,previous,fields){const descriptorFields=new Map(fields.map(field=>[field.key,field]));for(const[key,value]of Object.entries(config)){if(key==="type")continue;const field=descriptorFields.get(key);if(field){assertDescriptorValue(field,value,field.key,Object.hasOwn(previous,key)?previous[key]:void 0);continue}if(assertSharedField(key,value,Object.hasOwn(previous,key)?previous[key]:void 0,config["type"])){continue}assertPreservedUnknownField(void 0,key,value,previous)}assertRequiredFields(fields,config)}__name(assertManagedConfig,"assertManagedConfig");function validateSecretUpdate(update){if(!isRecord(update)){throw invalidSecret("Secret updates must be objects.")}const operation=update["operation"];const keys=Object.keys(update).sort();const valid=(operation==="preserve"||operation==="clear")&&keys.length===1&&keys[0]==="operation"||operation==="replace"&&keys.length===2&&keys[0]==="operation"&&keys[1]==="value"&&typeof update["value"]==="string"&&update["value"].length>0;if(!valid){throw invalidSecret("Secret updates contain an invalid operation.")}}__name(validateSecretUpdate,"validateSecretUpdate");function assertValidChannelSecretUpdates(updates){if(!isRecord(updates)){throw invalidSecret("Secret updates must be objects.")}for(const[key,update]of Object.entries(updates)){if(UNSAFE_OBJECT_KEYS.has(key)){throw invalidSecret(`Secret update ${JSON.stringify(key)} is invalid.`)}validateSecretUpdate(update)}}__name(assertValidChannelSecretUpdates,"assertValidChannelSecretUpdates");function channelSettingsScope(workspaceCwd){const loaded=loadSettings(workspaceCwd,{skipLoadEnvironment:true});return loaded.workspaceSettingsActive?loaded.workspace:loaded.user}__name(channelSettingsScope,"channelSettingsScope");function channelRecordMap(value){const rawChannels=isRecord(value)?value:{};const channels={};for(const[name,config]of Object.entries(rawChannels)){if(UNSAFE_OBJECT_KEYS.has(name))continue;if(isRecord(config))channels[name]=config}return channels}__name(channelRecordMap,"channelRecordMap");function snapshotFrom(values){return{revision:revisionOf(values.channels,values.startupNames),channels:{...values.channels},startupNames:[...values.startupNames]}}__name(snapshotFrom,"snapshotFrom");function workspaceValues(workspaceCwd){const scope=channelSettingsScope(workspaceCwd);const settings=scope.settings;const startupNames=Array.isArray(settings.serve?.channels)?settings.serve.channels.filter(name=>typeof name==="string"):[];return{channels:channelRecordMap(settings.channels),storedChannels:channelRecordMap(scope.originalSettings.channels),startupNames}}__name(workspaceValues,"workspaceValues");var WorkspaceChannelSettingsStore=class{constructor(workspaceCwd){this.workspaceCwd=workspaceCwd}static{__name(this,"WorkspaceChannelSettingsStore")}snapshot(){return snapshotFrom(workspaceValues(this.workspaceCwd))}async upsert(name,options){assertUpsertChannelName(name);const secretUpdates=options.secrets===void 0?{}:options.secrets;assertValidChannelSecretUpdates(secretUpdates);const plugin=await getPlugin(options.config.type);if(!plugin?.management){throw new ChannelSettingsError("channel_settings_unmanageable",`Channel type "${options.config.type}" does not provide safe management metadata.`)}const secretKeys=new Set(plugin.management.fields.filter(field=>field.kind==="secret").map(field=>field.key));const envResolvableKeys=new Set(plugin.management.fields.filter(field=>field.envResolvable).map(field=>field.key));for(const key of Object.keys(secretUpdates)){if(!secretKeys.has(key)){throw invalidSecret(`Channel type "${options.config.type}" does not declare "${key}" as a secret.`)}}for(const key of secretKeys){if(Object.hasOwn(options.config,key)){throw invalidSecret(`Secret "${key}" must use an explicit preserve, replace, or clear operation.`)}}const{current,storedChannels}=this.assertRevision(options.expectedRevision);const storedPrevious=current.channels[name]??{};const hasPreviousOfType=storedPrevious["type"]===options.config.type;const previous=hasPreviousOfType?storedPrevious:{};const storedOnDisk=storedChannels[name]??{};const previousOnDisk=hasPreviousOfType?storedOnDisk:{};const nextConfig={...options.config};const storedReferences={};for(const key of secretKeys){const update=secretUpdates[key]??{operation:"preserve"};const value=applySecretUpdate(previous[key],update);if(value!==void 0)nextConfig[key]=value;if(update.operation==="preserve"&&previousOnDisk[key]!==void 0&&envResolvableKeys.has(key)){storedReferences[key]=previousOnDisk[key]}}for(const field of plugin.management.fields){const key=field.key;if(!field.envResolvable||secretKeys.has(key))continue;const onDisk=previousOnDisk[key];if(typeof onDisk!=="string"||!isEnvironmentReference(onDisk)){continue}if(nextConfig[key]!==previous[key])continue;storedReferences[key]=onDisk}try{parseChannelOutputMode(name,nextConfig["outputMode"],plugin.supportsOutputMode===true)}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}assertManagedConfig(nextConfig,previous,plugin.supportsOutputMode===true?[...plugin.management.fields,CHANNEL_OUTPUT_MODE_FIELD]:plugin.management.fields);const multiSessionError=multiSessionCompatibilityError(name,{multiSession:nextConfig["multiSession"]===true,sessionRotation:parseSessionRotationConfig(name,nextConfig["sessionRotation"]),sessionScope:effectiveSessionScope(nextConfig,nextConfig["multiSession"]===true,plugin),groupHistoryLimit:nextConfig["groupHistoryLimit"],groups:isRecord(nextConfig["groups"])?nextConfig["groups"]:{},webhooks:nextConfig["webhooks"]});if(multiSessionError)throw invalidConfig(multiSessionError);try{const routing=parseMessageRoutingConfig(name,nextConfig);if(routing.messageRoutes!==void 0)nextConfig["messageRoutes"]=routing.messageRoutes;if(routing.defaultMessageRoute!==void 0)nextConfig["defaultMessageRoute"]=routing.defaultMessageRoute}catch(error){throw invalidConfig(error instanceof Error?error.message:String(error))}let crossFieldError;try{crossFieldError=plugin.management.validateConfig?.(nextConfig);if(crossFieldError instanceof Promise){void crossFieldError.catch(()=>{})}}catch(error){throw invalidConfig(`Channel validateConfig failed: ${error instanceof Error?error.message:String(error)}`)}if(crossFieldError!==void 0){throw invalidConfig(typeof crossFieldError==="string"?crossFieldError:"Channel validateConfig must return a string error message.")}const channels={...storedChannels,[name]:{...nextConfig,...storedReferences}};saveSettings(channelSettingsScope(this.workspaceCwd),{channels},["channels"],{throwOnWriteFailure:true});return this.snapshot()}async remove(name,options){assertSafeChannelName(name);const{current,storedChannels}=this.assertRevision(options.expectedRevision);const configured=Object.hasOwn(current.channels,name);if(!configured){if(!current.startupNames.includes(name))return current;saveSettings(channelSettingsScope(this.workspaceCwd),{serve:{channels:current.startupNames.filter(startupName=>startupName!==name)}},["serve","channels"],{throwOnWriteFailure:true});return this.snapshot()}const channels={...storedChannels};delete channels[name];const hasAllSentinel=current.startupNames.some(isAllStartupName);const startupNames=hasAllSentinel?Object.keys(channels).some(channelName=>!isAllStartupName(channelName))?["all"]:[]:current.startupNames.filter(startupName=>startupName!==name);saveSettings(channelSettingsScope(this.workspaceCwd),{channels,serve:{channels:startupNames}},["channels"],{throwOnWriteFailure:true});return this.snapshot()}async setStartupNames(names,options){for(const name of names){assertSafeChannelName(name)}this.assertRevision(options.expectedRevision);saveSettings(channelSettingsScope(this.workspaceCwd),{serve:{channels:[...names]}},["serve","channels"],{throwOnWriteFailure:true});return this.snapshot()}assertRevision(expectedRevision){const values=workspaceValues(this.workspaceCwd);const current=snapshotFrom(values);if(current.revision!==expectedRevision){throw new ChannelSettingsError("channel_settings_conflict","Channel settings changed; reload before trying again.")}return{current,storedChannels:values.storedChannels}}};export{ChannelSettingsError,assertValidChannelSecretUpdates,WorkspaceChannelSettingsStore};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{encodeTextFileContentAsync}from"./chunk-PFKTTUGS.js";import{assertShellSandboxCwd}from"./chunk-IC42HQCH.js";import{executeSandbox}from"./chunk-OV2J3OED.js";import{sandboxAsset}from"./chunk-NCBA52SB.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{statSync}from"node:fs";function getSandboxFileVersion(filePath){try{const stats=statSync(filePath,{bigint:true});if(!stats.isFile()){throw Object.assign(new Error("File tools require a regular file."),{code:stats.isDirectory()?"EISDIR":"EINVAL"})}return Object.freeze({dev:stats.dev.toString(),ino:stats.ino.toString(),size:stats.size.toString(),mtimeNs:stats.mtimeNs.toString(),ctimeNs:stats.ctimeNs.toString()})}catch(error){if(error.code==="ENOENT")return null;throw error}}__name(getSandboxFileVersion,"getSandboxFileVersion");init_esbuild_shims();init_esbuild_shims();var MAX_FILE_HEADER_BYTES=16*1024;function encodeSandboxWriteRequest(request){const header=Buffer.from(JSON.stringify({operation:request.operation,destination:request.destination,expected:request.expected,contentLength:request.content.length})+"\n");if(header.length>MAX_FILE_HEADER_BYTES)throw new Error("File worker header exceeds 16 KiB.");return Buffer.concat([header,request.content])}__name(encodeSandboxWriteRequest,"encodeSandboxWriteRequest");async function writeSandboxFile(policy,request,signal){signal.throwIfAborted();if(policy.filesystem==="read-only"){throw Object.assign(new Error("File writes are disabled by the read-only sandbox policy."),{code:"EROFS"})}const stdin=encodeSandboxWriteRequest(request);let reply="";let diagnostics="";const appendBounded=__name((current,chunk)=>(current+chunk).slice(-MAX_FILE_HEADER_BYTES),"appendBounded");const handle=await executeSandbox(policy,{executable:getJsInterpreterCommand(import.meta.url).command,args:[sandboxAsset("file-worker")],cwd:policy.workspace,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8"},stdin},event=>{if(event.type!=="data"||typeof event.chunk!=="string")return;if(event.stream==="stdout")reply=appendBounded(reply,event.chunk);else if(event.stream==="stderr")diagnostics=appendBounded(diagnostics,event.chunk)},signal,false,{},{streamStdout:true});const result=await handle.result;if(result.sandboxStatus.state!=="confirmed"||result.error||result.aborted){const detail=[result.error?.message,diagnostics||result.output].filter(Boolean).join("\n");throw new Error(`Sandbox file write failed (${result.sandboxStatus.state}): ${detail}`)}let parsedReply;try{parsedReply=JSON.parse(reply.trim())}catch{if(result.sandboxStatus.exitCode===0)throw new Error("Invalid sandbox file worker reply.");throw new Error(`Sandbox file worker exited ${result.sandboxStatus.exitCode}: ${diagnostics||result.output||reply||"invalid reply"}`)}if(result.sandboxStatus.exitCode===0&&parsedReply["ok"]===true)return;if(parsedReply["ok"]===false&&typeof parsedReply["error"]==="string"){throw Object.assign(new Error(parsedReply["error"]),{...typeof parsedReply["code"]==="string"?{code:parsedReply["code"]}:{}})}throw new Error("Invalid sandbox file worker reply.")}__name(writeSandboxFile,"writeSandboxFile");function captureRuntimeFileVersion(config,filePath){if(!config.getShellExecutionSandbox?.())return void 0;return getSandboxFileVersion(filePath)}__name(captureRuntimeFileVersion,"captureRuntimeFileVersion");async function writeRuntimeFile(config,params,expected,signal){const policy=config.getShellExecutionSandbox?.();if(!policy){await config.getFileSystemService().writeTextFile(params);return}signal.throwIfAborted();if(expected===void 0)throw new Error("Missing sandbox file version.");assertShellSandboxCwd(policy,config.getTargetDir());const content=await encodeTextFileContentAsync(params.path,params.content,params._meta);await writeSandboxFile(policy,{operation:"write",destination:params.path,content,expected},signal)}__name(writeRuntimeFile,"writeRuntimeFile");export{captureRuntimeFileVersion,writeRuntimeFile};
3
+ import{encodeTextFileContentAsync}from"./chunk-ZUWLTGSR.js";import{assertShellSandboxCwd}from"./chunk-IC42HQCH.js";import{executeSandbox}from"./chunk-OV2J3OED.js";import{sandboxAsset}from"./chunk-NCBA52SB.js";import{getJsInterpreterCommand}from"./chunk-WGNF7FPC.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();import{statSync}from"node:fs";function getSandboxFileVersion(filePath){try{const stats=statSync(filePath,{bigint:true});if(!stats.isFile()){throw Object.assign(new Error("File tools require a regular file."),{code:stats.isDirectory()?"EISDIR":"EINVAL"})}return Object.freeze({dev:stats.dev.toString(),ino:stats.ino.toString(),size:stats.size.toString(),mtimeNs:stats.mtimeNs.toString(),ctimeNs:stats.ctimeNs.toString()})}catch(error){if(error.code==="ENOENT")return null;throw error}}__name(getSandboxFileVersion,"getSandboxFileVersion");init_esbuild_shims();init_esbuild_shims();var MAX_FILE_HEADER_BYTES=16*1024;function encodeSandboxWriteRequest(request){const header=Buffer.from(JSON.stringify({operation:request.operation,destination:request.destination,expected:request.expected,contentLength:request.content.length})+"\n");if(header.length>MAX_FILE_HEADER_BYTES)throw new Error("File worker header exceeds 16 KiB.");return Buffer.concat([header,request.content])}__name(encodeSandboxWriteRequest,"encodeSandboxWriteRequest");async function writeSandboxFile(policy,request,signal){signal.throwIfAborted();if(policy.filesystem==="read-only"){throw Object.assign(new Error("File writes are disabled by the read-only sandbox policy."),{code:"EROFS"})}const stdin=encodeSandboxWriteRequest(request);let reply="";let diagnostics="";const appendBounded=__name((current,chunk)=>(current+chunk).slice(-MAX_FILE_HEADER_BYTES),"appendBounded");const handle=await executeSandbox(policy,{executable:getJsInterpreterCommand(import.meta.url).command,args:[sandboxAsset("file-worker")],cwd:policy.workspace,env:{PATH:"/usr/bin:/bin",LANG:"C.UTF-8"},stdin},event=>{if(event.type!=="data"||typeof event.chunk!=="string")return;if(event.stream==="stdout")reply=appendBounded(reply,event.chunk);else if(event.stream==="stderr")diagnostics=appendBounded(diagnostics,event.chunk)},signal,false,{},{streamStdout:true});const result=await handle.result;if(result.sandboxStatus.state!=="confirmed"||result.error||result.aborted){const detail=[result.error?.message,diagnostics||result.output].filter(Boolean).join("\n");throw new Error(`Sandbox file write failed (${result.sandboxStatus.state}): ${detail}`)}let parsedReply;try{parsedReply=JSON.parse(reply.trim())}catch{if(result.sandboxStatus.exitCode===0)throw new Error("Invalid sandbox file worker reply.");throw new Error(`Sandbox file worker exited ${result.sandboxStatus.exitCode}: ${diagnostics||result.output||reply||"invalid reply"}`)}if(result.sandboxStatus.exitCode===0&&parsedReply["ok"]===true)return;if(parsedReply["ok"]===false&&typeof parsedReply["error"]==="string"){throw Object.assign(new Error(parsedReply["error"]),{...typeof parsedReply["code"]==="string"?{code:parsedReply["code"]}:{}})}throw new Error("Invalid sandbox file worker reply.")}__name(writeSandboxFile,"writeSandboxFile");function captureRuntimeFileVersion(config,filePath){if(!config.getShellExecutionSandbox?.())return void 0;return getSandboxFileVersion(filePath)}__name(captureRuntimeFileVersion,"captureRuntimeFileVersion");async function writeRuntimeFile(config,params,expected,signal){const policy=config.getShellExecutionSandbox?.();if(!policy){await config.getFileSystemService().writeTextFile(params);return}signal.throwIfAborted();if(expected===void 0)throw new Error("Missing sandbox file version.");assertShellSandboxCwd(policy,config.getTargetDir());const content=await encodeTextFileContentAsync(params.path,params.content,params._meta);await writeSandboxFile(policy,{operation:"write",destination:params.path,content,expected},signal)}__name(writeRuntimeFile,"writeRuntimeFile");export{captureRuntimeFileVersion,writeRuntimeFile};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -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-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.
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-ZUWLTGSR.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-SINRWOVD.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{BaseJsonOutputAdapter}from"./chunk-G35E5UB3.js";import{observeHeadlessJsonToolResultWire}from"./chunk-SOCXRMZM.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonOutputAdapter=class extends BaseJsonOutputAdapter{static{__name(this,"JsonOutputAdapter")}messages=[];attemptMessageCheckpoint=0;lastAssistantMessageAtAttemptStart=null;constructor(config){super(config)}emitMessageImpl(message){this.messages.push(message);if(typeof message==="object"&&message!==null&&"type"in message&&message.type==="assistant"){this.updateLastAssistantMessage(message)}}shouldEmitStreamEvents(){return false}startAssistantMessage(){this.attemptMessageCheckpoint=this.messages.length;this.lastAssistantMessageAtAttemptStart=this.lastAssistantMessage;super.startAssistantMessage()}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant"||!message.message.content.some(block=>block.type==="tool_use"&&discardedIds.has(block.id)));this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.messages.findLast(message=>message.type==="assistant")??this.lastAssistantMessageAtAttemptStart}}else{const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant");this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.lastAssistantMessageAtAttemptStart}super.restartAttempt(preserveText,discardedToolCalls)}finalizeAssistantMessage(){return this.finalizeAssistantMessageInternal(this.mainAgentMessageState,null)}emitResult(options){const resultMessage=this.buildResultMessage(options,this.lastAssistantMessage);this.messages.push(resultMessage);if(this.config.getOutputFormat()==="text"){if(resultMessage.is_error){process.stderr.write(`${resultMessage.error?.message||""}
3
+ import{BaseJsonOutputAdapter}from"./chunk-JS6VAGRQ.js";import{observeHeadlessJsonToolResultWire}from"./chunk-OZL4ZMGQ.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var JsonOutputAdapter=class extends BaseJsonOutputAdapter{static{__name(this,"JsonOutputAdapter")}messages=[];attemptMessageCheckpoint=0;lastAssistantMessageAtAttemptStart=null;constructor(config){super(config)}emitMessageImpl(message){this.messages.push(message);if(typeof message==="object"&&message!==null&&"type"in message&&message.type==="assistant"){this.updateLastAssistantMessage(message)}}shouldEmitStreamEvents(){return false}startAssistantMessage(){this.attemptMessageCheckpoint=this.messages.length;this.lastAssistantMessageAtAttemptStart=this.lastAssistantMessage;super.startAssistantMessage()}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant"||!message.message.content.some(block=>block.type==="tool_use"&&discardedIds.has(block.id)));this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.messages.findLast(message=>message.type==="assistant")??this.lastAssistantMessageAtAttemptStart}}else{const retained=this.messages.slice(this.attemptMessageCheckpoint).filter(message=>message.type!=="assistant");this.messages.splice(this.attemptMessageCheckpoint,this.messages.length-this.attemptMessageCheckpoint,...retained);this.lastAssistantMessage=this.lastAssistantMessageAtAttemptStart}super.restartAttempt(preserveText,discardedToolCalls)}finalizeAssistantMessage(){return this.finalizeAssistantMessageInternal(this.mainAgentMessageState,null)}emitResult(options){const resultMessage=this.buildResultMessage(options,this.lastAssistantMessage);this.messages.push(resultMessage);if(this.config.getOutputFormat()==="text"){if(resultMessage.is_error){process.stderr.write(`${resultMessage.error?.message||""}
4
4
  `)}else{process.stdout.write(`${resultMessage.result}
5
5
  `)}}else{const json=JSON.stringify(this.messages);const frame=`${json}
6
6
  `;observeHeadlessJsonToolResultWire(this.messages,frame);process.stdout.write(frame)}}emitMessage(message){this.messages.push(message)}};export{JsonOutputAdapter};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{require_jsx_runtime}from"./chunk-REPFZQ7R.js";import{Box_default,Text}from"./chunk-YIJNS5IJ.js";import{require_react}from"./chunk-5QKDV4CD.js";import{themeManager}from"./chunk-GXNGLDUN.js";import{stringWidth,toCodePoints}from"./chunk-64CA3W6G.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_react2=__toESM(require_react(),1);init_esbuild_shims();var theme={get text(){return themeManager.getSemanticColors().text},get background(){return themeManager.getSemanticColors().background},get border(){return themeManager.getSemanticColors().border},get ui(){return themeManager.getSemanticColors().ui},get status(){return themeManager.getSemanticColors().status}};init_esbuild_shims();var import_react=__toESM(require_react(),1);var import_jsx_runtime=__toESM(require_jsx_runtime(),1);var OverflowStateContext=(0,import_react.createContext)(void 0);var OverflowActionsContext=(0,import_react.createContext)(void 0);var useOverflowState=__name(()=>(0,import_react.useContext)(OverflowStateContext),"useOverflowState");var useOverflowActions=__name(()=>(0,import_react.useContext)(OverflowActionsContext),"useOverflowActions");var OverflowProvider=__name(({children})=>{const[overflowingIds,setOverflowingIds]=(0,import_react.useState)(new Set);const addOverflowingId=(0,import_react.useCallback)(id=>{setOverflowingIds(prevIds=>{if(prevIds.has(id)){return prevIds}const newIds=new Set(prevIds);newIds.add(id);return newIds})},[]);const removeOverflowingId=(0,import_react.useCallback)(id=>{setOverflowingIds(prevIds=>{if(!prevIds.has(id)){return prevIds}const newIds=new Set(prevIds);newIds.delete(id);return newIds})},[]);const stateValue=(0,import_react.useMemo)(()=>({overflowingIds}),[overflowingIds]);const actionsValue=(0,import_react.useMemo)(()=>({addOverflowingId,removeOverflowingId}),[addOverflowingId,removeOverflowingId]);return(0,import_jsx_runtime.jsx)(OverflowStateContext.Provider,{value:stateValue,children:(0,import_jsx_runtime.jsx)(OverflowActionsContext.Provider,{value:actionsValue,children})})},"OverflowProvider");var import_jsx_runtime2=__toESM(require_jsx_runtime(),1);var enableDebugLog=false;var debugLogger=createDebugLogger("MAX_SIZED_BOX");var MINIMUM_MAX_HEIGHT=2;function setMaxSizedBoxDebugging(value){enableDebugLog=value}__name(setMaxSizedBoxDebugging,"setMaxSizedBoxDebugging");function debugReportError(message,element){if(!enableDebugLog)return;if(!import_react2.default.isValidElement(element)){debugLogger.error(message,`Invalid element: '${String(element)}' typeof=${typeof element}`);return}let sourceMessage="<Unknown file>";try{const elementWithSource=element;const fileName=elementWithSource._source?.fileName;const lineNumber=elementWithSource._source?.lineNumber;sourceMessage=fileName?`${fileName}:${lineNumber}`:"<Unknown file>"}catch(error){debugLogger.error("Error while trying to get file name:",error)}debugLogger.error(message,`${String(element.type)}. Source: ${sourceMessage}`)}__name(debugReportError,"debugReportError");var MaxSizedBox=__name(({children,maxWidth,maxHeight,overflowDirection="top",additionalHiddenLinesCount=0,sourceBoundaries,registerOverflow=true})=>{const id=(0,import_react2.useId)();const{addOverflowingId,removeOverflowingId}=useOverflowActions()||{};const laidOutStyledText=[];const lineMetadata=new Map;let rowIndex=0;let sourceBoundaryIndex=0;const targetMaxHeight=Math.max(Math.round(maxHeight??Number.MAX_SAFE_INTEGER),MINIMUM_MAX_HEIGHT);if(maxWidth===void 0){throw new Error("maxWidth must be defined when maxHeight is set.")}function visitRows(element){if(!import_react2.default.isValidElement(element)){return}if(element.type===import_react2.Fragment){import_react2.default.Children.forEach(element.props.children,visitRows);return}if(element.type===Box_default){layoutInkElementAsStyledText(element,maxWidth,laidOutStyledText,lineMetadata,`${id}:${rowIndex++}`,()=>sourceBoundaries?.[sourceBoundaryIndex++]);return}debugReportError("MaxSizedBox children must be <Box> elements",element)}__name(visitRows,"visitRows");import_react2.default.Children.forEach(children,visitRows);const contentWillOverflow=targetMaxHeight!==void 0&&laidOutStyledText.length>targetMaxHeight||additionalHiddenLinesCount>0;const visibleContentHeight=contentWillOverflow&&targetMaxHeight!==void 0?targetMaxHeight-1:targetMaxHeight;const hiddenLinesCount=visibleContentHeight!==void 0?Math.max(0,laidOutStyledText.length-visibleContentHeight):0;const totalHiddenLines=hiddenLinesCount+additionalHiddenLinesCount;(0,import_react2.useEffect)(()=>{if(registerOverflow&&totalHiddenLines>0){addOverflowingId?.(id)}else{removeOverflowingId?.(id)}return()=>{removeOverflowingId?.(id)}},[id,registerOverflow,totalHiddenLines,addOverflowingId,removeOverflowingId]);const visibleStyledText=hiddenLinesCount>0?overflowDirection==="top"?laidOutStyledText.slice(hiddenLinesCount,laidOutStyledText.length):laidOutStyledText.slice(0,visibleContentHeight):laidOutStyledText;const visibleLines=visibleStyledText.map((line,index)=>{const metadata=lineMetadata.get(line);return(0,import_jsx_runtime2.jsx)(Box_default,{flexShrink:0,children:line.length>0?line.map((segment,segIndex)=>(0,import_jsx_runtime2.jsx)(Text,{...segment.props,selectionFlow:metadata.flowKey,selectionBreakAfter:metadata.breakAfter,selectionJoiner:metadata.joiner,children:segment.text},segIndex)):(0,import_jsx_runtime2.jsx)(Text,{selectable:false,selectionFlow:metadata.flowKey,selectionBreakAfter:metadata.breakAfter,selectionJoiner:metadata.joiner,children:" "})},index)});return(0,import_jsx_runtime2.jsxs)(Box_default,{flexDirection:"column",width:maxWidth,flexShrink:0,children:[totalHiddenLines>0&&overflowDirection==="top"&&(0,import_jsx_runtime2.jsxs)(Text,{color:theme.text.secondary,wrap:"truncate",children:["... first ",totalHiddenLines," line",totalHiddenLines===1?"":"s"," ","hidden ..."]}),visibleLines,totalHiddenLines>0&&overflowDirection==="bottom"&&(0,import_jsx_runtime2.jsxs)(Text,{color:theme.text.secondary,wrap:"truncate",children:["... last ",totalHiddenLines," line",totalHiddenLines===1?"":"s"," ","hidden ..."]})]})},"MaxSizedBox");function visitBoxRow(element){if(!import_react2.default.isValidElement(element)||element.type!==Box_default){debugReportError(`All children of MaxSizedBox must be <Box> elements`,element);return{noWrapSegments:[{text:"<ERROR>",props:{}}],segments:[]}}if(enableDebugLog){const boxProps=element.props;let maxExpectedProps=4;if(boxProps.children!==void 0){maxExpectedProps+=1}if(boxProps.flexDirection!==void 0&&boxProps.flexDirection!=="row"){debugReportError('MaxSizedBox children must have flexDirection="row".',element)}if(Object.keys(boxProps).length>maxExpectedProps){debugReportError(`Boxes inside MaxSizedBox must not have additional props. ${Object.keys(boxProps).join(", ")}`,element)}}const row={noWrapSegments:[],segments:[]};let hasSeenWrapped=false;function visitRowChild(element2,parentProps){if(element2===null){return}if(typeof element2==="string"||typeof element2==="number"){const text=String(element2);if(!text){return}const segment={text,props:parentProps??{}};if(parentProps===void 0||parentProps["wrap"]==="wrap"){hasSeenWrapped=true;row.segments.push(segment)}else{if(!hasSeenWrapped){row.noWrapSegments.push(segment)}else{row.segments.push(segment);debugReportError("Text elements without wrapping cannot appear after elements with wrapping in the same row.",element2)}}return}if(!import_react2.default.isValidElement(element2)){debugReportError("Invalid element.",element2);return}if(element2.type===import_react2.Fragment){import_react2.default.Children.forEach(element2.props.children,child=>visitRowChild(child,parentProps));return}if(element2.type!==Text){debugReportError("Children of a row Box must be <Text> elements.",element2);return}const{children,...currentProps}=element2.props;const mergedProps=parentProps===void 0?currentProps:{...parentProps,...currentProps};import_react2.default.Children.forEach(children,child=>visitRowChild(child,mergedProps))}__name(visitRowChild,"visitRowChild");import_react2.default.Children.forEach(element.props.children,child=>visitRowChild(child,void 0));return row}__name(visitBoxRow,"visitBoxRow");function layoutInkElementAsStyledText(element,maxWidth,output,lineMetadata,flowKey,nextSourceBoundary){const pushOutput=__name((line,breakAfter,joiner)=>{output.push(line);lineMetadata.set(line,{flowKey,breakAfter,joiner})},"pushOutput");const row=visitBoxRow(element);if(row.segments.length===0&&row.noWrapSegments.length===0){pushOutput([],"hard","\n");return}const lines=[];const nonWrappingContent=[];let noWrappingWidth=0;row.noWrapSegments.forEach(segment=>{nonWrappingContent.push(segment);noWrappingWidth+=stringWidth(segment.text)});if(row.segments.length===0){const lines2=[];let currentLine=[];nonWrappingContent.forEach(segment=>{const textLines=segment.text.split("\n");textLines.forEach((text,index)=>{if(index>0){lines2.push(currentLine);currentLine=[]}if(text){currentLine.push({text,props:segment.props})}})});if(currentLine.length>0||nonWrappingContent.length>0&&nonWrappingContent[nonWrappingContent.length-1].text.endsWith("\n")){lines2.push(currentLine)}for(const line of lines2){pushOutput(line,"hard","\n")}return}const availableWidth=maxWidth-noWrappingWidth;if(availableWidth<1){const lines2=[];let currentLine=[];let currentLineWidth=0;for(const segment of nonWrappingContent){const textLines=segment.text.split("\n");textLines.forEach((text,index)=>{if(index>0){lines2.push(currentLine);currentLine=[];currentLineWidth=0}if(text){const textWidth=stringWidth(text);if(index>0&&textWidth>0){currentLine.push({text:"\u2026",props:{}});currentLineWidth=stringWidth("\u2026")}else{const maxContentWidth=Math.max(0,maxWidth-stringWidth("\u2026"));if(textWidth<=maxContentWidth&&currentLineWidth===0){currentLine.push({text,props:segment.props});currentLineWidth+=textWidth}else{const codePoints=toCodePoints(text);let truncatedWidth=currentLineWidth;let sliceEndIndex=0;for(const char of codePoints){const charWidth=stringWidth(char);if(truncatedWidth+charWidth>maxContentWidth){break}truncatedWidth+=charWidth;sliceEndIndex++}const slice=codePoints.slice(0,sliceEndIndex).join("");if(slice){currentLine.push({text:slice,props:segment.props})}currentLine.push({text:"\u2026",props:{}});currentLineWidth=truncatedWidth+stringWidth("\u2026")}}}})}if(currentLine.length>0||nonWrappingContent.length>0&&nonWrappingContent[nonWrappingContent.length-1].text.endsWith("\n")){lines2.push(currentLine)}if(lines2.length===0){lines2.push([{text:"\u2026",props:{}}])}for(const line of lines2){pushOutput(line,"hard","\n")}return}let wrappingPart=[];let wrappingPartWidth=0;function addWrappingPartToLines(breakAfter,joiner){let line;if(lines.length===0){line=[...nonWrappingContent,...wrappingPart]}else{if(noWrappingWidth>0){line=[...[{text:" ".repeat(noWrappingWidth),props:{selectable:false}}],...wrappingPart]}else{line=wrappingPart}}lines.push(line);lineMetadata.set(line,{flowKey,breakAfter,joiner});wrappingPart=[];wrappingPartWidth=0}__name(addWrappingPartToLines,"addWrappingPartToLines");function addToWrappingPart(text,props){if(wrappingPart.length>0&&wrappingPart[wrappingPart.length-1].props===props){wrappingPart[wrappingPart.length-1].text+=text}else{wrappingPart.push({text,props})}}__name(addToWrappingPart,"addToWrappingPart");row.segments.forEach(segment=>{const linesFromSegment=segment.text.split("\n");linesFromSegment.forEach((lineText,lineIndex)=>{if(lineIndex>0){const boundary=nextSourceBoundary()??{kind:"hard",joiner:"\n"};addWrappingPartToLines(boundary.kind,boundary.joiner)}const words=lineText.split(/(\s+)/);words.forEach(word=>{if(!word)return;const wordWidth=stringWidth(word);if(wrappingPartWidth+wordWidth>availableWidth&&wrappingPartWidth>0){addWrappingPartToLines("soft",/^\s+$/u.test(word)?word:"");if(/^\s+$/.test(word)){return}}if(wordWidth>availableWidth){const wordAsCodePoints=toCodePoints(word);let remainingWordAsCodePoints=wordAsCodePoints;while(remainingWordAsCodePoints.length>0){let splitIndex=0;let currentSplitWidth=0;for(const char of remainingWordAsCodePoints){const charWidth=stringWidth(char);if(wrappingPartWidth+currentSplitWidth+charWidth>availableWidth){break}currentSplitWidth+=charWidth;splitIndex++}if(splitIndex>0){const part=remainingWordAsCodePoints.slice(0,splitIndex).join("");addToWrappingPart(part,segment.props);wrappingPartWidth+=stringWidth(part);remainingWordAsCodePoints=remainingWordAsCodePoints.slice(splitIndex)}if(remainingWordAsCodePoints.length>0){addWrappingPartToLines("soft","")}}}else{addToWrappingPart(word,segment.props);wrappingPartWidth+=wordWidth}})});if(segment.text.endsWith("\n")){addWrappingPartToLines("hard","\n")}});if(wrappingPart.length>0){addWrappingPartToLines("hard","\n")}for(const line of lines){output.push(line)}}__name(layoutInkElementAsStyledText,"layoutInkElementAsStyledText");export{theme,useOverflowState,OverflowProvider,MINIMUM_MAX_HEIGHT,setMaxSizedBoxDebugging,MaxSizedBox};
3
+ import{require_jsx_runtime}from"./chunk-REPFZQ7R.js";import{Box_default,Text}from"./chunk-YIJNS5IJ.js";import{require_react}from"./chunk-5QKDV4CD.js";import{themeManager}from"./chunk-UXSXKLRH.js";import{stringWidth,toCodePoints}from"./chunk-64CA3W6G.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var import_react2=__toESM(require_react(),1);init_esbuild_shims();var theme={get text(){return themeManager.getSemanticColors().text},get background(){return themeManager.getSemanticColors().background},get border(){return themeManager.getSemanticColors().border},get ui(){return themeManager.getSemanticColors().ui},get status(){return themeManager.getSemanticColors().status}};init_esbuild_shims();var import_react=__toESM(require_react(),1);var import_jsx_runtime=__toESM(require_jsx_runtime(),1);var OverflowStateContext=(0,import_react.createContext)(void 0);var OverflowActionsContext=(0,import_react.createContext)(void 0);var useOverflowState=__name(()=>(0,import_react.useContext)(OverflowStateContext),"useOverflowState");var useOverflowActions=__name(()=>(0,import_react.useContext)(OverflowActionsContext),"useOverflowActions");var OverflowProvider=__name(({children})=>{const[overflowingIds,setOverflowingIds]=(0,import_react.useState)(new Set);const addOverflowingId=(0,import_react.useCallback)(id=>{setOverflowingIds(prevIds=>{if(prevIds.has(id)){return prevIds}const newIds=new Set(prevIds);newIds.add(id);return newIds})},[]);const removeOverflowingId=(0,import_react.useCallback)(id=>{setOverflowingIds(prevIds=>{if(!prevIds.has(id)){return prevIds}const newIds=new Set(prevIds);newIds.delete(id);return newIds})},[]);const stateValue=(0,import_react.useMemo)(()=>({overflowingIds}),[overflowingIds]);const actionsValue=(0,import_react.useMemo)(()=>({addOverflowingId,removeOverflowingId}),[addOverflowingId,removeOverflowingId]);return(0,import_jsx_runtime.jsx)(OverflowStateContext.Provider,{value:stateValue,children:(0,import_jsx_runtime.jsx)(OverflowActionsContext.Provider,{value:actionsValue,children})})},"OverflowProvider");var import_jsx_runtime2=__toESM(require_jsx_runtime(),1);var enableDebugLog=false;var debugLogger=createDebugLogger("MAX_SIZED_BOX");var MINIMUM_MAX_HEIGHT=2;function setMaxSizedBoxDebugging(value){enableDebugLog=value}__name(setMaxSizedBoxDebugging,"setMaxSizedBoxDebugging");function debugReportError(message,element){if(!enableDebugLog)return;if(!import_react2.default.isValidElement(element)){debugLogger.error(message,`Invalid element: '${String(element)}' typeof=${typeof element}`);return}let sourceMessage="<Unknown file>";try{const elementWithSource=element;const fileName=elementWithSource._source?.fileName;const lineNumber=elementWithSource._source?.lineNumber;sourceMessage=fileName?`${fileName}:${lineNumber}`:"<Unknown file>"}catch(error){debugLogger.error("Error while trying to get file name:",error)}debugLogger.error(message,`${String(element.type)}. Source: ${sourceMessage}`)}__name(debugReportError,"debugReportError");var MaxSizedBox=__name(({children,maxWidth,maxHeight,overflowDirection="top",additionalHiddenLinesCount=0,sourceBoundaries,registerOverflow=true})=>{const id=(0,import_react2.useId)();const{addOverflowingId,removeOverflowingId}=useOverflowActions()||{};const laidOutStyledText=[];const lineMetadata=new Map;let rowIndex=0;let sourceBoundaryIndex=0;const targetMaxHeight=Math.max(Math.round(maxHeight??Number.MAX_SAFE_INTEGER),MINIMUM_MAX_HEIGHT);if(maxWidth===void 0){throw new Error("maxWidth must be defined when maxHeight is set.")}function visitRows(element){if(!import_react2.default.isValidElement(element)){return}if(element.type===import_react2.Fragment){import_react2.default.Children.forEach(element.props.children,visitRows);return}if(element.type===Box_default){layoutInkElementAsStyledText(element,maxWidth,laidOutStyledText,lineMetadata,`${id}:${rowIndex++}`,()=>sourceBoundaries?.[sourceBoundaryIndex++]);return}debugReportError("MaxSizedBox children must be <Box> elements",element)}__name(visitRows,"visitRows");import_react2.default.Children.forEach(children,visitRows);const contentWillOverflow=targetMaxHeight!==void 0&&laidOutStyledText.length>targetMaxHeight||additionalHiddenLinesCount>0;const visibleContentHeight=contentWillOverflow&&targetMaxHeight!==void 0?targetMaxHeight-1:targetMaxHeight;const hiddenLinesCount=visibleContentHeight!==void 0?Math.max(0,laidOutStyledText.length-visibleContentHeight):0;const totalHiddenLines=hiddenLinesCount+additionalHiddenLinesCount;(0,import_react2.useEffect)(()=>{if(registerOverflow&&totalHiddenLines>0){addOverflowingId?.(id)}else{removeOverflowingId?.(id)}return()=>{removeOverflowingId?.(id)}},[id,registerOverflow,totalHiddenLines,addOverflowingId,removeOverflowingId]);const visibleStyledText=hiddenLinesCount>0?overflowDirection==="top"?laidOutStyledText.slice(hiddenLinesCount,laidOutStyledText.length):laidOutStyledText.slice(0,visibleContentHeight):laidOutStyledText;const visibleLines=visibleStyledText.map((line,index)=>{const metadata=lineMetadata.get(line);return(0,import_jsx_runtime2.jsx)(Box_default,{flexShrink:0,children:line.length>0?line.map((segment,segIndex)=>(0,import_jsx_runtime2.jsx)(Text,{...segment.props,selectionFlow:metadata.flowKey,selectionBreakAfter:metadata.breakAfter,selectionJoiner:metadata.joiner,children:segment.text},segIndex)):(0,import_jsx_runtime2.jsx)(Text,{selectable:false,selectionFlow:metadata.flowKey,selectionBreakAfter:metadata.breakAfter,selectionJoiner:metadata.joiner,children:" "})},index)});return(0,import_jsx_runtime2.jsxs)(Box_default,{flexDirection:"column",width:maxWidth,flexShrink:0,children:[totalHiddenLines>0&&overflowDirection==="top"&&(0,import_jsx_runtime2.jsxs)(Text,{color:theme.text.secondary,wrap:"truncate",children:["... first ",totalHiddenLines," line",totalHiddenLines===1?"":"s"," ","hidden ..."]}),visibleLines,totalHiddenLines>0&&overflowDirection==="bottom"&&(0,import_jsx_runtime2.jsxs)(Text,{color:theme.text.secondary,wrap:"truncate",children:["... last ",totalHiddenLines," line",totalHiddenLines===1?"":"s"," ","hidden ..."]})]})},"MaxSizedBox");function visitBoxRow(element){if(!import_react2.default.isValidElement(element)||element.type!==Box_default){debugReportError(`All children of MaxSizedBox must be <Box> elements`,element);return{noWrapSegments:[{text:"<ERROR>",props:{}}],segments:[]}}if(enableDebugLog){const boxProps=element.props;let maxExpectedProps=4;if(boxProps.children!==void 0){maxExpectedProps+=1}if(boxProps.flexDirection!==void 0&&boxProps.flexDirection!=="row"){debugReportError('MaxSizedBox children must have flexDirection="row".',element)}if(Object.keys(boxProps).length>maxExpectedProps){debugReportError(`Boxes inside MaxSizedBox must not have additional props. ${Object.keys(boxProps).join(", ")}`,element)}}const row={noWrapSegments:[],segments:[]};let hasSeenWrapped=false;function visitRowChild(element2,parentProps){if(element2===null){return}if(typeof element2==="string"||typeof element2==="number"){const text=String(element2);if(!text){return}const segment={text,props:parentProps??{}};if(parentProps===void 0||parentProps["wrap"]==="wrap"){hasSeenWrapped=true;row.segments.push(segment)}else{if(!hasSeenWrapped){row.noWrapSegments.push(segment)}else{row.segments.push(segment);debugReportError("Text elements without wrapping cannot appear after elements with wrapping in the same row.",element2)}}return}if(!import_react2.default.isValidElement(element2)){debugReportError("Invalid element.",element2);return}if(element2.type===import_react2.Fragment){import_react2.default.Children.forEach(element2.props.children,child=>visitRowChild(child,parentProps));return}if(element2.type!==Text){debugReportError("Children of a row Box must be <Text> elements.",element2);return}const{children,...currentProps}=element2.props;const mergedProps=parentProps===void 0?currentProps:{...parentProps,...currentProps};import_react2.default.Children.forEach(children,child=>visitRowChild(child,mergedProps))}__name(visitRowChild,"visitRowChild");import_react2.default.Children.forEach(element.props.children,child=>visitRowChild(child,void 0));return row}__name(visitBoxRow,"visitBoxRow");function layoutInkElementAsStyledText(element,maxWidth,output,lineMetadata,flowKey,nextSourceBoundary){const pushOutput=__name((line,breakAfter,joiner)=>{output.push(line);lineMetadata.set(line,{flowKey,breakAfter,joiner})},"pushOutput");const row=visitBoxRow(element);if(row.segments.length===0&&row.noWrapSegments.length===0){pushOutput([],"hard","\n");return}const lines=[];const nonWrappingContent=[];let noWrappingWidth=0;row.noWrapSegments.forEach(segment=>{nonWrappingContent.push(segment);noWrappingWidth+=stringWidth(segment.text)});if(row.segments.length===0){const lines2=[];let currentLine=[];nonWrappingContent.forEach(segment=>{const textLines=segment.text.split("\n");textLines.forEach((text,index)=>{if(index>0){lines2.push(currentLine);currentLine=[]}if(text){currentLine.push({text,props:segment.props})}})});if(currentLine.length>0||nonWrappingContent.length>0&&nonWrappingContent[nonWrappingContent.length-1].text.endsWith("\n")){lines2.push(currentLine)}for(const line of lines2){pushOutput(line,"hard","\n")}return}const availableWidth=maxWidth-noWrappingWidth;if(availableWidth<1){const lines2=[];let currentLine=[];let currentLineWidth=0;for(const segment of nonWrappingContent){const textLines=segment.text.split("\n");textLines.forEach((text,index)=>{if(index>0){lines2.push(currentLine);currentLine=[];currentLineWidth=0}if(text){const textWidth=stringWidth(text);if(index>0&&textWidth>0){currentLine.push({text:"\u2026",props:{}});currentLineWidth=stringWidth("\u2026")}else{const maxContentWidth=Math.max(0,maxWidth-stringWidth("\u2026"));if(textWidth<=maxContentWidth&&currentLineWidth===0){currentLine.push({text,props:segment.props});currentLineWidth+=textWidth}else{const codePoints=toCodePoints(text);let truncatedWidth=currentLineWidth;let sliceEndIndex=0;for(const char of codePoints){const charWidth=stringWidth(char);if(truncatedWidth+charWidth>maxContentWidth){break}truncatedWidth+=charWidth;sliceEndIndex++}const slice=codePoints.slice(0,sliceEndIndex).join("");if(slice){currentLine.push({text:slice,props:segment.props})}currentLine.push({text:"\u2026",props:{}});currentLineWidth=truncatedWidth+stringWidth("\u2026")}}}})}if(currentLine.length>0||nonWrappingContent.length>0&&nonWrappingContent[nonWrappingContent.length-1].text.endsWith("\n")){lines2.push(currentLine)}if(lines2.length===0){lines2.push([{text:"\u2026",props:{}}])}for(const line of lines2){pushOutput(line,"hard","\n")}return}let wrappingPart=[];let wrappingPartWidth=0;function addWrappingPartToLines(breakAfter,joiner){let line;if(lines.length===0){line=[...nonWrappingContent,...wrappingPart]}else{if(noWrappingWidth>0){line=[...[{text:" ".repeat(noWrappingWidth),props:{selectable:false}}],...wrappingPart]}else{line=wrappingPart}}lines.push(line);lineMetadata.set(line,{flowKey,breakAfter,joiner});wrappingPart=[];wrappingPartWidth=0}__name(addWrappingPartToLines,"addWrappingPartToLines");function addToWrappingPart(text,props){if(wrappingPart.length>0&&wrappingPart[wrappingPart.length-1].props===props){wrappingPart[wrappingPart.length-1].text+=text}else{wrappingPart.push({text,props})}}__name(addToWrappingPart,"addToWrappingPart");row.segments.forEach(segment=>{const linesFromSegment=segment.text.split("\n");linesFromSegment.forEach((lineText,lineIndex)=>{if(lineIndex>0){const boundary=nextSourceBoundary()??{kind:"hard",joiner:"\n"};addWrappingPartToLines(boundary.kind,boundary.joiner)}const words=lineText.split(/(\s+)/);words.forEach(word=>{if(!word)return;const wordWidth=stringWidth(word);if(wrappingPartWidth+wordWidth>availableWidth&&wrappingPartWidth>0){addWrappingPartToLines("soft",/^\s+$/u.test(word)?word:"");if(/^\s+$/.test(word)){return}}if(wordWidth>availableWidth){const wordAsCodePoints=toCodePoints(word);let remainingWordAsCodePoints=wordAsCodePoints;while(remainingWordAsCodePoints.length>0){let splitIndex=0;let currentSplitWidth=0;for(const char of remainingWordAsCodePoints){const charWidth=stringWidth(char);if(wrappingPartWidth+currentSplitWidth+charWidth>availableWidth){break}currentSplitWidth+=charWidth;splitIndex++}if(splitIndex>0){const part=remainingWordAsCodePoints.slice(0,splitIndex).join("");addToWrappingPart(part,segment.props);wrappingPartWidth+=stringWidth(part);remainingWordAsCodePoints=remainingWordAsCodePoints.slice(splitIndex)}if(remainingWordAsCodePoints.length>0){addWrappingPartToLines("soft","")}}}else{addToWrappingPart(word,segment.props);wrappingPartWidth+=wordWidth}})});if(segment.text.endsWith("\n")){addWrappingPartToLines("hard","\n")}});if(wrappingPart.length>0){addWrappingPartToLines("hard","\n")}for(const line of lines){output.push(line)}}__name(layoutInkElementAsStyledText,"layoutInkElementAsStyledText");export{theme,useOverflowState,OverflowProvider,MINIMUM_MAX_HEIGHT,setMaxSizedBoxDebugging,MaxSizedBox};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC