@hostclubeos/miraos 0.0.7-beta → 0.0.8-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 (237) hide show
  1. package/chunks/{MaxSizedBox-CBUPHLMW.js → MaxSizedBox-YR2SA5XW.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-EXZJQKTK.js → StandaloneSessionPicker-VEXSGLU4.js} +1 -1
  3. package/chunks/{acp-subagent-executor-BMIXP52W.js → acp-subagent-executor-ATOLWCVC.js} +1 -1
  4. package/chunks/{acpAgent-JC4KGTLW.js → acpAgent-DN46FTZ2.js} +3 -3
  5. package/chunks/{advisor-5RUG3VFZ.js → advisor-6MI5JQGC.js} +1 -1
  6. package/chunks/{agent-SGQ7AEZI.js → agent-6HPQ4XCT.js} +1 -1
  7. package/chunks/{agent-headless-ZGCZ2DA7.js → agent-headless-KXAJBOPG.js} +1 -1
  8. package/chunks/{agent-host-client-HY5GPSHM.js → agent-host-client-NOZRE2ZR.js} +1 -1
  9. package/chunks/{agent-host-connections-KGTBS37X.js → agent-host-connections-6FOSHEWD.js} +1 -1
  10. package/chunks/{autofix-pr-E62FC67X.js → autofix-pr-IMJA2KZF.js} +1 -1
  11. package/chunks/{batch-OUC6FGCQ.js → batch-L5VJ4XGP.js} +1 -1
  12. package/chunks/{bridge-FLEIBB5V.js → bridge-CCRTJSIM.js} +1 -1
  13. package/chunks/{channel-settings-store-QG6HREVH.js → channel-settings-store-SB7BP6XT.js} +1 -1
  14. package/chunks/{chunk-BSLIVO6O.js → chunk-2DPE27WB.js} +1 -1
  15. package/chunks/{chunk-JJDF5FHA.js → chunk-32DLSPV5.js} +1 -1
  16. package/chunks/{chunk-2PB6TEZU.js → chunk-3NA5O4QO.js} +1 -1
  17. package/chunks/{chunk-RBA3TP7L.js → chunk-3VKLOQ2P.js} +1 -1
  18. package/chunks/{chunk-3KFLO5W3.js → chunk-4C5BOFDC.js} +1 -1
  19. package/chunks/{chunk-TFITRCIC.js → chunk-4RRQ7CPF.js} +1 -1
  20. package/chunks/{chunk-YN6WXB6B.js → chunk-5AJKMBPM.js} +1 -1
  21. package/chunks/{chunk-SCHCTQCG.js → chunk-5BWVS5D3.js} +1 -1
  22. package/chunks/{chunk-5RYDKYIR.js → chunk-5SX4UPMN.js} +1 -1
  23. package/chunks/{chunk-FK5L2WVV.js → chunk-5YULNQF3.js} +1 -1
  24. package/chunks/{chunk-T3A53XMM.js → chunk-66N3SLXJ.js} +1 -1
  25. package/chunks/{chunk-4WYKHP7Q.js → chunk-6AAVML2M.js} +1 -1
  26. package/chunks/{chunk-N7WQH6L4.js → chunk-6STDVRH5.js} +2 -2
  27. package/chunks/{chunk-VRAHMOQQ.js → chunk-6TNX3S5H.js} +2 -2
  28. package/chunks/{chunk-ZOWMHZWO.js → chunk-77GGGTWS.js} +1 -1
  29. package/chunks/{chunk-KNW2OD46.js → chunk-7DJYSBNJ.js} +1 -1
  30. package/chunks/{chunk-MYS5NQXO.js → chunk-7EEWU6XO.js} +1 -1
  31. package/chunks/{chunk-VJUTDS6C.js → chunk-7GU7HKIT.js} +1 -1
  32. package/chunks/{chunk-UWMLSAQY.js → chunk-7HO5DQ6V.js} +1 -1
  33. package/chunks/{chunk-SHKSVOTG.js → chunk-7L4MR4QM.js} +1 -1
  34. package/chunks/{chunk-RWFOQXPU.js → chunk-7Q6RNE77.js} +1 -1
  35. package/chunks/{chunk-FC7SJIAS.js → chunk-AHV4IMUX.js} +1 -1
  36. package/chunks/{chunk-2QYFSBJY.js → chunk-ARILWFTZ.js} +1 -1
  37. package/chunks/{chunk-TXL535SJ.js → chunk-BWFZEDYG.js} +1 -1
  38. package/chunks/chunk-BWLMXGA2.js +13 -0
  39. package/chunks/{chunk-GN7ODRDE.js → chunk-C3ZJUOTJ.js} +1 -1
  40. package/chunks/{chunk-WJLHLFIR.js → chunk-CEVKKM22.js} +1 -1
  41. package/chunks/{chunk-K7KY7FIB.js → chunk-CJLKKIUW.js} +1 -1
  42. package/chunks/{chunk-HASJX2YS.js → chunk-CLLQQMTU.js} +1 -1
  43. package/chunks/{chunk-7F5IYTVE.js → chunk-CNGBG3X5.js} +1 -1
  44. package/chunks/{chunk-RNPVWQ3V.js → chunk-CNZS2RPX.js} +1 -1
  45. package/chunks/{chunk-WC72OWF2.js → chunk-D4WMUCSK.js} +2 -2
  46. package/chunks/{chunk-W2ZVZ6LS.js → chunk-DNCXESHL.js} +1 -1
  47. package/chunks/{chunk-HSN5QUS7.js → chunk-DNXQKR5E.js} +1 -1
  48. package/chunks/{chunk-H65ZVST6.js → chunk-DTNW2CM3.js} +1 -1
  49. package/chunks/{chunk-3NB3FFLR.js → chunk-DTRSC73M.js} +3 -3
  50. package/chunks/{chunk-2VW4HXVF.js → chunk-E743PFSX.js} +1 -1
  51. package/chunks/{chunk-P5543CFV.js → chunk-EHM4KL2U.js} +1 -1
  52. package/chunks/{chunk-PQOQONLN.js → chunk-FC5IAX56.js} +1 -1
  53. package/chunks/{chunk-3MBYQYPC.js → chunk-G3COGFSZ.js} +1 -1
  54. package/chunks/{chunk-67PM7M5R.js → chunk-G4OSEVOV.js} +2 -2
  55. package/chunks/{chunk-SOCXRMZM.js → chunk-G7D42XGP.js} +2 -2
  56. package/chunks/{chunk-IF3SWUYT.js → chunk-GBEQD55S.js} +1 -1
  57. package/chunks/{chunk-EW3EVEYN.js → chunk-GM6YF6IS.js} +1 -1
  58. package/chunks/{chunk-UOYXBAN7.js → chunk-GS4FZF6I.js} +1 -1
  59. package/chunks/{chunk-2ZWVSKPK.js → chunk-HCCONFJY.js} +1 -1
  60. package/chunks/{chunk-GY4ID3EB.js → chunk-HCKF74X7.js} +1 -1
  61. package/chunks/{chunk-6RDYPRV6.js → chunk-IJH5HZTB.js} +1 -1
  62. package/chunks/{chunk-MMGNOY3U.js → chunk-IJIQDCNJ.js} +5 -5
  63. package/chunks/{chunk-TLZM3DMY.js → chunk-IK5TB2CB.js} +1 -1
  64. package/chunks/{chunk-JDABSS6M.js → chunk-IWIGJDPL.js} +1 -1
  65. package/chunks/{chunk-VBJV7T47.js → chunk-JCWNB45W.js} +1 -1
  66. package/chunks/{chunk-GTQULDIL.js → chunk-JHGMLUAL.js} +1 -1
  67. package/chunks/{chunk-23543L6E.js → chunk-JRIVHFCG.js} +1 -1
  68. package/chunks/{chunk-7SAR6NXA.js → chunk-JT5EN5MI.js} +1 -1
  69. package/chunks/{chunk-JDHMSERR.js → chunk-K2PGOAJP.js} +1 -1
  70. package/chunks/{chunk-O6Z3KO6R.js → chunk-K3RWL2YH.js} +1 -1
  71. package/chunks/{chunk-7W5DOBKY.js → chunk-KZZ5ZQHX.js} +1 -1
  72. package/chunks/{chunk-H2QXWIRZ.js → chunk-LRXYXGMT.js} +1 -1
  73. package/chunks/{chunk-YVN32EUM.js → chunk-LTXZHHNK.js} +1 -1
  74. package/chunks/{chunk-TU5QHOJC.js → chunk-M3IQE5G4.js} +1 -1
  75. package/chunks/{chunk-RRMTSVGU.js → chunk-MCHMWRNO.js} +1 -1
  76. package/chunks/{chunk-JJQJFMPL.js → chunk-MCY3IS2E.js} +1 -1
  77. package/chunks/{chunk-WCLAVBNR.js → chunk-MOXZO5PM.js} +1 -1
  78. package/chunks/{chunk-TWJ4XBED.js → chunk-MV7LX23I.js} +1 -1
  79. package/chunks/{chunk-66DZADDA.js → chunk-MXFS555I.js} +1 -1
  80. package/chunks/{chunk-USR2Y7B3.js → chunk-NNYAXFFN.js} +1 -1
  81. package/chunks/{chunk-NGH27AWP.js → chunk-NUDHRTIM.js} +1 -1
  82. package/chunks/{chunk-G35E5UB3.js → chunk-NYGJ53Y7.js} +1 -1
  83. package/chunks/chunk-OHOG4HSN.js +31 -0
  84. package/chunks/{chunk-JQOLNQQN.js → chunk-OPFBBIAQ.js} +1 -1
  85. package/chunks/{chunk-KYK53GFP.js → chunk-OXG4BLFF.js} +1 -1
  86. package/chunks/{chunk-GLQWA4W2.js → chunk-PGKVSOWW.js} +1 -1
  87. package/chunks/{chunk-PFKTTUGS.js → chunk-POMEWCFJ.js} +6 -6
  88. package/chunks/{chunk-6T25QVBX.js → chunk-Q4NEZZ6L.js} +1 -1
  89. package/chunks/{chunk-Z4JY3HGO.js → chunk-QCSGHQ2P.js} +1 -1
  90. package/chunks/{chunk-VF2UWWI2.js → chunk-QWNTORRT.js} +1 -1
  91. package/chunks/{chunk-3GJ56V2J.js → chunk-QZNCYZ7H.js} +1 -1
  92. package/chunks/{chunk-T5PDEAU5.js → chunk-S5NTCBEI.js} +1 -1
  93. package/chunks/{chunk-AIAYQAPA.js → chunk-SK5C26Y6.js} +1 -1
  94. package/chunks/{chunk-ATVRF62A.js → chunk-SMO4PEHK.js} +1 -1
  95. package/chunks/{chunk-AE6E2YKY.js → chunk-SPCIIUIG.js} +1 -1
  96. package/chunks/{chunk-CUY6CVSL.js → chunk-SVNSF5ZH.js} +1 -1
  97. package/chunks/{chunk-K7VOBDFT.js → chunk-UC455ZS7.js} +1 -1
  98. package/chunks/{chunk-J773THNP.js → chunk-UZAFPEVN.js} +1 -1
  99. package/chunks/{chunk-PVHBBTAU.js → chunk-V3ASW57P.js} +1 -1
  100. package/chunks/{chunk-4MGTY3CJ.js → chunk-VAFRD2H4.js} +1 -1
  101. package/chunks/{chunk-PSSJDUZB.js → chunk-VOCM2M4K.js} +1 -1
  102. package/chunks/{chunk-W6IOHGWW.js → chunk-VOIC5ZW2.js} +1 -1
  103. package/chunks/{chunk-V5Z6OEKJ.js → chunk-W4M6JXZB.js} +1 -1
  104. package/chunks/{chunk-4KIFAVR2.js → chunk-WJXADORN.js} +1 -1
  105. package/chunks/{chunk-P42MFWO2.js → chunk-WN6Z3J27.js} +1 -1
  106. package/chunks/{chunk-FS67DOZQ.js → chunk-WOMJLK3E.js} +1 -1
  107. package/chunks/{chunk-NVD63O5H.js → chunk-WSXRO2YB.js} +1 -1
  108. package/chunks/{chunk-DF6TBGS2.js → chunk-WUZ53TKN.js} +1 -1
  109. package/chunks/{chunk-724YPZRX.js → chunk-WW43VZ6O.js} +1 -1
  110. package/chunks/{chunk-PFECH6U6.js → chunk-WZAUO3LV.js} +1 -1
  111. package/chunks/{chunk-EF3HUB7S.js → chunk-XGPGIMZK.js} +1 -1
  112. package/chunks/{chunk-PGKFDR73.js → chunk-XJKDC7OE.js} +1 -1
  113. package/chunks/{chunk-HZ4L4MDM.js → chunk-XNP5JXCS.js} +1 -1
  114. package/chunks/{chunk-4346FNTB.js → chunk-YELFN6AG.js} +1 -1
  115. package/chunks/{chunk-WZTO3EYG.js → chunk-YFXKRGHT.js} +1 -1
  116. package/chunks/{chunk-E6LRCLLE.js → chunk-YOBM4ZFW.js} +2 -2
  117. package/chunks/{chunk-7VP4KALB.js → chunk-ZJOVJLIH.js} +1 -1
  118. package/chunks/{chunk-KK6SQPYG.js → chunk-ZQZK267X.js} +1 -1
  119. package/chunks/{codex-subagent-executor-UCDGQFTR.js → codex-subagent-executor-TPO62HU5.js} +1 -1
  120. package/chunks/{config-utils-Z6F4DVLG.js → config-utils-6GWIYBUK.js} +1 -1
  121. package/chunks/{contextCommand-HMVZT56Y.js → contextCommand-WWVGDTOL.js} +1 -1
  122. package/chunks/{core-runtime-AV7CJXOL.js → core-runtime-ASQR33TV.js} +1 -1
  123. package/chunks/{create-sub-session-NNKVHZKT.js → create-sub-session-XY2FXSPE.js} +1 -1
  124. package/chunks/{cron-create-HWZDFVPA.js → cron-create-HY3TLNV2.js} +1 -1
  125. package/chunks/{daemon-git-worktree-guard-Q3C45X7T.js → daemon-git-worktree-guard-ILW3NJJC.js} +1 -1
  126. package/chunks/{daemon-status-provider-UX574XBB.js → daemon-status-provider-JVOGEKWY.js} +1 -1
  127. package/chunks/{daemon-trust-policy-6D4KJANB.js → daemon-trust-policy-XXRBG4JE.js} +1 -1
  128. package/chunks/{daemon-trust-policy-monitor-BZ46W4IA.js → daemon-trust-policy-monitor-UL73ADOZ.js} +1 -1
  129. package/chunks/{deferred-core-runtime-YC5XIWEI.js → deferred-core-runtime-PT747R7S.js} +1 -1
  130. package/chunks/{edit-LOWDEKPX.js → edit-4PJ3NPFA.js} +1 -1
  131. package/chunks/{enterPlanMode-NGSATDRH.js → enterPlanMode-KQ62QN7S.js} +1 -1
  132. package/chunks/{environment-CVIB5DW4.js → environment-H4HADXGA.js} +1 -1
  133. package/chunks/{errors-USKSVZFO.js → errors-OSD4ZZGR.js} +1 -1
  134. package/chunks/{execution-tool-QSJLRU5N.js → execution-tool-PHHGLKWC.js} +1 -1
  135. package/chunks/{execution-worker-TQEIC4AJ.js → execution-worker-MH3CV66T.js} +1 -1
  136. package/chunks/{exitPlanMode-AW2HOTIK.js → exitPlanMode-OU5YP4XN.js} +1 -1
  137. package/chunks/{fast-path-OQWHYDXC.js → fast-path-WKOMHBWN.js} +1 -1
  138. package/chunks/{glob-7U6FQSWZ.js → glob-FYCOEQPM.js} +1 -1
  139. package/chunks/{goal-tools-5ZB6GPCJ.js → goal-tools-T27GSDNM.js} +1 -1
  140. package/chunks/{handleAutoUpdate-MLUFTWFP.js → handleAutoUpdate-XXCPJLKO.js} +1 -1
  141. package/chunks/{i18n-QAPQLOC3.js → i18n-3B2PRJM2.js} +1 -1
  142. package/chunks/{initializer-B27IZ7K4.js → initializer-HSFVDRTR.js} +1 -1
  143. package/chunks/{installationInfo-SAMHABWV.js → installationInfo-SJJ2DYZ6.js} +1 -1
  144. package/chunks/{interactive-mod-session-7LQ5CYUR.js → interactive-mod-session-BWY2JRSQ.js} +1 -1
  145. package/chunks/{list-TDMJQDQO.js → list-TGCI3MBM.js} +1 -1
  146. package/chunks/{llm-R2RFT63S.js → llm-FYR73GKD.js} +4 -4
  147. package/chunks/{loadedSettingsAdapter-ZQK5KMEW.js → loadedSettingsAdapter-DUDCINQL.js} +1 -1
  148. package/chunks/{local-AONDQYFL.js → local-7PEOBJKE.js} +1 -1
  149. package/chunks/{local-execution-environment-WJVCE26F.js → local-execution-environment-Q4OOA7BL.js} +1 -1
  150. package/chunks/{loggingContentGenerator-ALSG42YA.js → loggingContentGenerator-VVESQOIQ.js} +1 -1
  151. package/chunks/{loop-wakeup-LFU4LDJM.js → loop-wakeup-M2XLAAKZ.js} +1 -1
  152. package/chunks/{manage-memory-FBL6CHX2.js → manage-memory-FRVWHM2C.js} +1 -1
  153. package/chunks/{managed-execution-engine-FX7FDAWW.js → managed-execution-engine-AVIM6AQU.js} +1 -1
  154. package/chunks/{managed-local-serve-DRNC6PTL.js → managed-local-serve-GIXHGFIU.js} +1 -1
  155. package/chunks/{managed-npm-update-2MKV7UOI.js → managed-npm-update-3QSXGSHW.js} +1 -1
  156. package/chunks/{managed-runtime-attestation-worker-DBAHM5MN.js → managed-runtime-attestation-worker-ML4TCRAW.js} +1 -1
  157. package/chunks/{managed-runtime-bootstrap-K3GRKDNQ.js → managed-runtime-bootstrap-JWJFGLBM.js} +1 -1
  158. package/chunks/{managed-runtime-session-worker-YN4KML7A.js → managed-runtime-session-worker-4ISKROGZ.js} +1 -1
  159. package/chunks/{managed-runtime-ssh-worker-AVNBWFYC.js → managed-runtime-ssh-worker-C44V2CPM.js} +1 -1
  160. package/chunks/{managed-session-authority-MFEINLXC.js → managed-session-authority-UJ3FSKMD.js} +1 -1
  161. package/chunks/{mcp-TS5PX5FY.js → mcp-BWCLHHZ6.js} +1 -1
  162. package/chunks/{memory-JVT5LAWJ.js → memory-5XQ2JVNS.js} +1 -1
  163. package/chunks/{model-call-collection-TNBMD3YL.js → model-call-collection-DXK2SIDR.js} +1 -1
  164. package/chunks/{model-configuration-6KTQQTMO.js → model-configuration-6OLZS4C3.js} +1 -1
  165. package/chunks/{modelConfigUtils-LCZZ3EQU.js → modelConfigUtils-5S5PC2RR.js} +1 -1
  166. package/chunks/{monitor-KCCNIKLE.js → monitor-6GKCWWUI.js} +1 -1
  167. package/chunks/{nonInteractiveCli-2GHQYHGW.js → nonInteractiveCli-ROHAB2H7.js} +1 -1
  168. package/chunks/{nonInteractiveToolExecutor-R5CTTWKD.js → nonInteractiveToolExecutor-OWCCSC5Y.js} +1 -1
  169. package/chunks/{notebook-edit-KIWE2XOA.js → notebook-edit-WNRQ3QJZ.js} +1 -1
  170. package/chunks/{omni-IFTMWBMU.js → omni-DJ5RGNKA.js} +1 -1
  171. package/chunks/{openaiContentGenerator-XP3VPU6C.js → openaiContentGenerator-237NVB63.js} +1 -1
  172. package/chunks/{openaiResponsesContentGenerator-ZJ6C22EA.js → openaiResponsesContentGenerator-J33TCZKQ.js} +1 -1
  173. package/chunks/{pidfile-42P24JIA.js → pidfile-F7IYTFLX.js} +1 -1
  174. package/chunks/{processUtils-I2XOO5U2.js → processUtils-C6CSXITS.js} +1 -1
  175. package/chunks/{prompt-terminal-ledger-7EW46VQ4.js → prompt-terminal-ledger-ZGYWPFJF.js} +1 -1
  176. package/chunks/{reactive-degrade-O4JO7MOX.js → reactive-degrade-QKXPZQ3W.js} +1 -1
  177. package/chunks/{read-file-VGC4O7F2.js → read-file-GSNUMHRE.js} +1 -1
  178. package/chunks/{resumeHistoryUtils-QMVIHQRW.js → resumeHistoryUtils-4GUCHQGU.js} +1 -1
  179. package/chunks/{review-NDK2B7XI.js → review-M2QGZFIO.js} +1 -1
  180. package/chunks/{ripGrep-JY4PZABK.js → ripGrep-X4JTJZC6.js} +1 -1
  181. package/chunks/{run-qwen-serve-P5X5OZUH.js → run-qwen-serve-4WW37RL2.js} +1 -1
  182. package/chunks/{runtime-OL7B72CH.js → runtime-EFHJ6REE.js} +1 -1
  183. package/chunks/{sandboxConfig-EJTMWZHD.js → sandboxConfig-5XMIRDS4.js} +1 -1
  184. package/chunks/{scheduled-tasks-XQSZWZXG.js → scheduled-tasks-ZCYM5YQJ.js} +1 -1
  185. package/chunks/{scheduler-3TIRZEVB.js → scheduler-5UAKCD5Z.js} +1 -1
  186. package/chunks/{search-memory-P5KOTUVV.js → search-memory-KKPYK33Q.js} +1 -1
  187. package/chunks/{send-message-KFSKFXLX.js → send-message-KOZRSWXO.js} +1 -1
  188. package/chunks/{serve-UHEH433U.js → serve-5HSHEBMT.js} +1 -1
  189. package/chunks/{server-ARYDETSZ.js → server-MC6KHP3G.js} +3 -3
  190. package/chunks/{session-HKWGCZF2.js → session-Z5HFG4IQ.js} +1 -1
  191. package/chunks/{session-attachments-root-O3YQ7HWD.js → session-attachments-root-K2E5ETD4.js} +1 -1
  192. package/chunks/{session-execution-engine-selector-LZBHS3UO.js → session-execution-engine-selector-NZA6CAJB.js} +1 -1
  193. package/chunks/{session-pr-refresh-L5Z5WCXS.js → session-pr-refresh-OYJ56U3L.js} +1 -1
  194. package/chunks/{sessionService-MMPZUN5X.js → sessionService-BC56MX3G.js} +1 -1
  195. package/chunks/{settings-7PYHXPN4.js → settings-OHB77GXH.js} +1 -1
  196. package/chunks/{shell-E6QLKRVU.js → shell-VKSH7JVL.js} +1 -1
  197. package/chunks/{skill-55IZUUM5.js → skill-HQ4C2C3X.js} +1 -1
  198. package/chunks/{skill-settings-A2M5BPH7.js → skill-settings-6WPQFE3V.js} +1 -1
  199. package/chunks/{spawnChannel-KWU26CB7.js → spawnChannel-MXKVLS24.js} +1 -1
  200. package/chunks/{standalone-update-32WYZ3BJ.js → standalone-update-NZP3OAZZ.js} +1 -1
  201. package/chunks/{start-opentui-ui-S7A4FBGP.js → start-opentui-ui-25YQQD3O.js} +1 -1
  202. package/chunks/{startInteractiveUI-DY6DWFW7.js → startInteractiveUI-DWQJNIIV.js} +1 -1
  203. package/chunks/{team-create-ARICYIQB.js → team-create-RSD7IADX.js} +1 -1
  204. package/chunks/{team-plan-approval-JPRE6Q3R.js → team-plan-approval-XAOKZ6BR.js} +1 -1
  205. package/chunks/{terminal-image-renderer-HVIZ2VNE.js → terminal-image-renderer-P5AGEOYS.js} +1 -1
  206. package/chunks/{theme-manager-UEPLIBUP.js → theme-manager-YBKJYPVQ.js} +1 -1
  207. package/chunks/{tool-call-EFJKXI3Z.js → tool-call-HJCSPR6N.js} +1 -1
  208. package/chunks/{tool-result-media-LMIYNXSD.js → tool-result-media-SPWVV3OS.js} +1 -1
  209. package/chunks/{tool-search-D7HQTRQG.js → tool-search-YWCOODLL.js} +1 -1
  210. package/chunks/{total-session-admission-67QMR44O.js → total-session-admission-HKACVEI2.js} +1 -1
  211. package/chunks/{trustedFolders-HARYVS3F.js → trustedFolders-BXLZULWO.js} +1 -1
  212. package/chunks/{update-relaunch-NVNPOK5J.js → update-relaunch-CBJVLG6S.js} +1 -1
  213. package/chunks/{updateCheck-7NMXUCTN.js → updateCheck-2J6RY3L3.js} +1 -1
  214. package/chunks/{upload-config-W2SICJ32.js → upload-config-EN5XYA3V.js} +1 -1
  215. package/chunks/{useAutoAcceptIndicator-ELMIP4TJ.js → useAutoAcceptIndicator-LF7VIUER.js} +1 -1
  216. package/chunks/{validateNonInterActiveAuth-P2F6MYO6.js → validateNonInterActiveAuth-63TR5JOG.js} +1 -1
  217. package/chunks/{version-2ZFKVIIW.js → version-F22SKNME.js} +1 -1
  218. package/chunks/{web-fetch-537RS6IX.js → web-fetch-ULH7TOLR.js} +1 -1
  219. package/chunks/{web-search-O27MYFSW.js → web-search-C3ORWAWR.js} +1 -1
  220. package/chunks/{workflow-6QF4RMYM.js → workflow-4ATPGZ5N.js} +1 -1
  221. package/chunks/{workflow-ancestor-trust-CABLU3VV.js → workflow-ancestor-trust-AJ27EBZD.js} +1 -1
  222. package/chunks/{workspace-agents-5WP3PY7W.js → workspace-agents-VLAJGYJF.js} +1 -1
  223. package/chunks/{workspace-providers-status-7G2EJJEO.js → workspace-providers-status-TFAXNJ6L.js} +1 -1
  224. package/chunks/{workspace-recovery-worker-ICCIDEWU.js → workspace-recovery-worker-GKYYJPXV.js} +1 -1
  225. package/chunks/{workspace-registration-store-WHXMNQQQ.js → workspace-registration-store-ANR3STGQ.js} +1 -1
  226. package/chunks/{workspace-registry-NXBODLYH.js → workspace-registry-OVHNLVBM.js} +1 -1
  227. package/chunks/{workspace-runtime-coordinator-CJXS273B.js → workspace-runtime-coordinator-IEN2G7JP.js} +1 -1
  228. package/chunks/{workspace-service-HUDE2RXN.js → workspace-service-NISFZTBE.js} +1 -1
  229. package/chunks/{workspace-skills-status-FJC6U62F.js → workspace-skills-status-QRF5ZXMT.js} +1 -1
  230. package/chunks/{workspace-trust-reconciler-ZIQ3A5ZB.js → workspace-trust-reconciler-X3XMX2GJ.js} +1 -1
  231. package/chunks/{write-file-652YGG7I.js → write-file-SF42KZAH.js} +1 -1
  232. package/chunks/{zoom-image-YEH4O74G.js → zoom-image-4UMB6G3P.js} +1 -1
  233. package/cli.js +2 -2
  234. package/execution-worker.js +1 -1
  235. package/package.json +2 -2
  236. package/chunks/chunk-56PVVXUG.js +0 -8
  237. 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{ProcessRegistry}from"./chunk-ESSOEHTE.js";import{createStderrForwarder}from"./chunk-QDSIJTQB.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError,ndJsonStream}from"./chunk-7JDZEB77.js";import{AgentEventEmitter,renderSubagentSystemPrompt}from"./chunk-PFKTTUGS.js";import{sanitizeChildEnv}from"./chunk-C6KSOOGV.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{spawn}from"node:child_process";import{Readable,Writable}from"node:stream";init_esbuild_shims();var INIT_TIMEOUT_MS=1e4;var debugLogger=createDebugLogger("EXTERNAL_AGENT");function externalModelLabel(command){return`external-acp:${command.split(/[\\/]/).pop()??command}`}__name(externalModelLabel,"externalModelLabel");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var EXTERNAL_ACTION_PROMPT_MAX=300;function stripControlChars(value){let out="";for(const ch of value){const code=ch.codePointAt(0)??0;out+=code>=32&&code!==127&&!(code>=128&&code<=159)?ch:" "}return out}__name(stripControlChars,"stripControlChars");function describeExternalAction(toolCall){const title=stripControlChars(toolCall.title??toolCall.kind??"External action");const raw=toolCall.rawInput;if(!isRecord(raw))return title;const detail=stripControlChars(JSON.stringify(raw));const rendered=`${title}: ${detail}`;return rendered.length>EXTERNAL_ACTION_PROMPT_MAX?`${rendered.slice(0,EXTERNAL_ACTION_PROMPT_MAX)}\u2026`:rendered}__name(describeExternalAction,"describeExternalAction");function assertExternalAgentSpawnPlatformSupported(platform=process.platform){if(platform==="win32"){throw new Error("External agents are not supported on Windows in this release: the executor spawn is POSIX-only. An npm-installed adapter resolves to a `.cmd` launcher that cannot be spawned without a shell, and the process-tree reaping is POSIX-specific. Run the external agent on macOS/Linux (or WSL). Windows support is a tracked follow-up.")}}__name(assertExternalAgentSpawnPlatformSupported,"assertExternalAgentSpawnPlatformSupported");function resolvePermissionMode(permissionMode,approvalMode){switch((approvalMode??permissionMode??"").trim().toLowerCase()){case"auto":case"acceptedits":case"auto-edit":return"acceptEdits";case"plan":return"plan";case"bypasspermissions":case"bypass":case"yolo":return"bypass";default:return"default"}}__name(resolvePermissionMode,"resolvePermissionMode");var POLICY_MODE_ALIASES={bypass:["bypassPermissions","yolo"],acceptEdits:["acceptEdits","auto-edit","auto"],plan:["plan"],default:["default"]};function selectPeerModeId(policy,availableModeIds){return POLICY_MODE_ALIASES[policy].find(id=>availableModeIds.includes(id))}__name(selectPeerModeId,"selectPeerModeId");function optionKindForOutcome(outcome){switch(outcome){case"proceed_once":case"proceed_once_and_switch_to_default":return"allow_once";case"proceed_always":case"proceed_always_server":case"proceed_always_tool":case"proceed_always_project":case"proceed_always_user":return"allow_always";case"modify_with_editor":case"cancel":case"restore_previous":return"reject_once";default:{const exhaustive=outcome;void exhaustive;return"reject_once"}}}__name(optionKindForOutcome,"optionKindForOutcome");function selectPermissionOption(options,outcome){if(outcome==="cancel")return void 0;if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}const kind=optionKindForOutcome(outcome);return(options.find(option=>option.kind===kind)??(kind==="allow_always"?options.find(option=>option.kind==="allow_once"):void 0)??options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectPermissionOption,"selectPermissionOption");function selectRejectOption(options){if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}return(options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectRejectOption,"selectRejectOption");function isExpectedExternalAgentCleanupExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited uncleanly during shutdown \(code=[^,]+, signal=[^)]+\)$/.test(error.message)}__name(isExpectedExternalAgentCleanupExit,"isExpectedExternalAgentCleanupExit");function isUnprovenExternalAgentTreeExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited before its initial process-tree snapshot completed$/.test(error.message)}__name(isUnprovenExternalAgentTreeExit,"isUnprovenExternalAgentTreeExit");var ExternalAgentTimeoutError=class extends Error{static{__name(this,"ExternalAgentTimeoutError")}constructor(timeoutMs){super(`External ACP operation timed out after ${timeoutMs}ms`);this.name="ExternalAgentTimeoutError"}};var AcpSubagentExecutor=class _AcpSubagentExecutor{constructor(params,child,emitter){this.params=params;this.child=child;this.emitter=emitter;this.coreView={getEventEmitter:__name(()=>emitter,"getEventEmitter"),modelConfig:{...params.modelConfig,model:externalModelLabel(params.spec.command)}};void child.exited.then(()=>this.fail(new Error(`external agent "${params.name}" exited`)),error=>this.fail(error))}static{__name(this,"AcpSubagentExecutor")}connection;sessionId="";finalText="";thoughtText="";terminateMode="ERROR";round=0;durationMs=0;turnStartedAt=0;toolCalls=0;toolSucceeded=0;toolFailed=0;executing=false;started=false;disposed=false;cancelled=false;disposePromise;provider;pendingPermissions=new Map;tools=new Map;toolNames=new Map;finishedTools=new Set;failure=new AbortController;coreView;static async create(params){assertExternalAgentSpawnPlatformSupported();if(params.runConfig.max_turns!==void 0){throw new Error("External ACP agents cannot enforce max_turns.")}const minutes=params.runConfig.max_time_minutes;if(minutes!==void 0&&(!Number.isFinite(minutes)||minutes<=0||minutes*6e4>2147483647)){throw new Error("External ACP max_time_minutes must be positive, finite, and within the Node timer range.")}const child=spawn(params.spec.command,params.spec.args??[],{cwd:params.runtimeContext.getTargetDir(),stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:true,env:sanitizeChildEnv(process.env)});const tracked=new ProcessRegistry().reserve().attach(child,{ownsProcessTree:true});const executor=new _AcpSubagentExecutor(params,tracked,params.eventEmitter??new AgentEventEmitter);child.on("error",error=>executor.fail(error));child.stdin.on("error",error=>executor.fail(error));child.stdout.on("error",error=>executor.fail(error));const forwarder=createStderrForwarder({prefix:`[external-agent ${params.name}] `});child.stderr.setEncoding("utf8");child.stderr.on("data",forwarder.onData);child.stderr.on("end",forwarder.onEnd);child.stderr.on("error",()=>{});try{executor.connection=new ClientSideConnection(()=>executor.buildClient(),ndJsonStream(Writable.toWeb(child.stdin),Readable.toWeb(child.stdout)));void executor.connection.closed.then(()=>executor.fail(new Error("External ACP connection closed")));await executor.wait(executor.connect(),INIT_TIMEOUT_MS);return executor}catch(error){await executor.dispose();throw error}}buildClient(){return{sessionUpdate:__name(async params=>this.onSessionUpdate(params),"sessionUpdate"),requestPermission:__name(params=>this.onRequestPermission(params),"requestPermission"),readTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/read_text_file")},"readTextFile"),writeTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/write_text_file")},"writeTextFile"),extMethod:__name(async method=>{throw RequestError.methodNotFound(method)},"extMethod"),extNotification:__name(async()=>{},"extNotification")}}async connect(){const initialized=await this.connection.initialize({protocolVersion:PROTOCOL_VERSION,clientCapabilities:{fs:{readTextFile:false,writeTextFile:false}}});if(initialized.protocolVersion!==PROTOCOL_VERSION){throw new Error("Unsupported external ACP protocol version")}const session=await this.connection.newSession({cwd:this.params.runtimeContext.getTargetDir(),mcpServers:[]});if(!session.sessionId)throw new Error("External ACP agent returned no sessionId");this.sessionId=session.sessionId;const policy=resolvePermissionMode(this.params.permissionMode,this.params.approvalMode);const availableIds=session.modes?.availableModes.map(mode=>mode.id)??[];const modeId=selectPeerModeId(policy,availableIds);if(!modeId){throw new Error(`External ACP agent does not advertise any mode for the host's ${policy} approval policy (advertised: ${availableIds.join(", ")||"none"})`)}await this.connection.setSessionMode({sessionId:this.sessionId,modeId})}fail(error){this.failure.abort(error);this.drainPermissions()}async wait(operation,timeoutMs,signal){let timer;let onFailure=__name(()=>{},"onFailure");let onAbort=__name(()=>{},"onAbort");const stopped=new Promise((_resolve,reject)=>{onFailure=__name(()=>reject(this.failure.signal.reason),"onFailure");onAbort=__name(()=>reject(signal?.reason??new Error("External agent cancelled")),"onAbort");this.failure.signal.addEventListener("abort",onFailure,{once:true});signal?.addEventListener("abort",onAbort,{once:true});if(this.failure.signal.aborted)onFailure();if(signal?.aborted)onAbort();if(timeoutMs!==void 0){timer=setTimeout(()=>reject(new ExternalAgentTimeoutError(timeoutMs)),timeoutMs)}});try{return await Promise.race([operation,stopped])}finally{clearTimeout(timer);this.failure.signal.removeEventListener("abort",onFailure);signal?.removeEventListener("abort",onAbort)}}async execute(context,signal,options={}){if(context.get("initial_messages_override")!==void 0){throw new Error("External ACP agents cannot import in-process conversation history")}const continuation=this.started;const system=continuation?"":renderSubagentSystemPrompt(this.params.promptConfig,context,this.params.runtimeContext);const task=String(context.get("task_prompt")??"Get Started!");const catalog=system?this.params.runtimeContext.getAutoMemoryContext():"";await this.runTurn([...system?[{type:"text",text:system}]:[],{type:"text",text:task},...catalog?[{type:"text",text:catalog}]:[]],signal,options,continuation?[task]:void 0)}async executeExternalInputs(inputs,signal,options={}){if(inputs.length===0)return;await this.runTurn(this.inputPrompt(inputs),signal,options,inputs)}inputPrompt(inputs){return inputs.map(input=>({type:"text",text:typeof input==="string"?input:input.text}))}emitInputs(inputs){for(const input of inputs){this.emitter.emit("external_message",{subagentId:this.id,kind:typeof input==="string"?"message":input.kind,text:typeof input==="string"?input:input.text,timestamp:Date.now()})}}async runTurn(prompt,signal,options={},inputs){if(this.executing)throw new Error("External ACP agents do not support concurrent turns");if(this.disposed||this.failure.signal.aborted)throw new Error("External ACP agent is closed");this.executing=true;this.started=true;this.cancelled=false;this.finalText="";this.thoughtText="";this.terminateMode="ERROR";if(options.resetStats!==false){this.round=this.durationMs=this.toolCalls=this.toolSucceeded=this.toolFailed=0}this.tools.clear();this.toolNames.clear();this.finishedTools.clear();this.turnStartedAt=Date.now();const timeoutMs=this.params.runConfig.max_time_minutes===void 0?void 0:this.params.runConfig.max_time_minutes*6e4;const cancel=__name(()=>{this.cancelled=true;this.drainPermissions();void this.connection.cancel({sessionId:this.sessionId}).catch(()=>{})},"cancel");signal?.addEventListener("abort",cancel,{once:true});let timedOut=false;try{this.emitter.emit("start",{subagentId:this.id,name:this.params.name,model:this.coreView.modelConfig.model,tools:[],timestamp:Date.now()});if(signal?.aborted){this.terminateMode="CANCELLED";return}const entryRound=this.round;let next=prompt;do{this.round++;const remaining=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remaining!==void 0&&remaining<=0){this.terminateMode="TIMEOUT";break}if(inputs&&this.round===entryRound+1)this.emitInputs(inputs);const result=await this.wait(this.connection.prompt({sessionId:this.sessionId,prompt:next}),remaining,signal);this.terminateMode=this.stopMode(result.stopReason);if(this.terminateMode!=="GOAL")break;if(signal?.aborted){this.terminateMode="CANCELLED";break}const remainingNext=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remainingNext!==void 0&&remainingNext<=0){this.terminateMode="TIMEOUT";break}const queued=this.provider?.()??[];if(queued.length===0)break;this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.finalText="";this.thoughtText="";this.emitInputs(queued);next=this.inputPrompt(queued)}while(!signal?.aborted);if(signal?.aborted)this.terminateMode="CANCELLED"}catch(error){timedOut=error instanceof ExternalAgentTimeoutError;this.terminateMode=signal?.aborted?"CANCELLED":timedOut?"TIMEOUT":"ERROR";if(this.emitter.rawListeners("error").length>0&&!signal?.aborted){this.emitter.emit("error",{subagentId:this.id,error:error instanceof Error?error.message:String(error),timestamp:Date.now()})}await this.dispose();if(!signal?.aborted&&!timedOut)throw error}finally{signal?.removeEventListener("abort",cancel);this.durationMs+=Date.now()-this.turnStartedAt;this.executing=false;this.drainPermissions();this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.flushOpenTools();this.emitter.emit("finish",{subagentId:this.id,terminateReason:this.terminateMode,rounds:this.round,totalDurationMs:this.durationMs,totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,timestamp:Date.now()})}}stopMode(reason){switch(reason){case"end_turn":return"GOAL";case"max_turn_requests":return"MAX_TURNS";case"cancelled":return"CANCELLED";case"refusal":return"ERROR";default:return"ERROR"}}get id(){return this.params.subagentId??this.params.name}getFinalText(){return this.finalText}getTerminateMode(){return this.terminateMode}getCore(){return this.coreView}setExternalMessageProvider(provider){this.provider=provider}getExecutionSummary(){return{rounds:this.round,totalDurationMs:this.durationMs+(this.executing?Date.now()-this.turnStartedAt:0),totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,successRate:this.toolCalls?this.toolSucceeded/this.toolCalls*100:0,inputTokens:0,outputTokens:0,thoughtTokens:0,cachedTokens:0,totalTokens:0,toolUsage:[]}}dispose(){this.disposed=true;this.fail(new Error("External ACP agent disposed"));return this.disposePromise??=this.child.terminate().catch(error=>{if(isUnprovenExternalAgentTreeExit(error)){const detail=error instanceof Error?error.message:String(error);debugLogger.warn(`External ACP agent process tree was not proven gone after disposal: ${detail}`);if(this.emitter.rawListeners("error").length>0){this.emitter.emit("error",{subagentId:this.id,error:`External agent process tree not proven gone after disposal: ${detail}`,timestamp:Date.now()})}return}if(!isExpectedExternalAgentCleanupExit(error))throw error})}drainPermissions(){for(const cancel of this.pendingPermissions.values())cancel();this.pendingPermissions.clear()}onSessionUpdate({sessionId,update}){if(sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted)return;switch(update.sessionUpdate){case"agent_message_chunk":case"agent_thought_chunk":{const thought=update.sessionUpdate==="agent_thought_chunk";const text=update.content.type==="text"?update.content.text:JSON.stringify(update.content);if(thought)this.thoughtText+=text;else this.finalText+=text;this.emitter.emit("stream_text",{subagentId:this.id,round:this.round,text,thought,timestamp:Date.now()});break}case"tool_call":this.updateTool(update);break;case"tool_call_update":this.updateTool(update);break;default:break}}updateTool(update){if(update._meta?.["toolLifecycle"]!==void 0&&update.status===void 0&&update.content===void 0)return;const callId=update.toolCallId;if(this.finishedTools.has(callId))return;const previous=this.tools.get(callId);const tool={toolCallId:callId,title:previous?.title??"External tool",...previous,...Object.fromEntries(Object.entries(update).filter(([,value])=>value!==null&&value!==void 0))};this.tools.set(callId,tool);const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;if(!previous){this.toolNames.set(callId,name);this.toolCalls++;this.emitter.emit("tool_call",{subagentId:this.id,round:this.round,callId,name,args:isRecord(tool.rawInput)?tool.rawInput:{input:tool.rawInput},description:tool.title,timestamp:Date.now()})}if(tool.status!=="completed"&&tool.status!=="failed")return;this.finishedTools.add(callId);this.tools.delete(callId);const success=tool.status==="completed";if(success)this.toolSucceeded++;else this.toolFailed++;this.toolNames.delete(callId);const response={input:tool.rawInput??null,toolName:reportedName,output:tool.rawOutput??null,content:tool.content??null,status:tool.status};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success,responseParts,resultDisplay:JSON.stringify(tool.rawOutput??tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}flushOpenTools(){for(const[callId,tool]of this.tools){const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;this.toolFailed++;const response={input:tool.rawInput??null,toolName:reportedName,output:null,content:tool.content??null,status:"failed"};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success:false,responseParts,resultDisplay:JSON.stringify(tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}this.tools.clear();this.toolNames.clear()}async onRequestPermission(params){const cancelled={outcome:{outcome:"cancelled"}};const runtime=this.params.runtimeContext;const callId=params.toolCall.toolCallId;const meta=params.toolCall._meta?.["claudeCode"];const name=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:params.toolCall.kind??"external_tool";if(params.sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted||this.pendingPermissions.has(callId)||params.options.length===0||new Set(params.options.map(option=>option.optionId)).size!==params.options.length)return cancelled;if(name.replaceAll("_","").toLowerCase()==="askuserquestion"||runtime.getShouldAvoidPermissionPrompts()||!runtime.isInteractive()&&!runtime.getExperimentalZedIntegration()&&runtime.getInputFormat()!=="stream-json"||this.emitter.rawListeners("tool_waiting_approval").length===0){const rejectOptionId=selectRejectOption(params.options);return rejectOptionId?{outcome:{outcome:"selected",optionId:rejectOptionId}}:cancelled}return new Promise(resolve=>{const finish=__name(optionId=>{if(this.pendingPermissions.get(callId)!==deny)return;this.pendingPermissions.delete(callId);resolve(optionId?{outcome:{outcome:"selected",optionId}}:cancelled)},"finish");const deny=__name(()=>finish(),"deny");this.pendingPermissions.set(callId,deny);try{this.emitter.emit("tool_waiting_approval",{subagentId:this.id,round:this.round,callId,name,args:isRecord(params.toolCall.rawInput)?params.toolCall.rawInput:{},description:params.toolCall.title??"External action",confirmationDetails:{type:"info",title:params.toolCall.title??"External action",prompt:describeExternalAction(params.toolCall),renderPromptAsPlainText:true,hideAlwaysAllow:true},respond:__name(async outcome=>finish(selectPermissionOption(params.options,outcome)??(outcome==="cancel"?selectRejectOption(params.options):void 0)),"respond"),timestamp:Date.now()})}catch{deny()}})}};var acpExternalAgentExecutor={create:__name(params=>AcpSubagentExecutor.create(params),"create")};export{externalModelLabel,describeExternalAction,assertExternalAgentSpawnPlatformSupported,resolvePermissionMode,selectPeerModeId,optionKindForOutcome,selectPermissionOption,selectRejectOption,isExpectedExternalAgentCleanupExit,isUnprovenExternalAgentTreeExit,acpExternalAgentExecutor};
3
+ import{ProcessRegistry}from"./chunk-ESSOEHTE.js";import{createStderrForwarder}from"./chunk-QDSIJTQB.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError,ndJsonStream}from"./chunk-7JDZEB77.js";import{AgentEventEmitter,renderSubagentSystemPrompt}from"./chunk-POMEWCFJ.js";import{sanitizeChildEnv}from"./chunk-C6KSOOGV.js";import{createDebugLogger}from"./chunk-46KPDLFH.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{spawn}from"node:child_process";import{Readable,Writable}from"node:stream";init_esbuild_shims();var INIT_TIMEOUT_MS=1e4;var debugLogger=createDebugLogger("EXTERNAL_AGENT");function externalModelLabel(command){return`external-acp:${command.split(/[\\/]/).pop()??command}`}__name(externalModelLabel,"externalModelLabel");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var EXTERNAL_ACTION_PROMPT_MAX=300;function stripControlChars(value){let out="";for(const ch of value){const code=ch.codePointAt(0)??0;out+=code>=32&&code!==127&&!(code>=128&&code<=159)?ch:" "}return out}__name(stripControlChars,"stripControlChars");function describeExternalAction(toolCall){const title=stripControlChars(toolCall.title??toolCall.kind??"External action");const raw=toolCall.rawInput;if(!isRecord(raw))return title;const detail=stripControlChars(JSON.stringify(raw));const rendered=`${title}: ${detail}`;return rendered.length>EXTERNAL_ACTION_PROMPT_MAX?`${rendered.slice(0,EXTERNAL_ACTION_PROMPT_MAX)}\u2026`:rendered}__name(describeExternalAction,"describeExternalAction");function assertExternalAgentSpawnPlatformSupported(platform=process.platform){if(platform==="win32"){throw new Error("External agents are not supported on Windows in this release: the executor spawn is POSIX-only. An npm-installed adapter resolves to a `.cmd` launcher that cannot be spawned without a shell, and the process-tree reaping is POSIX-specific. Run the external agent on macOS/Linux (or WSL). Windows support is a tracked follow-up.")}}__name(assertExternalAgentSpawnPlatformSupported,"assertExternalAgentSpawnPlatformSupported");function resolvePermissionMode(permissionMode,approvalMode){switch((approvalMode??permissionMode??"").trim().toLowerCase()){case"auto":case"acceptedits":case"auto-edit":return"acceptEdits";case"plan":return"plan";case"bypasspermissions":case"bypass":case"yolo":return"bypass";default:return"default"}}__name(resolvePermissionMode,"resolvePermissionMode");var POLICY_MODE_ALIASES={bypass:["bypassPermissions","yolo"],acceptEdits:["acceptEdits","auto-edit","auto"],plan:["plan"],default:["default"]};function selectPeerModeId(policy,availableModeIds){return POLICY_MODE_ALIASES[policy].find(id=>availableModeIds.includes(id))}__name(selectPeerModeId,"selectPeerModeId");function optionKindForOutcome(outcome){switch(outcome){case"proceed_once":case"proceed_once_and_switch_to_default":return"allow_once";case"proceed_always":case"proceed_always_server":case"proceed_always_tool":case"proceed_always_project":case"proceed_always_user":return"allow_always";case"modify_with_editor":case"cancel":case"restore_previous":return"reject_once";default:{const exhaustive=outcome;void exhaustive;return"reject_once"}}}__name(optionKindForOutcome,"optionKindForOutcome");function selectPermissionOption(options,outcome){if(outcome==="cancel")return void 0;if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}const kind=optionKindForOutcome(outcome);return(options.find(option=>option.kind===kind)??(kind==="allow_always"?options.find(option=>option.kind==="allow_once"):void 0)??options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectPermissionOption,"selectPermissionOption");function selectRejectOption(options){if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}return(options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectRejectOption,"selectRejectOption");function isExpectedExternalAgentCleanupExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited uncleanly during shutdown \(code=[^,]+, signal=[^)]+\)$/.test(error.message)}__name(isExpectedExternalAgentCleanupExit,"isExpectedExternalAgentCleanupExit");function isUnprovenExternalAgentTreeExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited before its initial process-tree snapshot completed$/.test(error.message)}__name(isUnprovenExternalAgentTreeExit,"isUnprovenExternalAgentTreeExit");var ExternalAgentTimeoutError=class extends Error{static{__name(this,"ExternalAgentTimeoutError")}constructor(timeoutMs){super(`External ACP operation timed out after ${timeoutMs}ms`);this.name="ExternalAgentTimeoutError"}};var AcpSubagentExecutor=class _AcpSubagentExecutor{constructor(params,child,emitter){this.params=params;this.child=child;this.emitter=emitter;this.coreView={getEventEmitter:__name(()=>emitter,"getEventEmitter"),modelConfig:{...params.modelConfig,model:externalModelLabel(params.spec.command)}};void child.exited.then(()=>this.fail(new Error(`external agent "${params.name}" exited`)),error=>this.fail(error))}static{__name(this,"AcpSubagentExecutor")}connection;sessionId="";finalText="";thoughtText="";terminateMode="ERROR";round=0;durationMs=0;turnStartedAt=0;toolCalls=0;toolSucceeded=0;toolFailed=0;executing=false;started=false;disposed=false;cancelled=false;disposePromise;provider;pendingPermissions=new Map;tools=new Map;toolNames=new Map;finishedTools=new Set;failure=new AbortController;coreView;static async create(params){assertExternalAgentSpawnPlatformSupported();if(params.runConfig.max_turns!==void 0){throw new Error("External ACP agents cannot enforce max_turns.")}const minutes=params.runConfig.max_time_minutes;if(minutes!==void 0&&(!Number.isFinite(minutes)||minutes<=0||minutes*6e4>2147483647)){throw new Error("External ACP max_time_minutes must be positive, finite, and within the Node timer range.")}const child=spawn(params.spec.command,params.spec.args??[],{cwd:params.runtimeContext.getTargetDir(),stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:true,env:sanitizeChildEnv(process.env)});const tracked=new ProcessRegistry().reserve().attach(child,{ownsProcessTree:true});const executor=new _AcpSubagentExecutor(params,tracked,params.eventEmitter??new AgentEventEmitter);child.on("error",error=>executor.fail(error));child.stdin.on("error",error=>executor.fail(error));child.stdout.on("error",error=>executor.fail(error));const forwarder=createStderrForwarder({prefix:`[external-agent ${params.name}] `});child.stderr.setEncoding("utf8");child.stderr.on("data",forwarder.onData);child.stderr.on("end",forwarder.onEnd);child.stderr.on("error",()=>{});try{executor.connection=new ClientSideConnection(()=>executor.buildClient(),ndJsonStream(Writable.toWeb(child.stdin),Readable.toWeb(child.stdout)));void executor.connection.closed.then(()=>executor.fail(new Error("External ACP connection closed")));await executor.wait(executor.connect(),INIT_TIMEOUT_MS);return executor}catch(error){await executor.dispose();throw error}}buildClient(){return{sessionUpdate:__name(async params=>this.onSessionUpdate(params),"sessionUpdate"),requestPermission:__name(params=>this.onRequestPermission(params),"requestPermission"),readTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/read_text_file")},"readTextFile"),writeTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/write_text_file")},"writeTextFile"),extMethod:__name(async method=>{throw RequestError.methodNotFound(method)},"extMethod"),extNotification:__name(async()=>{},"extNotification")}}async connect(){const initialized=await this.connection.initialize({protocolVersion:PROTOCOL_VERSION,clientCapabilities:{fs:{readTextFile:false,writeTextFile:false}}});if(initialized.protocolVersion!==PROTOCOL_VERSION){throw new Error("Unsupported external ACP protocol version")}const session=await this.connection.newSession({cwd:this.params.runtimeContext.getTargetDir(),mcpServers:[]});if(!session.sessionId)throw new Error("External ACP agent returned no sessionId");this.sessionId=session.sessionId;const policy=resolvePermissionMode(this.params.permissionMode,this.params.approvalMode);const availableIds=session.modes?.availableModes.map(mode=>mode.id)??[];const modeId=selectPeerModeId(policy,availableIds);if(!modeId){throw new Error(`External ACP agent does not advertise any mode for the host's ${policy} approval policy (advertised: ${availableIds.join(", ")||"none"})`)}await this.connection.setSessionMode({sessionId:this.sessionId,modeId})}fail(error){this.failure.abort(error);this.drainPermissions()}async wait(operation,timeoutMs,signal){let timer;let onFailure=__name(()=>{},"onFailure");let onAbort=__name(()=>{},"onAbort");const stopped=new Promise((_resolve,reject)=>{onFailure=__name(()=>reject(this.failure.signal.reason),"onFailure");onAbort=__name(()=>reject(signal?.reason??new Error("External agent cancelled")),"onAbort");this.failure.signal.addEventListener("abort",onFailure,{once:true});signal?.addEventListener("abort",onAbort,{once:true});if(this.failure.signal.aborted)onFailure();if(signal?.aborted)onAbort();if(timeoutMs!==void 0){timer=setTimeout(()=>reject(new ExternalAgentTimeoutError(timeoutMs)),timeoutMs)}});try{return await Promise.race([operation,stopped])}finally{clearTimeout(timer);this.failure.signal.removeEventListener("abort",onFailure);signal?.removeEventListener("abort",onAbort)}}async execute(context,signal,options={}){if(context.get("initial_messages_override")!==void 0){throw new Error("External ACP agents cannot import in-process conversation history")}const continuation=this.started;const system=continuation?"":renderSubagentSystemPrompt(this.params.promptConfig,context,this.params.runtimeContext);const task=String(context.get("task_prompt")??"Get Started!");const catalog=system?this.params.runtimeContext.getAutoMemoryContext():"";await this.runTurn([...system?[{type:"text",text:system}]:[],{type:"text",text:task},...catalog?[{type:"text",text:catalog}]:[]],signal,options,continuation?[task]:void 0)}async executeExternalInputs(inputs,signal,options={}){if(inputs.length===0)return;await this.runTurn(this.inputPrompt(inputs),signal,options,inputs)}inputPrompt(inputs){return inputs.map(input=>({type:"text",text:typeof input==="string"?input:input.text}))}emitInputs(inputs){for(const input of inputs){this.emitter.emit("external_message",{subagentId:this.id,kind:typeof input==="string"?"message":input.kind,text:typeof input==="string"?input:input.text,timestamp:Date.now()})}}async runTurn(prompt,signal,options={},inputs){if(this.executing)throw new Error("External ACP agents do not support concurrent turns");if(this.disposed||this.failure.signal.aborted)throw new Error("External ACP agent is closed");this.executing=true;this.started=true;this.cancelled=false;this.finalText="";this.thoughtText="";this.terminateMode="ERROR";if(options.resetStats!==false){this.round=this.durationMs=this.toolCalls=this.toolSucceeded=this.toolFailed=0}this.tools.clear();this.toolNames.clear();this.finishedTools.clear();this.turnStartedAt=Date.now();const timeoutMs=this.params.runConfig.max_time_minutes===void 0?void 0:this.params.runConfig.max_time_minutes*6e4;const cancel=__name(()=>{this.cancelled=true;this.drainPermissions();void this.connection.cancel({sessionId:this.sessionId}).catch(()=>{})},"cancel");signal?.addEventListener("abort",cancel,{once:true});let timedOut=false;try{this.emitter.emit("start",{subagentId:this.id,name:this.params.name,model:this.coreView.modelConfig.model,tools:[],timestamp:Date.now()});if(signal?.aborted){this.terminateMode="CANCELLED";return}const entryRound=this.round;let next=prompt;do{this.round++;const remaining=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remaining!==void 0&&remaining<=0){this.terminateMode="TIMEOUT";break}if(inputs&&this.round===entryRound+1)this.emitInputs(inputs);const result=await this.wait(this.connection.prompt({sessionId:this.sessionId,prompt:next}),remaining,signal);this.terminateMode=this.stopMode(result.stopReason);if(this.terminateMode!=="GOAL")break;if(signal?.aborted){this.terminateMode="CANCELLED";break}const remainingNext=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remainingNext!==void 0&&remainingNext<=0){this.terminateMode="TIMEOUT";break}const queued=this.provider?.()??[];if(queued.length===0)break;this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.finalText="";this.thoughtText="";this.emitInputs(queued);next=this.inputPrompt(queued)}while(!signal?.aborted);if(signal?.aborted)this.terminateMode="CANCELLED"}catch(error){timedOut=error instanceof ExternalAgentTimeoutError;this.terminateMode=signal?.aborted?"CANCELLED":timedOut?"TIMEOUT":"ERROR";if(this.emitter.rawListeners("error").length>0&&!signal?.aborted){this.emitter.emit("error",{subagentId:this.id,error:error instanceof Error?error.message:String(error),timestamp:Date.now()})}await this.dispose();if(!signal?.aborted&&!timedOut)throw error}finally{signal?.removeEventListener("abort",cancel);this.durationMs+=Date.now()-this.turnStartedAt;this.executing=false;this.drainPermissions();this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.flushOpenTools();this.emitter.emit("finish",{subagentId:this.id,terminateReason:this.terminateMode,rounds:this.round,totalDurationMs:this.durationMs,totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,timestamp:Date.now()})}}stopMode(reason){switch(reason){case"end_turn":return"GOAL";case"max_turn_requests":return"MAX_TURNS";case"cancelled":return"CANCELLED";case"refusal":return"ERROR";default:return"ERROR"}}get id(){return this.params.subagentId??this.params.name}getFinalText(){return this.finalText}getTerminateMode(){return this.terminateMode}getCore(){return this.coreView}setExternalMessageProvider(provider){this.provider=provider}getExecutionSummary(){return{rounds:this.round,totalDurationMs:this.durationMs+(this.executing?Date.now()-this.turnStartedAt:0),totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,successRate:this.toolCalls?this.toolSucceeded/this.toolCalls*100:0,inputTokens:0,outputTokens:0,thoughtTokens:0,cachedTokens:0,totalTokens:0,toolUsage:[]}}dispose(){this.disposed=true;this.fail(new Error("External ACP agent disposed"));return this.disposePromise??=this.child.terminate().catch(error=>{if(isUnprovenExternalAgentTreeExit(error)){const detail=error instanceof Error?error.message:String(error);debugLogger.warn(`External ACP agent process tree was not proven gone after disposal: ${detail}`);if(this.emitter.rawListeners("error").length>0){this.emitter.emit("error",{subagentId:this.id,error:`External agent process tree not proven gone after disposal: ${detail}`,timestamp:Date.now()})}return}if(!isExpectedExternalAgentCleanupExit(error))throw error})}drainPermissions(){for(const cancel of this.pendingPermissions.values())cancel();this.pendingPermissions.clear()}onSessionUpdate({sessionId,update}){if(sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted)return;switch(update.sessionUpdate){case"agent_message_chunk":case"agent_thought_chunk":{const thought=update.sessionUpdate==="agent_thought_chunk";const text=update.content.type==="text"?update.content.text:JSON.stringify(update.content);if(thought)this.thoughtText+=text;else this.finalText+=text;this.emitter.emit("stream_text",{subagentId:this.id,round:this.round,text,thought,timestamp:Date.now()});break}case"tool_call":this.updateTool(update);break;case"tool_call_update":this.updateTool(update);break;default:break}}updateTool(update){if(update._meta?.["toolLifecycle"]!==void 0&&update.status===void 0&&update.content===void 0)return;const callId=update.toolCallId;if(this.finishedTools.has(callId))return;const previous=this.tools.get(callId);const tool={toolCallId:callId,title:previous?.title??"External tool",...previous,...Object.fromEntries(Object.entries(update).filter(([,value])=>value!==null&&value!==void 0))};this.tools.set(callId,tool);const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;if(!previous){this.toolNames.set(callId,name);this.toolCalls++;this.emitter.emit("tool_call",{subagentId:this.id,round:this.round,callId,name,args:isRecord(tool.rawInput)?tool.rawInput:{input:tool.rawInput},description:tool.title,timestamp:Date.now()})}if(tool.status!=="completed"&&tool.status!=="failed")return;this.finishedTools.add(callId);this.tools.delete(callId);const success=tool.status==="completed";if(success)this.toolSucceeded++;else this.toolFailed++;this.toolNames.delete(callId);const response={input:tool.rawInput??null,toolName:reportedName,output:tool.rawOutput??null,content:tool.content??null,status:tool.status};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success,responseParts,resultDisplay:JSON.stringify(tool.rawOutput??tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}flushOpenTools(){for(const[callId,tool]of this.tools){const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;this.toolFailed++;const response={input:tool.rawInput??null,toolName:reportedName,output:null,content:tool.content??null,status:"failed"};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success:false,responseParts,resultDisplay:JSON.stringify(tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}this.tools.clear();this.toolNames.clear()}async onRequestPermission(params){const cancelled={outcome:{outcome:"cancelled"}};const runtime=this.params.runtimeContext;const callId=params.toolCall.toolCallId;const meta=params.toolCall._meta?.["claudeCode"];const name=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:params.toolCall.kind??"external_tool";if(params.sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted||this.pendingPermissions.has(callId)||params.options.length===0||new Set(params.options.map(option=>option.optionId)).size!==params.options.length)return cancelled;if(name.replaceAll("_","").toLowerCase()==="askuserquestion"||runtime.getShouldAvoidPermissionPrompts()||!runtime.isInteractive()&&!runtime.getExperimentalZedIntegration()&&runtime.getInputFormat()!=="stream-json"||this.emitter.rawListeners("tool_waiting_approval").length===0){const rejectOptionId=selectRejectOption(params.options);return rejectOptionId?{outcome:{outcome:"selected",optionId:rejectOptionId}}:cancelled}return new Promise(resolve=>{const finish=__name(optionId=>{if(this.pendingPermissions.get(callId)!==deny)return;this.pendingPermissions.delete(callId);resolve(optionId?{outcome:{outcome:"selected",optionId}}:cancelled)},"finish");const deny=__name(()=>finish(),"deny");this.pendingPermissions.set(callId,deny);try{this.emitter.emit("tool_waiting_approval",{subagentId:this.id,round:this.round,callId,name,args:isRecord(params.toolCall.rawInput)?params.toolCall.rawInput:{},description:params.toolCall.title??"External action",confirmationDetails:{type:"info",title:params.toolCall.title??"External action",prompt:describeExternalAction(params.toolCall),renderPromptAsPlainText:true,hideAlwaysAllow:true},respond:__name(async outcome=>finish(selectPermissionOption(params.options,outcome)??(outcome==="cancel"?selectRejectOption(params.options):void 0)),"respond"),timestamp:Date.now()})}catch{deny()}})}};var acpExternalAgentExecutor={create:__name(params=>AcpSubagentExecutor.create(params),"create")};export{externalModelLabel,describeExternalAction,assertExternalAgentSpawnPlatformSupported,resolvePermissionMode,selectPeerModeId,optionKindForOutcome,selectPermissionOption,selectRejectOption,isExpectedExternalAgentCleanupExit,isUnprovenExternalAgentTreeExit,acpExternalAgentExecutor};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{cancelTask,checkReadiness,cleanTask,collectTask,listTasks,retryTask,runPlan}from"./chunk-TJT2PKMI.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{loadSettings}from"./chunk-23543L6E.js";import{collectProviderModelsForProtocol,getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-56PVVXUG.js";import{normalizeProxyUrl}from"./chunk-PFKTTUGS.js";import{isTlsVerificationDisabled}from"./chunk-E5XJBLSO.js";import{ignoreBrokenPipe,writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();async function resolveProxy(cliProxy,settingsProxy){const proxyUrl=resolveProxyUrl(cliProxy,settingsProxy);if(proxyUrl){const{EnvHttpProxyAgent,setGlobalDispatcher}=await loadUndici();setGlobalDispatcher(new EnvHttpProxyAgent({httpProxy:proxyUrl,httpsProxy:proxyUrl}))}return proxyUrl}__name(resolveProxy,"resolveProxy");function resolveProxyUrl(cliProxy,settingsProxy){return normalizeProxyUrl(cliProxy||settingsProxy||process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"])}__name(resolveProxyUrl,"resolveProxyUrl");var DEFAULT_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1";function resolveEndpoint(env=process.env,options={}){let settings=options.settings??loadSettings().merged;const batch=settings.batch;if(batch?.model||batch?.authType||batch?.baseUrl){if(!batch.model?.trim()){throw new Error("Set batch.model to a modelProviders model ID.")}if(batch.authType&&batch.authType!=="openai"){throw new Error('batch.authType must be "openai" for DashScope Batch.')}const matches=collectProviderModelsForProtocol(settings.modelProviders,settings.providerProtocol,"openai").filter(provider2=>provider2.id===batch.model&&(!batch.baseUrl||provider2.baseUrl===batch.baseUrl));if(matches.length!==1){throw new Error("batch.model must match exactly one chat-completions modelProviders entry; use batch.baseUrl to disambiguate duplicate IDs.")}const provider=matches[0];if(!provider.baseUrl||!provider.envKey||!env[provider.envKey]){throw new Error("The Batch provider needs baseUrl and an envKey with a non-empty value in settings.env or the environment.")}settings={...settings,model:{name:provider.id,baseUrl:provider.baseUrl},modelProviders:{openai:[provider]},security:{auth:{selectedType:"openai"}}};env={[provider.envKey]:env[provider.envKey]}}const selectedAuthType=settings.security?.auth?.selectedType??getAuthTypeFromEnv(env);if(selectedAuthType!=="openai"){throw new Error(`qwen batch needs an API key (auth type "openai") for a DashScope endpoint; current auth type is "${selectedAuthType??"none"}".`)}const{apiKey,baseUrl,model,warnings,authType,generationConfig}=resolveCliGenerationConfig({argv:{},settings,selectedAuthType,env});if(authType!=="openai"){throw new Error(`qwen batch needs a model on the OpenAI-compatible chat-completions wire; "${model||"the configured model"}" resolves to auth type "${authType??"none"}".`)}if(!apiKey){throw new Error("No API key found: set OPENAI_API_KEY or security.auth.apiKey.")}const warn=options.warn??(message=>writeStderrLine(`warning: ${message}`));for(const warning of warnings??[]){warn(warning)}return{apiKey,baseUrl:(baseUrl||DEFAULT_BASE_URL).replace(/\/+$/,""),model,generationConfig}}__name(resolveEndpoint,"resolveEndpoint");async function prepareEndpoint(env=process.env,cliOptions={}){if(cliOptions.insecure)process.env["QWEN_TLS_INSECURE"]="1";if(isTlsVerificationDisabled()&&process.env["NODE_TLS_REJECT_UNAUTHORIZED"]!=="0"){process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0";writeStderrLine("WARNING: TLS certificate verification is disabled (--insecure / QWEN_TLS_INSECURE); connections made by this command are vulnerable to man-in-the-middle attacks.")}await resolveProxy(cliOptions.proxy,loadSettings().merged.proxy);return resolveEndpoint(env)}__name(prepareEndpoint,"prepareEndpoint");var cliOptionsOf=__name(argv=>({proxy:argv["proxy"],insecure:argv["insecure"]}),"cliOptionsOf");async function run(fn){try{await fn()}catch(error){writeStderrLine(error instanceof Error?error.message:String(error));process.exitCode=1}await Promise.all([process.stdout,process.stderr].map(stream=>new Promise(resolve=>stream.write("",()=>resolve()))))}__name(run,"run");var LOCK_WAIT_MS=15e3;var workflowDeps=__name(ep=>({ep,cwd:process.cwd(),env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS}),"workflowDeps");var runWorkflowCommand={command:"run <plan>",describe:"Run an agent-prepared batch plan: assemble requests, submit, record the task",builder:__name(yargs=>yargs.positional("plan",{describe:"Plan JSON (usually written by the /batch-api skill): shared rules + source/target items",type:"string",demandOption:true}).option("dry-run",{describe:"Assemble and show items, frozen settings and the estimate without uploading; prints a snapshot digest",type:"boolean",default:false}).option("expect",{describe:"Submit only if the batch still matches this snapshot digest from --dry-run",type:"string"}).check(argv=>argv["dry-run"]&&argv["expect"]!==void 0?"--dry-run and --expect cannot be combined":true),"builder"),handler:__name(argv=>run(async()=>{await runPlan(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["plan"],{dryRun:argv["dry-run"],expect:argv["expect"]})}),"handler")};var collectWorkflowCommand={command:"collect <task-id>",describe:"Collect a workflow task: reconcile, download, validate, and deliver results",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id printed by `qwen batch run`",type:"string",demandOption:true}).option("wait",{describe:"Poll (over HTTP, holding no lock) until the batch settles, then collect",type:"boolean",default:false}).option("timeout",{describe:"Seconds to wait with --wait before giving up (default: none)",type:"number"}).check(argv=>argv["timeout"]===void 0||Number.isFinite(argv["timeout"])&&argv["timeout"]>0?true:"--timeout must be a positive number of seconds"),"builder"),handler:__name(argv=>run(async()=>{await collectTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{wait:argv["wait"],timeoutSeconds:argv["timeout"]})}),"handler")};var retryWorkflowCommand={command:"retry <task-id>",describe:"Resubmit only the failed items of a workflow task",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("max-output-tokens",{describe:"Output limit for the new attempt; required to resend items that were truncated",type:"number"}).check(argv=>argv["max-output-tokens"]===void 0||Number.isInteger(argv["max-output-tokens"])&&argv["max-output-tokens"]>0?true:"--max-output-tokens must be a positive integer"),"builder"),handler:__name(argv=>run(async()=>{await retryTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{maxOutputTokens:argv["max-output-tokens"]})}),"handler")};var cleanWorkflowCommand={command:"clean <task-id>",describe:"Delete a workflow task's local record (cancels nothing; refuses while a batch may be running)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("force",{describe:"Delete even if a batch may still be running or uncollected (it is not cancelled)",type:"boolean",default:false}),"builder"),handler:__name(argv=>run(async()=>{await cleanTask({env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS},argv["task-id"],{force:argv["force"]})}),"handler")};var checkWorkflowCommand={command:"check",describe:"Verify credentials and the Batch route, and show the settings a run would freeze (no billed request)",builder:__name(yargs=>yargs,"builder"),handler:__name(argv=>run(async()=>{await checkReadiness(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))))}),"handler")};var cancelWorkflowCommand={command:"cancel <task-id>",describe:"Cancel a workflow task's active batch (already-completed requests are still billed)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}),"builder"),handler:__name(argv=>run(async()=>{await cancelTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"])}),"handler")};var listWorkflowCommand={command:"list",describe:"List all recorded workflow tasks with their project",builder:__name(yargs=>yargs,"builder"),handler:__name(()=>run(async()=>{ignoreBrokenPipe();await listTasks({env:process.env,out:writeStdoutLine,err:writeStderrLine})}),"handler")};var batchCommand={command:"batch",describe:"Run many independent requests through the DashScope Batch API",builder:__name(yargs=>yargs.command(runWorkflowCommand).command(collectWorkflowCommand).command(retryWorkflowCommand).command(cancelWorkflowCommand).command(listWorkflowCommand).command(checkWorkflowCommand).command(cleanWorkflowCommand).demandCommand(1,"You need at least one command before continuing.").version(false),"builder"),handler:__name(()=>{},"handler")};export{resolveProxy,resolveProxyUrl,resolveEndpoint,prepareEndpoint,listWorkflowCommand,batchCommand};
3
+ import{cancelTask,checkReadiness,cleanTask,collectTask,listTasks,retryTask,runPlan}from"./chunk-TJT2PKMI.js";import{loadUndici}from"./chunk-XKSB7VTV.js";import{loadSettings}from"./chunk-JRIVHFCG.js";import{collectProviderModelsForProtocol,getAuthTypeFromEnv,resolveCliGenerationConfig}from"./chunk-BWLMXGA2.js";import{normalizeProxyUrl}from"./chunk-POMEWCFJ.js";import{isTlsVerificationDisabled}from"./chunk-E5XJBLSO.js";import{ignoreBrokenPipe,writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();async function resolveProxy(cliProxy,settingsProxy){const proxyUrl=resolveProxyUrl(cliProxy,settingsProxy);if(proxyUrl){const{EnvHttpProxyAgent,setGlobalDispatcher}=await loadUndici();setGlobalDispatcher(new EnvHttpProxyAgent({httpProxy:proxyUrl,httpsProxy:proxyUrl}))}return proxyUrl}__name(resolveProxy,"resolveProxy");function resolveProxyUrl(cliProxy,settingsProxy){return normalizeProxyUrl(cliProxy||settingsProxy||process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"])}__name(resolveProxyUrl,"resolveProxyUrl");var DEFAULT_BASE_URL="https://dashscope.aliyuncs.com/compatible-mode/v1";function resolveEndpoint(env=process.env,options={}){let settings=options.settings??loadSettings().merged;const batch=settings.batch;if(batch?.model||batch?.authType||batch?.baseUrl){if(!batch.model?.trim()){throw new Error("Set batch.model to a modelProviders model ID.")}if(batch.authType&&batch.authType!=="openai"){throw new Error('batch.authType must be "openai" for DashScope Batch.')}const matches=collectProviderModelsForProtocol(settings.modelProviders,settings.providerProtocol,"openai").filter(provider2=>provider2.id===batch.model&&(!batch.baseUrl||provider2.baseUrl===batch.baseUrl));if(matches.length!==1){throw new Error("batch.model must match exactly one chat-completions modelProviders entry; use batch.baseUrl to disambiguate duplicate IDs.")}const provider=matches[0];if(!provider.baseUrl||!provider.envKey||!env[provider.envKey]){throw new Error("The Batch provider needs baseUrl and an envKey with a non-empty value in settings.env or the environment.")}settings={...settings,model:{name:provider.id,baseUrl:provider.baseUrl},modelProviders:{openai:[provider]},security:{auth:{selectedType:"openai"}}};env={[provider.envKey]:env[provider.envKey]}}const selectedAuthType=settings.security?.auth?.selectedType??getAuthTypeFromEnv(env);if(selectedAuthType!=="openai"){throw new Error(`qwen batch needs an API key (auth type "openai") for a DashScope endpoint; current auth type is "${selectedAuthType??"none"}".`)}const{apiKey,baseUrl,model,warnings,authType,generationConfig}=resolveCliGenerationConfig({argv:{},settings,selectedAuthType,env});if(authType!=="openai"){throw new Error(`qwen batch needs a model on the OpenAI-compatible chat-completions wire; "${model||"the configured model"}" resolves to auth type "${authType??"none"}".`)}if(!apiKey){throw new Error("No API key found: set OPENAI_API_KEY or security.auth.apiKey.")}const warn=options.warn??(message=>writeStderrLine(`warning: ${message}`));for(const warning of warnings??[]){warn(warning)}return{apiKey,baseUrl:(baseUrl||DEFAULT_BASE_URL).replace(/\/+$/,""),model,generationConfig}}__name(resolveEndpoint,"resolveEndpoint");async function prepareEndpoint(env=process.env,cliOptions={}){if(cliOptions.insecure)process.env["QWEN_TLS_INSECURE"]="1";if(isTlsVerificationDisabled()&&process.env["NODE_TLS_REJECT_UNAUTHORIZED"]!=="0"){process.env["NODE_TLS_REJECT_UNAUTHORIZED"]="0";writeStderrLine("WARNING: TLS certificate verification is disabled (--insecure / QWEN_TLS_INSECURE); connections made by this command are vulnerable to man-in-the-middle attacks.")}await resolveProxy(cliOptions.proxy,loadSettings().merged.proxy);return resolveEndpoint(env)}__name(prepareEndpoint,"prepareEndpoint");var cliOptionsOf=__name(argv=>({proxy:argv["proxy"],insecure:argv["insecure"]}),"cliOptionsOf");async function run(fn){try{await fn()}catch(error){writeStderrLine(error instanceof Error?error.message:String(error));process.exitCode=1}await Promise.all([process.stdout,process.stderr].map(stream=>new Promise(resolve=>stream.write("",()=>resolve()))))}__name(run,"run");var LOCK_WAIT_MS=15e3;var workflowDeps=__name(ep=>({ep,cwd:process.cwd(),env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS}),"workflowDeps");var runWorkflowCommand={command:"run <plan>",describe:"Run an agent-prepared batch plan: assemble requests, submit, record the task",builder:__name(yargs=>yargs.positional("plan",{describe:"Plan JSON (usually written by the /batch-api skill): shared rules + source/target items",type:"string",demandOption:true}).option("dry-run",{describe:"Assemble and show items, frozen settings and the estimate without uploading; prints a snapshot digest",type:"boolean",default:false}).option("expect",{describe:"Submit only if the batch still matches this snapshot digest from --dry-run",type:"string"}).check(argv=>argv["dry-run"]&&argv["expect"]!==void 0?"--dry-run and --expect cannot be combined":true),"builder"),handler:__name(argv=>run(async()=>{await runPlan(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["plan"],{dryRun:argv["dry-run"],expect:argv["expect"]})}),"handler")};var collectWorkflowCommand={command:"collect <task-id>",describe:"Collect a workflow task: reconcile, download, validate, and deliver results",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id printed by `qwen batch run`",type:"string",demandOption:true}).option("wait",{describe:"Poll (over HTTP, holding no lock) until the batch settles, then collect",type:"boolean",default:false}).option("timeout",{describe:"Seconds to wait with --wait before giving up (default: none)",type:"number"}).check(argv=>argv["timeout"]===void 0||Number.isFinite(argv["timeout"])&&argv["timeout"]>0?true:"--timeout must be a positive number of seconds"),"builder"),handler:__name(argv=>run(async()=>{await collectTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{wait:argv["wait"],timeoutSeconds:argv["timeout"]})}),"handler")};var retryWorkflowCommand={command:"retry <task-id>",describe:"Resubmit only the failed items of a workflow task",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("max-output-tokens",{describe:"Output limit for the new attempt; required to resend items that were truncated",type:"number"}).check(argv=>argv["max-output-tokens"]===void 0||Number.isInteger(argv["max-output-tokens"])&&argv["max-output-tokens"]>0?true:"--max-output-tokens must be a positive integer"),"builder"),handler:__name(argv=>run(async()=>{await retryTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"],{maxOutputTokens:argv["max-output-tokens"]})}),"handler")};var cleanWorkflowCommand={command:"clean <task-id>",describe:"Delete a workflow task's local record (cancels nothing; refuses while a batch may be running)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}).option("force",{describe:"Delete even if a batch may still be running or uncollected (it is not cancelled)",type:"boolean",default:false}),"builder"),handler:__name(argv=>run(async()=>{await cleanTask({env:process.env,out:writeStdoutLine,err:writeStderrLine,lockWaitMs:LOCK_WAIT_MS},argv["task-id"],{force:argv["force"]})}),"handler")};var checkWorkflowCommand={command:"check",describe:"Verify credentials and the Batch route, and show the settings a run would freeze (no billed request)",builder:__name(yargs=>yargs,"builder"),handler:__name(argv=>run(async()=>{await checkReadiness(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))))}),"handler")};var cancelWorkflowCommand={command:"cancel <task-id>",describe:"Cancel a workflow task's active batch (already-completed requests are still billed)",builder:__name(yargs=>yargs.positional("task-id",{describe:"Task id",type:"string",demandOption:true}),"builder"),handler:__name(argv=>run(async()=>{await cancelTask(workflowDeps(await prepareEndpoint(process.env,cliOptionsOf(argv))),argv["task-id"])}),"handler")};var listWorkflowCommand={command:"list",describe:"List all recorded workflow tasks with their project",builder:__name(yargs=>yargs,"builder"),handler:__name(()=>run(async()=>{ignoreBrokenPipe();await listTasks({env:process.env,out:writeStdoutLine,err:writeStderrLine})}),"handler")};var batchCommand={command:"batch",describe:"Run many independent requests through the DashScope Batch API",builder:__name(yargs=>yargs.command(runWorkflowCommand).command(collectWorkflowCommand).command(retryWorkflowCommand).command(cancelWorkflowCommand).command(listWorkflowCommand).command(checkWorkflowCommand).command(cleanWorkflowCommand).demandCommand(1,"You need at least one command before continuing.").version(false),"builder"),handler:__name(()=>{},"handler")};export{resolveProxy,resolveProxyUrl,resolveEndpoint,prepareEndpoint,listWorkflowCommand,batchCommand};
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{getWritableScopes}from"./chunk-23543L6E.js";import{publicProviderBaseUrl}from"./chunk-YQXX44YA.js";import{isImageGenerationCapable,tryResolveModelProtocol}from"./chunk-AJ75BPTA.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";function modelKey(scope,provider,model,authType){return createHash("sha256").update(JSON.stringify([scope,provider,model.id,model.baseUrl??"",authType])).digest("hex")}__name(modelKey,"modelKey");function modelEntries(loaded){const seenProviders=new Set;return["System",...getWritableScopes(loaded),"SystemDefaults"].flatMap(scope=>{const providers=loaded.forScope(scope).settings.modelProviders??{};return Object.entries(providers).flatMap(([provider,models])=>{if(seenProviders.has(provider))return[];seenProviders.add(provider);if(!Array.isArray(models))return[];return models.flatMap((model,index)=>{if(!model||typeof model!=="object"||typeof model.id!=="string"||!model.id||model.baseUrl!==void 0&&typeof model.baseUrl!=="string")return[];const authType=tryResolveModelProtocol(provider,model,loaded.merged.providerProtocol);if(!authType||authType==="qwen-oauth")return[];return[{scope,provider,authType,model,index,key:modelKey(scope,provider,model,authType)}]})})})}__name(modelEntries,"modelEntries");function findModelConfiguration(loaded,key){const matches=modelEntries(loaded).filter(entry=>entry.key===key);return matches.length===1&&getWritableScopes(loaded).includes(matches[0].scope)?matches[0]:void 0}__name(findModelConfiguration,"findModelConfiguration");function findModelConfigurationForDeletion(loaded,target){const candidates=modelEntries(loaded).filter(entry=>entry.authType===target.authType&&entry.model.id===target.modelId);const exact=candidates.filter(entry=>(entry.model.baseUrl??void 0)===target.baseUrl);const matches=target.baseUrl!==void 0&&exact.length?exact:candidates;if(matches.length===0)return void 0;return matches.length===1&&getWritableScopes(loaded).includes(matches[0].scope)?matches[0]:"ambiguous"}__name(findModelConfigurationForDeletion,"findModelConfigurationForDeletion");function getModelConfigurationKey(loaded,authType,modelId,baseUrl){const matches=modelEntries(loaded).filter(entry=>entry.authType===authType&&entry.model.id===modelId&&(entry.model.baseUrl??"")===(baseUrl??""));return matches.length===1&&getWritableScopes(loaded).includes(matches[0].scope)?matches[0].key:void 0}__name(getModelConfigurationKey,"getModelConfigurationKey");function isConversationModelConfiguration(model){return!model.imageOnly&&!model.voiceOnly&&!model.fastOnly&&!model.visionOnly&&!model.realtimeOnly}__name(isConversationModelConfiguration,"isConversationModelConfiguration");function isImageModelConfiguration(model){if(!isImageGenerationCapable(model)||model.fastOnly||model.voiceOnly||model.realtimeOnly||!model.baseUrl||typeof model.envKey!=="string"||!model.envKey.trim())return false;try{const url=new URL(model.baseUrl);return url.protocol==="https:"&&!url.username&&!url.password&&!url.search&&!url.hash}catch{return false}}__name(isImageModelConfiguration,"isImageModelConfiguration");function listModelConfigurations(loaded){const entries=modelEntries(loaded);const routeKey=__name(entry=>JSON.stringify([entry.authType,entry.model.id,entry.model.baseUrl??""]),"routeKey");const counts=new Map;for(const entry of entries){const route=routeKey(entry);counts.set(route,(counts.get(route)??0)+1)}const writableScopes=getWritableScopes(loaded);return entries.filter(entry=>writableScopes.includes(entry.scope)).map(entry=>{const{model,authType,key}=entry;const uniqueRoute=counts.get(routeKey(entry))===1;let imageModel;let advisorModel;if(uniqueRoute&&isConversationModelConfiguration(model)){if(!model.baseUrl)advisorModel=`${authType}:${model.id}\0`;else{try{const url=new URL(model.baseUrl);if(["https:","http:"].includes(url.protocol)&&!url.username&&!url.password&&!url.search&&!url.hash)advisorModel=`${authType}:${model.id}\0${model.baseUrl}`}catch{}}}if(uniqueRoute&&isImageModelConfiguration(model)){imageModel=`${authType}:${model.id}\0${model.baseUrl}`}return{key,authType,modelId:model.id,name:model.name,baseUrl:model.baseUrl?publicProviderBaseUrl(model.baseUrl):void 0,envKey:typeof model.envKey==="string"?model.envKey:void 0,contextWindowSize:typeof model.generationConfig?.contextWindowSize==="number"&&Number.isInteger(model.generationConfig.contextWindowSize)&&model.generationConfig.contextWindowSize>0?model.generationConfig.contextWindowSize:void 0,canEditContextWindow:uniqueRoute,purpose:model.imageOnly===true?"image":model.voiceOnly===true?"voice":model.realtimeOnly===true?"realtime":"chat",...imageModel?{imageModel}:{},...advisorModel?{advisorModel}:{}}})}__name(listModelConfigurations,"listModelConfigurations");function updateModelContextWindow(loaded,key,contextWindowSize,assertGenerationOpen){const match=findModelConfiguration(loaded,key);if(!match)return void 0;if(getModelConfigurationKey(loaded,match.authType,match.model.id,match.model.baseUrl)!==key)return void 0;const{scope,provider,index}=match;const providers=loaded.forScope(scope).originalSettings.modelProviders??{};const model=providers[provider][index];const generationConfig={...model.generationConfig};if(contextWindowSize===null)delete generationConfig.contextWindowSize;else generationConfig.contextWindowSize=contextWindowSize;const updated={...model,generationConfig};if(Object.keys(generationConfig).length===0)delete updated.generationConfig;loaded.setValue(scope,"modelProviders",{...providers,[provider]:providers[provider].map((entry,i)=>i===index?updated:entry)},assertGenerationOpen,{throwOnWriteFailure:true});return scope==="Workspace"?"workspace":"user"}__name(updateModelContextWindow,"updateModelContextWindow");export{findModelConfiguration,findModelConfigurationForDeletion,getModelConfigurationKey,isConversationModelConfiguration,isImageModelConfiguration,listModelConfigurations,updateModelContextWindow};
3
+ import{getWritableScopes}from"./chunk-JRIVHFCG.js";import{publicProviderBaseUrl}from"./chunk-YQXX44YA.js";import{isImageGenerationCapable,tryResolveModelProtocol}from"./chunk-OHOG4HSN.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{createHash}from"node:crypto";function modelKey(scope,provider,model,authType){return createHash("sha256").update(JSON.stringify([scope,provider,model.id,model.baseUrl??"",authType])).digest("hex")}__name(modelKey,"modelKey");function modelEntries(loaded){const seenProviders=new Set;return["System",...getWritableScopes(loaded),"SystemDefaults"].flatMap(scope=>{const providers=loaded.forScope(scope).settings.modelProviders??{};return Object.entries(providers).flatMap(([provider,models])=>{if(seenProviders.has(provider))return[];seenProviders.add(provider);if(!Array.isArray(models))return[];return models.flatMap((model,index)=>{if(!model||typeof model!=="object"||typeof model.id!=="string"||!model.id||model.baseUrl!==void 0&&typeof model.baseUrl!=="string")return[];const authType=tryResolveModelProtocol(provider,model,loaded.merged.providerProtocol);if(!authType||authType==="qwen-oauth")return[];return[{scope,provider,authType,model,index,key:modelKey(scope,provider,model,authType)}]})})})}__name(modelEntries,"modelEntries");function findModelConfiguration(loaded,key){const matches=modelEntries(loaded).filter(entry=>entry.key===key);return matches.length===1&&getWritableScopes(loaded).includes(matches[0].scope)?matches[0]:void 0}__name(findModelConfiguration,"findModelConfiguration");function findModelConfigurationForDeletion(loaded,target){const candidates=modelEntries(loaded).filter(entry=>entry.authType===target.authType&&entry.model.id===target.modelId);const exact=candidates.filter(entry=>(entry.model.baseUrl??void 0)===target.baseUrl);const matches=target.baseUrl!==void 0&&exact.length?exact:candidates;if(matches.length===0)return void 0;return matches.length===1&&getWritableScopes(loaded).includes(matches[0].scope)?matches[0]:"ambiguous"}__name(findModelConfigurationForDeletion,"findModelConfigurationForDeletion");function getModelConfigurationKey(loaded,authType,modelId,baseUrl){const matches=modelEntries(loaded).filter(entry=>entry.authType===authType&&entry.model.id===modelId&&(entry.model.baseUrl??"")===(baseUrl??""));return matches.length===1&&getWritableScopes(loaded).includes(matches[0].scope)?matches[0].key:void 0}__name(getModelConfigurationKey,"getModelConfigurationKey");function isConversationModelConfiguration(model){return!model.imageOnly&&!model.voiceOnly&&!model.fastOnly&&!model.visionOnly&&!model.realtimeOnly}__name(isConversationModelConfiguration,"isConversationModelConfiguration");function isImageModelConfiguration(model){if(!isImageGenerationCapable(model)||model.fastOnly||model.voiceOnly||model.realtimeOnly||!model.baseUrl||typeof model.envKey!=="string"||!model.envKey.trim())return false;try{const url=new URL(model.baseUrl);return url.protocol==="https:"&&!url.username&&!url.password&&!url.search&&!url.hash}catch{return false}}__name(isImageModelConfiguration,"isImageModelConfiguration");function listModelConfigurations(loaded){const entries=modelEntries(loaded);const routeKey=__name(entry=>JSON.stringify([entry.authType,entry.model.id,entry.model.baseUrl??""]),"routeKey");const counts=new Map;for(const entry of entries){const route=routeKey(entry);counts.set(route,(counts.get(route)??0)+1)}const writableScopes=getWritableScopes(loaded);return entries.filter(entry=>writableScopes.includes(entry.scope)).map(entry=>{const{model,authType,key}=entry;const uniqueRoute=counts.get(routeKey(entry))===1;let imageModel;let advisorModel;if(uniqueRoute&&isConversationModelConfiguration(model)){if(!model.baseUrl)advisorModel=`${authType}:${model.id}\0`;else{try{const url=new URL(model.baseUrl);if(["https:","http:"].includes(url.protocol)&&!url.username&&!url.password&&!url.search&&!url.hash)advisorModel=`${authType}:${model.id}\0${model.baseUrl}`}catch{}}}if(uniqueRoute&&isImageModelConfiguration(model)){imageModel=`${authType}:${model.id}\0${model.baseUrl}`}return{key,authType,modelId:model.id,name:model.name,baseUrl:model.baseUrl?publicProviderBaseUrl(model.baseUrl):void 0,envKey:typeof model.envKey==="string"?model.envKey:void 0,contextWindowSize:typeof model.generationConfig?.contextWindowSize==="number"&&Number.isInteger(model.generationConfig.contextWindowSize)&&model.generationConfig.contextWindowSize>0?model.generationConfig.contextWindowSize:void 0,canEditContextWindow:uniqueRoute,purpose:model.imageOnly===true?"image":model.voiceOnly===true?"voice":model.realtimeOnly===true?"realtime":"chat",...imageModel?{imageModel}:{},...advisorModel?{advisorModel}:{}}})}__name(listModelConfigurations,"listModelConfigurations");function updateModelContextWindow(loaded,key,contextWindowSize,assertGenerationOpen){const match=findModelConfiguration(loaded,key);if(!match)return void 0;if(getModelConfigurationKey(loaded,match.authType,match.model.id,match.model.baseUrl)!==key)return void 0;const{scope,provider,index}=match;const providers=loaded.forScope(scope).originalSettings.modelProviders??{};const model=providers[provider][index];const generationConfig={...model.generationConfig};if(contextWindowSize===null)delete generationConfig.contextWindowSize;else generationConfig.contextWindowSize=contextWindowSize;const updated={...model,generationConfig};if(Object.keys(generationConfig).length===0)delete updated.generationConfig;loaded.setValue(scope,"modelProviders",{...providers,[provider]:providers[provider].map((entry,i)=>i===index?updated:entry)},assertGenerationOpen,{throwOnWriteFailure:true});return scope==="Workspace"?"workspace":"user"}__name(updateModelContextWindow,"updateModelContextWindow");export{findModelConfiguration,findModelConfigurationForDeletion,getModelConfigurationKey,isConversationModelConfiguration,isImageModelConfiguration,listModelConfigurations,updateModelContextWindow};
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{BACKSLASH_ENTER_DETECTION_WINDOW_MS,CHAR_CODE_ESC,KITTY_CTRL_C,KITTY_KEYCODE_BACKSPACE,KITTY_KEYCODE_ENTER,KITTY_KEYCODE_NUMPAD_ENTER,KITTY_KEYCODE_TAB,KITTY_MODIFIER_BASE,KITTY_MODIFIER_EVENT_TYPES_OFFSET,MAX_KITTY_SEQUENCE_LENGTH,MODIFIER_ALT_BIT,MODIFIER_CTRL_BIT,MODIFIER_SHIFT_BIT,MODIFIER_SUPER_BIT,clipboardHasImage}from"./chunk-K7VOBDFT.js";import{require_jsx_runtime}from"./chunk-REPFZQ7R.js";import{use_stdin_default,use_stdout_default}from"./chunk-YIJNS5IJ.js";import{require_react}from"./chunk-5QKDV4CD.js";import{noteInteraction}from"./chunk-UGLQO5K7.js";import{KittySequenceOverflowEvent,logKittySequenceOverflow}from"./chunk-MJEL7DIE.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_react4=__toESM(require_react(),1);init_esbuild_shims();var import_react2=__toESM(require_react(),1);import readline from"node:readline";import{PassThrough}from"node:stream";init_esbuild_shims();var ESC="\x1B";var SGR_EVENT_PREFIX=`${ESC}[<`;var X11_EVENT_PREFIX=`${ESC}[M`;var MAX_SGR_MOUSE_SEQUENCE_LENGTH=50;var SGR_MOUSE_REGEX=/^\x1b\[<(\d+);(\d+);(\d+)([mM])/;function getEventName(buttonCode,isRelease){const isMove=(buttonCode&32)!==0;if(buttonCode===66)return"scroll-left";if(buttonCode===67)return"scroll-right";if((buttonCode&64)===64){return(buttonCode&1)===0?"scroll-up":"scroll-down"}if(isMove)return"move";const button=buttonCode&3;const type=isRelease?"release":"press";switch(button){case 0:return`left-${type}`;case 1:return`middle-${type}`;case 2:return`right-${type}`;default:return null}}__name(getEventName,"getEventName");function buttonFromCode(code){switch(code&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}__name(buttonFromCode,"buttonFromCode");function parseSGRMouseEvent(buffer){const match=buffer.match(SGR_MOUSE_REGEX);if(!match)return null;const buttonCode=parseInt(match[1],10);const col=parseInt(match[2],10);const row=parseInt(match[3],10);const isRelease=match[4]==="m";const name=getEventName(buttonCode,isRelease);if(!name)return null;return{event:{name,col,row,shift:(buttonCode&4)!==0,meta:(buttonCode&8)!==0,ctrl:(buttonCode&16)!==0,button:buttonFromCode(buttonCode)},length:match[0].length}}__name(parseSGRMouseEvent,"parseSGRMouseEvent");var ENABLE_SGR_MOUSE={button:"\x1B[?1002h\x1B[?1006h",any:"\x1B[?1003h\x1B[?1006h"};var DISABLE_SGR_MOUSE={button:"\x1B[?1006l\x1B[?1002l",any:"\x1B[?1006l\x1B[?1003l"};function enableMouseEvents(stdout,tracking="button"){stdout.write(ENABLE_SGR_MOUSE[tracking])}__name(enableMouseEvents,"enableMouseEvents");function disableMouseEvents(stdout,tracking="button"){stdout.write(DISABLE_SGR_MOUSE[tracking])}__name(disableMouseEvents,"disableMouseEvents");init_esbuild_shims();var import_react=__toESM(require_react(),1);var ENABLE_FOCUS_REPORTING="\x1B[?1004h";var DISABLE_FOCUS_REPORTING="\x1B[?1004l";var FOCUS_IN="\x1B[I";var FOCUS_OUT="\x1B[O";var useFocus=__name(()=>{const{stdin}=use_stdin_default();const{stdout}=use_stdout_default();const[isFocused,setIsFocused]=(0,import_react.useState)(true);(0,import_react.useEffect)(()=>{const handleData=__name(data=>{const sequence=data.toString();const lastFocusIn=sequence.lastIndexOf(FOCUS_IN);const lastFocusOut=sequence.lastIndexOf(FOCUS_OUT);if(lastFocusIn>lastFocusOut){setIsFocused(true)}else if(lastFocusOut>lastFocusIn){setIsFocused(false)}},"handleData");stdout?.write(ENABLE_FOCUS_REPORTING);stdin?.on("data",handleData);return()=>{stdout?.write(DISABLE_FOCUS_REPORTING);stdin?.removeListener("data",handleData)}},[stdin,stdout]);useKeypress(_=>{if(!isFocused){setIsFocused(true)}},{isActive:true});return isFocused},"useFocus");var import_jsx_runtime=__toESM(require_jsx_runtime(),1);var ESC2="\x1B";var OPTION_COMPOSED_GLYPHS={"\u2020":"t","\u221A":"v"};var PASTE_MODE_PREFIX=`${ESC2}[200~`;var PASTE_MODE_SUFFIX=`${ESC2}[201~`;var KITTY_SEQUENCE_TIMEOUT_MS=200;var PASTE_IDLE_TIMEOUT_MS=1e3;var KITTY_KEYPAD_PRINTABLE_KEYCODE_TO_CHAR={57399:"0",57400:"1",57401:"2",57402:"3",57403:"4",57404:"5",57405:"6",57406:"7",57407:"8",57408:"9",57409:".",57410:"/",57411:"*",57412:"-",57413:"+",57415:"=",57416:","};var KITTY_KEYPAD_FUNCTIONAL_KEYCODE_TO_NAME={57417:"left",57418:"right",57419:"up",57420:"down",57421:"pageup",57422:"pagedown",57423:"home",57424:"end",57425:"insert",57426:"delete"};var KeypressContext=(0,import_react2.createContext)(void 0);var debugLogger=createDebugLogger("KEYPRESS");function useKeypressContext(){const context=(0,import_react2.useContext)(KeypressContext);if(!context){throw new Error("useKeypressContext must be used within a KeypressProvider")}return context}__name(useKeypressContext,"useKeypressContext");function KeypressProvider({children,kittyProtocolEnabled,pasteWorkaround=false,config,debugKeystrokeLogging,initialCapturedInput}){const{stdin,setRawMode}=use_stdin_default();const subscribers=(0,import_react2.useRef)(new Set).current;const mouseSubscribers=(0,import_react2.useRef)(new Set).current;const[pasteProgress,setPasteProgress]=(0,import_react2.useState)({active:false,receivedBytes:0});const subscribe=(0,import_react2.useCallback)(handler=>{subscribers.add(handler)},[subscribers]);const unsubscribe=(0,import_react2.useCallback)(handler=>{subscribers.delete(handler)},[subscribers]);const subscribeMouse=(0,import_react2.useCallback)(handler=>{mouseSubscribers.add(handler)},[mouseSubscribers]);const unsubscribeMouse=(0,import_react2.useCallback)(handler=>{mouseSubscribers.delete(handler)},[mouseSubscribers]);(0,import_react2.useEffect)(()=>{setRawMode(true);const capturedInput=initialCapturedInput??Buffer.alloc(0);const keypressStream=new PassThrough;let usePassthrough=false;if(pasteWorkaround){usePassthrough=true}let isPaste=false;let pasteChunks=[];let pasteAlreadyFlushed=false;let pasteIdleTimeout=null;let lastPasteChunkAt=0;const kittySequenceBufferRef={current:""};let kittySequenceTimeout=null;let backslashTimeout=null;let waitingForEnterAfterBackslash=false;let rawDataBuffer=Buffer.alloc(0);let rawFlushTimeout=null;let swallowingSgrMouse=false;let sgrMouseBuffer="";let sgrMouseTimeout=null;const resetSgrMouse=__name(()=>{swallowingSgrMouse=false;sgrMouseBuffer="";if(sgrMouseTimeout){clearTimeout(sgrMouseTimeout);sgrMouseTimeout=null}},"resetSgrMouse");const updateKittyBuffer=__name(value=>{kittySequenceBufferRef.current=value},"updateKittyBuffer");const clearKittyTimeout=__name(()=>{if(kittySequenceTimeout){clearTimeout(kittySequenceTimeout);kittySequenceTimeout=null}},"clearKittyTimeout");const startKittyTimeout=__name(()=>{clearKittyTimeout();kittySequenceTimeout=setTimeout(()=>{if(kittySequenceBufferRef.current){while(kittySequenceBufferRef.current){const parsed=parseKittyPrefix(kittySequenceBufferRef.current);if(parsed){kittySequenceBufferRef.current=kittySequenceBufferRef.current.slice(parsed.length);broadcast(parsed.key);continue}const plain=parsePlainTextPrefix(kittySequenceBufferRef.current);if(plain){kittySequenceBufferRef.current=kittySequenceBufferRef.current.slice(plain.length);broadcast(plain.key);continue}break}if(kittySequenceBufferRef.current){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer timeout, clearing:",kittySequenceBufferRef.current)}kittySequenceBufferRef.current=""}}},KITTY_SEQUENCE_TIMEOUT_MS)},"startKittyTimeout");const clearKittyBufferAndTimeout=__name(()=>{clearKittyTimeout();kittySequenceBufferRef.current=""},"clearKittyBufferAndTimeout");const clearPasteIdleTimeout=__name(()=>{if(pasteIdleTimeout){clearTimeout(pasteIdleTimeout);pasteIdleTimeout=null}},"clearPasteIdleTimeout");const forceFlushStuckPaste=__name(()=>{clearPasteIdleTimeout();if(!isPaste&&pasteChunks.length===0)return;const buffered=pasteChunks.join("");isPaste=false;pasteChunks=[];pasteAlreadyFlushed=true;if(buffered.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:buffered})}},"forceFlushStuckPaste");const onPasteIdleTimeout=__name(()=>{const idleFor=Date.now()-lastPasteChunkAt;if(idleFor>=PASTE_IDLE_TIMEOUT_MS){forceFlushStuckPaste()}else{pasteIdleTimeout=setTimeout(onPasteIdleTimeout,PASTE_IDLE_TIMEOUT_MS-idleFor)}},"onPasteIdleTimeout");const startPasteIdleTimeout=__name(()=>{lastPasteChunkAt=Date.now();if(pasteIdleTimeout)return;pasteIdleTimeout=setTimeout(onPasteIdleTimeout,PASTE_IDLE_TIMEOUT_MS)},"startPasteIdleTimeout");const createPrintableKey=__name(char=>{const printableName=char===" "?"space":/^[A-Za-z]$/.test(char)?char.toLowerCase():char;return{name:printableName,ctrl:false,meta:false,shift:false,paste:false,sequence:char,kittyProtocol:true}},"createPrintableKey");const parseKittyPrefix=__name(buffer=>{const revTabLegacy=new RegExp(`^${ESC2}\\[Z`);let m=buffer.match(revTabLegacy);if(m){return{key:{name:"tab",ctrl:false,meta:false,shift:true,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}const revTabParam=new RegExp(`^${ESC2}\\[1;(\\d+)Z`);m=buffer.match(revTabParam);if(m){let mods=parseInt(m[1],10);if(mods>=KITTY_MODIFIER_EVENT_TYPES_OFFSET){mods-=KITTY_MODIFIER_EVENT_TYPES_OFFSET}const bits=mods-KITTY_MODIFIER_BASE;const alt=(bits&MODIFIER_ALT_BIT)===MODIFIER_ALT_BIT||(bits&MODIFIER_SUPER_BIT)===MODIFIER_SUPER_BIT;const ctrl=(bits&MODIFIER_CTRL_BIT)===MODIFIER_CTRL_BIT;return{key:{name:"tab",ctrl,meta:alt,shift:true,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}const arrowPrefix=new RegExp(`^${ESC2}\\[1;(\\d+)([ABCDHFPQSR])`);m=buffer.match(arrowPrefix);if(m){let mods=parseInt(m[1],10);if(mods>=KITTY_MODIFIER_EVENT_TYPES_OFFSET){mods-=KITTY_MODIFIER_EVENT_TYPES_OFFSET}const bits=mods-KITTY_MODIFIER_BASE;const shift=(bits&MODIFIER_SHIFT_BIT)===MODIFIER_SHIFT_BIT;const alt=(bits&MODIFIER_ALT_BIT)===MODIFIER_ALT_BIT||(bits&MODIFIER_SUPER_BIT)===MODIFIER_SUPER_BIT;const ctrl=(bits&MODIFIER_CTRL_BIT)===MODIFIER_CTRL_BIT;const sym=m[2];const symbolToName={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"};const name=symbolToName[sym]||"";if(!name)return null;return{key:{name,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}const csiUPrefix=new RegExp(`^${ESC2}\\[(\\d+)(?::\\d+)*(?:;(\\d+)(?::\\d+)*)?(?:;(\\d+))?([u~])`);m=buffer.match(csiUPrefix);if(m){let keyCode=parseInt(m[1],10);let modifiers=m[2]?parseInt(m[2],10):KITTY_MODIFIER_BASE;if(modifiers>=KITTY_MODIFIER_EVENT_TYPES_OFFSET){modifiers-=KITTY_MODIFIER_EVENT_TYPES_OFFSET}const modifierBits=modifiers-KITTY_MODIFIER_BASE;const shift=(modifierBits&MODIFIER_SHIFT_BIT)===MODIFIER_SHIFT_BIT;const alt=(modifierBits&MODIFIER_ALT_BIT)===MODIFIER_ALT_BIT||(modifierBits&MODIFIER_SUPER_BIT)===MODIFIER_SUPER_BIT;const ctrl=(modifierBits&MODIFIER_CTRL_BIT)===MODIFIER_CTRL_BIT;const terminator=m[4];if(keyCode===CHAR_CODE_ESC&&terminator==="~"&&m[3]){keyCode=parseInt(m[3],10)}if(terminator==="~"){let name2=null;switch(keyCode){case 1:name2="home";break;case 2:name2="insert";break;case 3:name2="delete";break;case 4:name2="end";break;case 5:name2="pageup";break;case 6:name2="pagedown";break;default:break}if(name2){return{key:{name:name2,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}}const kittyKeyCodeToName={[CHAR_CODE_ESC]:"escape",[KITTY_KEYCODE_TAB]:"tab",[KITTY_KEYCODE_BACKSPACE]:"backspace",[KITTY_KEYCODE_ENTER]:"return",[KITTY_KEYCODE_NUMPAD_ENTER]:"return"};const name=kittyKeyCodeToName[keyCode];if(name){return{key:{name,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}if(!ctrl){const keypadChar=KITTY_KEYPAD_PRINTABLE_KEYCODE_TO_CHAR[keyCode];if(keypadChar){return{key:{name:keypadChar,ctrl:false,meta:alt,shift,paste:false,sequence:keypadChar,kittyProtocol:true},length:m[0].length}}}const keypadName=KITTY_KEYPAD_FUNCTIONAL_KEYCODE_TO_NAME[keyCode];if(keypadName){return{key:{name:keypadName,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}if(terminator==="u"&&!ctrl&&keyCode>=32&&keyCode!==127&&keyCode<=1114111&&!(keyCode>=57344&&keyCode<=63743)){return{key:{...createPrintableKey(String.fromCodePoint(keyCode)),meta:alt,shift},length:m[0].length}}if(ctrl&&keyCode>="a".charCodeAt(0)&&keyCode<="z".charCodeAt(0)){const letter=String.fromCharCode(keyCode);return{key:{name:letter,ctrl:true,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}}const legacyFuncKey=new RegExp(`^${ESC2}\\[([ABCDHF])`);m=buffer.match(legacyFuncKey);if(m){const sym=m[1];const nameMap={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end"};const name=nameMap[sym];return{key:{name,ctrl:false,meta:false,shift:false,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}return null},"parseKittyPrefix");const getCompleteCsiSequenceLength=__name(buffer=>{if(!buffer.startsWith(`${ESC2}[`)){return null}for(let i=2;i<buffer.length;i++){const code=buffer.charCodeAt(i);if(code>=64&&code<=126){return i+1}if(code<32||code>63){return 0}}return null},"getCompleteCsiSequenceLength");const parsePlainTextPrefix=__name(buffer=>{if(!buffer||buffer.startsWith(ESC2)){return null}const[char]=Array.from(buffer);if(!char){return null}return{key:createPrintableKey(char),length:char.length}},"parsePlainTextPrefix");const broadcast=__name(key=>{noteInteraction();for(const handler of subscribers){handler(key)}},"broadcast");const TERMINAL_RESPONSE_RE=/^\x1b\[[?>][\d;]*[uc]$/;const handleKeypress=__name(async(_,key)=>{if(TERMINAL_RESPONSE_RE.test(key.sequence)){return}if(key.sequence===FOCUS_IN||key.sequence===FOCUS_OUT){return}if(isPaste){resetSgrMouse()}else if(swallowingSgrMouse){if(key.ctrl&&key.name==="c"){resetSgrMouse()}else if(key.name==="paste-start"){resetSgrMouse()}else{sgrMouseBuffer+=key.sequence;if(key.name==="m"||key.sequence==="M"){swallowingSgrMouse=false;if(sgrMouseTimeout){clearTimeout(sgrMouseTimeout);sgrMouseTimeout=null}const parsed=parseSGRMouseEvent(sgrMouseBuffer);if(parsed){for(const handler of mouseSubscribers){handler(parsed.event)}}sgrMouseBuffer=""}else if(sgrMouseBuffer.length>=MAX_SGR_MOUSE_SEQUENCE_LENGTH){resetSgrMouse()}return}}if(!isPaste&&key.sequence===`${ESC2}[<`){swallowingSgrMouse=true;sgrMouseBuffer=`${ESC2}[<`;if(sgrMouseTimeout){clearTimeout(sgrMouseTimeout)}sgrMouseTimeout=setTimeout(()=>{swallowingSgrMouse=false;sgrMouseBuffer="";sgrMouseTimeout=null},KITTY_SEQUENCE_TIMEOUT_MS);return}const isCtrlCKey=key.ctrl&&key.name==="c"||key.sequence===`${ESC2}${KITTY_CTRL_C}`;if(isCtrlCKey){if(isPaste||pasteChunks.length>0){isPaste=false;pasteChunks=[];pasteAlreadyFlushed=true;clearPasteIdleTimeout()}if(kittySequenceBufferRef.current&&debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer cleared on Ctrl+C:",kittySequenceBufferRef.current)}clearKittyBufferAndTimeout();if(key.sequence===`${ESC2}${KITTY_CTRL_C}`){broadcast({name:"c",ctrl:true,meta:false,shift:false,paste:false,sequence:key.sequence,kittyProtocol:true})}else{broadcast(key)}return}if(key.name==="paste-start"){isPaste=true;pasteAlreadyFlushed=false;startPasteIdleTimeout();return}if(key.name==="paste-end"){clearPasteIdleTimeout();if(pasteAlreadyFlushed){pasteAlreadyFlushed=false;isPaste=false;pasteChunks=[];return}isPaste=false;const buffered=pasteChunks.join("");pasteChunks=[];if(buffered.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:buffered})}else{let clipboardImageUnavailable=false;const hasImage=await clipboardHasImage(()=>{clipboardImageUnavailable=true});broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,pasteImage:hasImage,clipboardImageUnavailable,sequence:buffered})}return}if(isPaste){pasteChunks.push(key.sequence);startPasteIdleTimeout();return}if(key.name==="return"&&waitingForEnterAfterBackslash){if(backslashTimeout){clearTimeout(backslashTimeout);backslashTimeout=null}waitingForEnterAfterBackslash=false;broadcast({...key,shift:true,sequence:"\r"});return}if(key.sequence==="\\"&&!key.name){waitingForEnterAfterBackslash=true;backslashTimeout=setTimeout(()=>{waitingForEnterAfterBackslash=false;backslashTimeout=null;broadcast(key)},BACKSLASH_ENTER_DETECTION_WINDOW_MS);return}if(waitingForEnterAfterBackslash&&key.name!=="return"){if(backslashTimeout){clearTimeout(backslashTimeout);backslashTimeout=null}waitingForEnterAfterBackslash=false;broadcast({name:"",sequence:"\\",ctrl:false,meta:false,shift:false,paste:false})}if(["up","down","left","right"].includes(key.name)){broadcast(key);return}const isModifyOtherKeysSequence=key.sequence?.startsWith(`${ESC2}[27`)??false;if(kittyProtocolEnabled||kittySequenceBufferRef.current||isModifyOtherKeysSequence){if(kittySequenceBufferRef.current||key.sequence.startsWith(`${ESC2}[`)&&!key.sequence.startsWith(PASTE_MODE_PREFIX)&&!key.sequence.startsWith(PASTE_MODE_SUFFIX)&&!key.sequence.startsWith(FOCUS_IN)&&!key.sequence.startsWith(FOCUS_OUT)){updateKittyBuffer(kittySequenceBufferRef.current+key.sequence);startKittyTimeout();if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer accumulating:",kittySequenceBufferRef.current)}let bufferedInputHandled=false;while(kittySequenceBufferRef.current){const parsed=parseKittyPrefix(kittySequenceBufferRef.current);if(parsed){if(debugKeystrokeLogging){const parsedSequence=kittySequenceBufferRef.current.slice(0,parsed.length);if(kittySequenceBufferRef.current.length>parsed.length){debugLogger.debug("[DEBUG] Kitty sequence parsed successfully (prefix):",parsedSequence)}else{debugLogger.debug("[DEBUG] Kitty sequence parsed successfully:",parsedSequence)}}updateKittyBuffer(kittySequenceBufferRef.current.slice(parsed.length));if(!kittySequenceBufferRef.current){clearKittyTimeout()}broadcast(parsed.key);bufferedInputHandled=true;continue}const completeUnsupportedCsiLength=getCompleteCsiSequenceLength(kittySequenceBufferRef.current);if(completeUnsupportedCsiLength){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Dropping unsupported complete CSI sequence:",kittySequenceBufferRef.current.slice(0,completeUnsupportedCsiLength))}updateKittyBuffer(kittySequenceBufferRef.current.slice(completeUnsupportedCsiLength));if(!kittySequenceBufferRef.current){clearKittyTimeout()}bufferedInputHandled=true;continue}const plainTextPrefix=parsePlainTextPrefix(kittySequenceBufferRef.current);if(plainTextPrefix){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Recovered plain text after kitty sequence:",plainTextPrefix.key.sequence)}updateKittyBuffer(kittySequenceBufferRef.current.slice(plainTextPrefix.length));if(!kittySequenceBufferRef.current){clearKittyTimeout()}broadcast(plainTextPrefix.key);bufferedInputHandled=true;continue}const nextStart=kittySequenceBufferRef.current.indexOf(`${ESC2}[`,1);if(nextStart>0){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Skipping incomplete/invalid CSI prefix:",kittySequenceBufferRef.current.slice(0,nextStart))}updateKittyBuffer(kittySequenceBufferRef.current.slice(nextStart));if(!kittySequenceBufferRef.current){clearKittyTimeout()}bufferedInputHandled=true;continue}break}if(bufferedInputHandled)return;if(config?.getDebugMode()||debugKeystrokeLogging){const codes=Array.from(kittySequenceBufferRef.current).map(ch=>ch.charCodeAt(0));debugLogger.warn("Kitty sequence buffer has char codes:",codes)}if(kittySequenceBufferRef.current.length>MAX_KITTY_SEQUENCE_LENGTH){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer overflow, clearing:",kittySequenceBufferRef.current)}if(config){const event=new KittySequenceOverflowEvent(kittySequenceBufferRef.current.length,kittySequenceBufferRef.current);logKittySequenceOverflow(config,event)}clearKittyBufferAndTimeout()}else{return}}}if(key.name==="return"&&key.sequence===`${ESC2}\r`){key.meta=true}const composedKeyName=Object.hasOwn(OPTION_COMPOSED_GLYPHS,key.sequence)?OPTION_COMPOSED_GLYPHS[key.sequence]:void 0;if(process.platform==="darwin"&&!isPaste&&composedKeyName){key.name=composedKeyName;key.meta=true}broadcast({...key,paste:isPaste})},"handleKeypress");const clearRawFlushTimeout=__name(()=>{if(rawFlushTimeout){clearTimeout(rawFlushTimeout);rawFlushTimeout=null}},"clearRawFlushTimeout");const createPasteKeyEvent=__name((name="",sequence="")=>({name,ctrl:false,meta:false,shift:false,paste:false,sequence}),"createPasteKeyEvent");const shouldFlushRawDataAsPaste=__name(data=>{if(data.includes(27))return false;const hasReturn=data.includes(13);const hasEmbeddedTab=data.length>1&&data.includes(9);const isSingleReturn=data.length<=2&&hasReturn;return!isSingleReturn&&(hasReturn||hasEmbeddedTab)},"shouldFlushRawDataAsPaste");const flushRawBuffer=__name(()=>{if(!rawDataBuffer.length){return}const pasteModePrefixBuffer=Buffer.from(PASTE_MODE_PREFIX);const pasteModeSuffixBuffer=Buffer.from(PASTE_MODE_SUFFIX);const data=rawDataBuffer;let cursor=0;while(cursor<data.length){const prefixPos=data.indexOf(pasteModePrefixBuffer,cursor);const suffixPos=data.indexOf(pasteModeSuffixBuffer,cursor);const hasPrefix=prefixPos!==-1&&prefixPos+pasteModePrefixBuffer.length<=data.length;const hasSuffix=suffixPos!==-1&&suffixPos+pasteModeSuffixBuffer.length<=data.length;let markerPos=-1;let markerLength=0;let markerType=null;if(hasPrefix&&(!hasSuffix||prefixPos<suffixPos)){markerPos=prefixPos;markerLength=pasteModePrefixBuffer.length;markerType="prefix"}else if(hasSuffix){markerPos=suffixPos;markerLength=pasteModeSuffixBuffer.length;markerType="suffix"}if(markerPos===-1){break}const nextData=data.slice(cursor,markerPos);if(nextData.length>0){keypressStream.write(nextData)}if(markerType==="prefix"){handleKeypress(void 0,createPasteKeyEvent("paste-start"))}else if(markerType==="suffix"){handleKeypress(void 0,createPasteKeyEvent("paste-end"))}cursor=markerPos+markerLength}rawDataBuffer=data.slice(cursor);if(rawDataBuffer.length===0){return}if(isPaste||!shouldFlushRawDataAsPaste(rawDataBuffer)){keypressStream.write(rawDataBuffer)}else{handleKeypress(void 0,createPasteKeyEvent("paste-start"));keypressStream.write(rawDataBuffer);handleKeypress(void 0,createPasteKeyEvent("paste-end"))}rawDataBuffer=Buffer.alloc(0);clearRawFlushTimeout()},"flushRawBuffer");const handleRawKeypress=__name(_data=>{const data=Buffer.isBuffer(_data)?_data:Buffer.from(_data,"utf8");rawDataBuffer=Buffer.concat([rawDataBuffer,data]);clearRawFlushTimeout();const isReturnChar=rawDataBuffer.length<=2&&rawDataBuffer.includes(13);if(isReturnChar){rawFlushTimeout=setTimeout(flushRawBuffer,100)}else{flushRawBuffer()}},"handleRawKeypress");const pasteModePrefixBuf=Buffer.from(PASTE_MODE_PREFIX);const pasteModeSuffixBuf=Buffer.from(PASTE_MODE_SUFFIX);function partialMarkerTailLength(chunk,marker,minLen=2){const maxCheck=Math.min(chunk.length,marker.length-1);for(let len=maxCheck;len>=minLen;len--){const tail=chunk.subarray(chunk.length-len);if(marker.subarray(0,len).equals(tail)){return len}}return 0}__name(partialMarkerTailLength,"partialMarkerTailLength");let rawStdinTail=Buffer.alloc(0);let rawPasteAccumulating=false;let rawPasteChunks=[];let rawPasteReceivedBytes=0;let rawPasteIdleTimeout=null;const clearRawPasteIdleTimeout=__name(()=>{if(rawPasteIdleTimeout){clearTimeout(rawPasteIdleTimeout);rawPasteIdleTimeout=null}},"clearRawPasteIdleTimeout");const forceFlushRawPaste=__name(()=>{clearRawPasteIdleTimeout();if(!rawPasteAccumulating&&rawPasteChunks.length===0&&rawStdinTail.length===0)return;if(rawStdinTail.length>0){rawPasteChunks.push(rawStdinTail);rawStdinTail=Buffer.alloc(0)}const content=Buffer.concat(rawPasteChunks);rawPasteChunks=[];rawPasteAccumulating=false;broadcastPasteFromRaw(content)},"forceFlushRawPaste");const startRawPasteIdleTimeout=__name(()=>{clearRawPasteIdleTimeout();rawPasteIdleTimeout=setTimeout(forceFlushRawPaste,PASTE_IDLE_TIMEOUT_MS)},"startRawPasteIdleTimeout");const broadcastPasteFromRaw=__name(content=>{pasteAlreadyFlushed=true;setPasteProgress({active:false,receivedBytes:0});const text=content.toString("utf-8");if(text.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:text})}else{let clipboardImageUnavailable=false;void clipboardHasImage(()=>{clipboardImageUnavailable=true}).then(hasImage=>{broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,pasteImage:hasImage,clipboardImageUnavailable,sequence:""})})}},"broadcastPasteFromRaw");const handleStdinData=__name(data=>{const raw=Buffer.isBuffer(data)?data:Buffer.from(data,"utf8");const buf=rawStdinTail.length>0?Buffer.concat([rawStdinTail,raw]):raw;rawStdinTail=Buffer.alloc(0);let cursor=0;while(cursor<buf.length){if(rawPasteAccumulating){const suffixIdx=buf.indexOf(pasteModeSuffixBuf,cursor);if(suffixIdx===-1){const remaining=buf.subarray(cursor);const tailLen=partialMarkerTailLength(remaining,pasteModeSuffixBuf,1);const contentEnd=remaining.length-tailLen;if(contentEnd>0){const chunk=remaining.subarray(0,contentEnd);rawPasteChunks.push(chunk);rawPasteReceivedBytes+=chunk.length;setPasteProgress(prev=>({...prev,receivedBytes:rawPasteReceivedBytes}))}if(tailLen>0){rawStdinTail=Buffer.from(remaining.subarray(contentEnd))}startRawPasteIdleTimeout();cursor=buf.length}else{clearRawPasteIdleTimeout();if(suffixIdx>cursor){rawPasteChunks.push(buf.subarray(cursor,suffixIdx))}const pasteContent=Buffer.concat(rawPasteChunks);rawPasteChunks=[];rawPasteAccumulating=false;broadcastPasteFromRaw(pasteContent);cursor=suffixIdx+pasteModeSuffixBuf.length}}else{const prefixIdx=buf.indexOf(pasteModePrefixBuf,cursor);if(prefixIdx===-1){const remaining=buf.subarray(cursor);if(remaining.length>0){const tailLen=partialMarkerTailLength(remaining,pasteModePrefixBuf);if(tailLen>0){const safe=remaining.subarray(0,remaining.length-tailLen);if(safe.length>0)keypressStream.write(safe);rawStdinTail=Buffer.from(remaining.subarray(remaining.length-tailLen))}else{keypressStream.write(remaining)}}cursor=buf.length}else{if(prefixIdx>cursor){keypressStream.write(buf.subarray(cursor,prefixIdx))}rawPasteAccumulating=true;rawPasteChunks=[];rawPasteReceivedBytes=0;startRawPasteIdleTimeout();setPasteProgress({active:true,receivedBytes:0});cursor=prefixIdx+pasteModePrefixBuf.length}}}},"handleStdinData");let rl;if(usePassthrough){rl=readline.createInterface({input:keypressStream,escapeCodeTimeout:0});readline.emitKeypressEvents(keypressStream,rl);keypressStream.on("keypress",handleKeypress);stdin.on("data",handleRawKeypress)}else{rl=readline.createInterface({input:keypressStream,escapeCodeTimeout:0});readline.emitKeypressEvents(keypressStream,rl);keypressStream.on("keypress",handleKeypress);stdin.on("keypress",handleKeypress);stdin.on("data",handleStdinData)}let replayPending=false;if(capturedInput.length>0){debugLogger.debug(`Replaying ${capturedInput.length} bytes of captured input`);replayPending=true;setImmediate(()=>{if(!replayPending)return;try{stdin.emit("data",capturedInput)}catch(err){debugLogger.error("Failed to replay captured input:",err)}})}return()=>{replayPending=false;if(usePassthrough){keypressStream.removeListener("keypress",handleKeypress);stdin.removeListener("data",handleRawKeypress)}else{keypressStream.removeListener("keypress",handleKeypress);stdin.removeListener("keypress",handleKeypress);stdin.removeListener("data",handleStdinData)}rl.close();setRawMode(false);if(backslashTimeout){clearTimeout(backslashTimeout);backslashTimeout=null}clearKittyBufferAndTimeout();clearPasteIdleTimeout();clearRawPasteIdleTimeout();resetSgrMouse();if(rawFlushTimeout){clearTimeout(rawFlushTimeout);rawFlushTimeout=null}if(rawPasteAccumulating||rawPasteChunks.length>0){forceFlushRawPaste()}else if(isPaste){const buffered=pasteChunks.join("");if(buffered.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:buffered})}pasteChunks=[]}}},[stdin,setRawMode,kittyProtocolEnabled,debugKeystrokeLogging,pasteWorkaround,config,subscribers,mouseSubscribers,initialCapturedInput]);return(0,import_jsx_runtime.jsx)(KeypressContext.Provider,{value:{subscribe,unsubscribe,subscribeMouse,unsubscribeMouse,pasteWorkaround,pasteProgress},children})}__name(KeypressProvider,"KeypressProvider");init_esbuild_shims();var import_react3=__toESM(require_react(),1);var import_jsx_runtime2=__toESM(require_jsx_runtime(),1);var ContextMenuContext=(0,import_react3.createContext)({menu:null,isMenuOpen:__name(()=>false,"isMenuOpen"),selectedIndex:0,openMenu:__name(()=>{},"openMenu"),closeMenu:__name(()=>{},"closeMenu"),setSelectedIndex:__name(()=>{},"setSelectedIndex"),executeIndex:__name(()=>{},"executeIndex")});var ContextMenuProvider=__name(({children,onMenuChange})=>{const[menu,setMenu]=(0,import_react3.useState)(null);const[selectedIndex,setSelectedIndexState]=(0,import_react3.useState)(0);const menuRef=(0,import_react3.useRef)(null);menuRef.current=menu;const isMenuOpen=(0,import_react3.useCallback)(()=>menuRef.current!==null,[]);const openMenu=(0,import_react3.useCallback)((items,position)=>{if(items.length===0)return;menuRef.current={items,position};onMenuChange?.(true);setMenu(menuRef.current);setSelectedIndexState(0)},[onMenuChange]);const closeMenu=(0,import_react3.useCallback)(()=>{menuRef.current=null;setMenu(null)},[]);(0,import_react3.useEffect)(()=>{onMenuChange?.(menu!==null)},[menu,onMenuChange]);const setSelectedIndex=(0,import_react3.useCallback)(index=>{setSelectedIndexState(index)},[]);const executeIndex=(0,import_react3.useCallback)(index=>{const current=menuRef.current;menuRef.current=null;setMenu(null);current?.items[index]?.onSelect()},[]);const value=(0,import_react3.useMemo)(()=>({menu,isMenuOpen,selectedIndex,openMenu,closeMenu,setSelectedIndex,executeIndex}),[menu,isMenuOpen,selectedIndex,openMenu,closeMenu,setSelectedIndex,executeIndex]);return(0,import_jsx_runtime2.jsx)(ContextMenuContext.Provider,{value,children})},"ContextMenuProvider");function useContextMenu(){return(0,import_react3.useContext)(ContextMenuContext)}__name(useContextMenu,"useContextMenu");function contextMenuSize(items){const longest=items.reduce((max,item)=>Math.max(max,item.label.length),0);return{width:longest+4,height:items.length+2}}__name(contextMenuSize,"contextMenuSize");function clampMenuPosition(desired,size,terminalColumns,terminalRows){return{x:Math.max(0,Math.min(desired.x,terminalColumns-size.width)),y:Math.max(0,Math.min(desired.y,terminalRows-size.height))}}__name(clampMenuPosition,"clampMenuPosition");function useKeypress(onKeypress,{isActive}){const{subscribe,unsubscribe}=useKeypressContext();const{menu,isMenuOpen}=useContextMenu();const onKeypressRef=(0,import_react4.useRef)(onKeypress);onKeypressRef.current=key=>{if(menu===null&&isMenuOpen())return;onKeypress(key)};const handleKeypress=(0,import_react4.useCallback)(key=>{onKeypressRef.current(key)},[]);(0,import_react4.useEffect)(()=>{if(!isActive){return}subscribe(handleKeypress);return()=>{unsubscribe(handleKeypress)}},[isActive,handleKeypress,subscribe,unsubscribe])}__name(useKeypress,"useKeypress");export{enableMouseEvents,disableMouseEvents,ContextMenuProvider,useContextMenu,contextMenuSize,clampMenuPosition,useKeypress,useFocus,useKeypressContext,KeypressProvider};
3
+ import{BACKSLASH_ENTER_DETECTION_WINDOW_MS,CHAR_CODE_ESC,KITTY_CTRL_C,KITTY_KEYCODE_BACKSPACE,KITTY_KEYCODE_ENTER,KITTY_KEYCODE_NUMPAD_ENTER,KITTY_KEYCODE_TAB,KITTY_MODIFIER_BASE,KITTY_MODIFIER_EVENT_TYPES_OFFSET,MAX_KITTY_SEQUENCE_LENGTH,MODIFIER_ALT_BIT,MODIFIER_CTRL_BIT,MODIFIER_SHIFT_BIT,MODIFIER_SUPER_BIT,clipboardHasImage}from"./chunk-UC455ZS7.js";import{require_jsx_runtime}from"./chunk-REPFZQ7R.js";import{use_stdin_default,use_stdout_default}from"./chunk-YIJNS5IJ.js";import{require_react}from"./chunk-5QKDV4CD.js";import{noteInteraction}from"./chunk-UGLQO5K7.js";import{KittySequenceOverflowEvent,logKittySequenceOverflow}from"./chunk-MJEL7DIE.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_react4=__toESM(require_react(),1);init_esbuild_shims();var import_react2=__toESM(require_react(),1);import readline from"node:readline";import{PassThrough}from"node:stream";init_esbuild_shims();var ESC="\x1B";var SGR_EVENT_PREFIX=`${ESC}[<`;var X11_EVENT_PREFIX=`${ESC}[M`;var MAX_SGR_MOUSE_SEQUENCE_LENGTH=50;var SGR_MOUSE_REGEX=/^\x1b\[<(\d+);(\d+);(\d+)([mM])/;function getEventName(buttonCode,isRelease){const isMove=(buttonCode&32)!==0;if(buttonCode===66)return"scroll-left";if(buttonCode===67)return"scroll-right";if((buttonCode&64)===64){return(buttonCode&1)===0?"scroll-up":"scroll-down"}if(isMove)return"move";const button=buttonCode&3;const type=isRelease?"release":"press";switch(button){case 0:return`left-${type}`;case 1:return`middle-${type}`;case 2:return`right-${type}`;default:return null}}__name(getEventName,"getEventName");function buttonFromCode(code){switch(code&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}__name(buttonFromCode,"buttonFromCode");function parseSGRMouseEvent(buffer){const match=buffer.match(SGR_MOUSE_REGEX);if(!match)return null;const buttonCode=parseInt(match[1],10);const col=parseInt(match[2],10);const row=parseInt(match[3],10);const isRelease=match[4]==="m";const name=getEventName(buttonCode,isRelease);if(!name)return null;return{event:{name,col,row,shift:(buttonCode&4)!==0,meta:(buttonCode&8)!==0,ctrl:(buttonCode&16)!==0,button:buttonFromCode(buttonCode)},length:match[0].length}}__name(parseSGRMouseEvent,"parseSGRMouseEvent");var ENABLE_SGR_MOUSE={button:"\x1B[?1002h\x1B[?1006h",any:"\x1B[?1003h\x1B[?1006h"};var DISABLE_SGR_MOUSE={button:"\x1B[?1006l\x1B[?1002l",any:"\x1B[?1006l\x1B[?1003l"};function enableMouseEvents(stdout,tracking="button"){stdout.write(ENABLE_SGR_MOUSE[tracking])}__name(enableMouseEvents,"enableMouseEvents");function disableMouseEvents(stdout,tracking="button"){stdout.write(DISABLE_SGR_MOUSE[tracking])}__name(disableMouseEvents,"disableMouseEvents");init_esbuild_shims();var import_react=__toESM(require_react(),1);var ENABLE_FOCUS_REPORTING="\x1B[?1004h";var DISABLE_FOCUS_REPORTING="\x1B[?1004l";var FOCUS_IN="\x1B[I";var FOCUS_OUT="\x1B[O";var useFocus=__name(()=>{const{stdin}=use_stdin_default();const{stdout}=use_stdout_default();const[isFocused,setIsFocused]=(0,import_react.useState)(true);(0,import_react.useEffect)(()=>{const handleData=__name(data=>{const sequence=data.toString();const lastFocusIn=sequence.lastIndexOf(FOCUS_IN);const lastFocusOut=sequence.lastIndexOf(FOCUS_OUT);if(lastFocusIn>lastFocusOut){setIsFocused(true)}else if(lastFocusOut>lastFocusIn){setIsFocused(false)}},"handleData");stdout?.write(ENABLE_FOCUS_REPORTING);stdin?.on("data",handleData);return()=>{stdout?.write(DISABLE_FOCUS_REPORTING);stdin?.removeListener("data",handleData)}},[stdin,stdout]);useKeypress(_=>{if(!isFocused){setIsFocused(true)}},{isActive:true});return isFocused},"useFocus");var import_jsx_runtime=__toESM(require_jsx_runtime(),1);var ESC2="\x1B";var OPTION_COMPOSED_GLYPHS={"\u2020":"t","\u221A":"v"};var PASTE_MODE_PREFIX=`${ESC2}[200~`;var PASTE_MODE_SUFFIX=`${ESC2}[201~`;var KITTY_SEQUENCE_TIMEOUT_MS=200;var PASTE_IDLE_TIMEOUT_MS=1e3;var KITTY_KEYPAD_PRINTABLE_KEYCODE_TO_CHAR={57399:"0",57400:"1",57401:"2",57402:"3",57403:"4",57404:"5",57405:"6",57406:"7",57407:"8",57408:"9",57409:".",57410:"/",57411:"*",57412:"-",57413:"+",57415:"=",57416:","};var KITTY_KEYPAD_FUNCTIONAL_KEYCODE_TO_NAME={57417:"left",57418:"right",57419:"up",57420:"down",57421:"pageup",57422:"pagedown",57423:"home",57424:"end",57425:"insert",57426:"delete"};var KeypressContext=(0,import_react2.createContext)(void 0);var debugLogger=createDebugLogger("KEYPRESS");function useKeypressContext(){const context=(0,import_react2.useContext)(KeypressContext);if(!context){throw new Error("useKeypressContext must be used within a KeypressProvider")}return context}__name(useKeypressContext,"useKeypressContext");function KeypressProvider({children,kittyProtocolEnabled,pasteWorkaround=false,config,debugKeystrokeLogging,initialCapturedInput}){const{stdin,setRawMode}=use_stdin_default();const subscribers=(0,import_react2.useRef)(new Set).current;const mouseSubscribers=(0,import_react2.useRef)(new Set).current;const[pasteProgress,setPasteProgress]=(0,import_react2.useState)({active:false,receivedBytes:0});const subscribe=(0,import_react2.useCallback)(handler=>{subscribers.add(handler)},[subscribers]);const unsubscribe=(0,import_react2.useCallback)(handler=>{subscribers.delete(handler)},[subscribers]);const subscribeMouse=(0,import_react2.useCallback)(handler=>{mouseSubscribers.add(handler)},[mouseSubscribers]);const unsubscribeMouse=(0,import_react2.useCallback)(handler=>{mouseSubscribers.delete(handler)},[mouseSubscribers]);(0,import_react2.useEffect)(()=>{setRawMode(true);const capturedInput=initialCapturedInput??Buffer.alloc(0);const keypressStream=new PassThrough;let usePassthrough=false;if(pasteWorkaround){usePassthrough=true}let isPaste=false;let pasteChunks=[];let pasteAlreadyFlushed=false;let pasteIdleTimeout=null;let lastPasteChunkAt=0;const kittySequenceBufferRef={current:""};let kittySequenceTimeout=null;let backslashTimeout=null;let waitingForEnterAfterBackslash=false;let rawDataBuffer=Buffer.alloc(0);let rawFlushTimeout=null;let swallowingSgrMouse=false;let sgrMouseBuffer="";let sgrMouseTimeout=null;const resetSgrMouse=__name(()=>{swallowingSgrMouse=false;sgrMouseBuffer="";if(sgrMouseTimeout){clearTimeout(sgrMouseTimeout);sgrMouseTimeout=null}},"resetSgrMouse");const updateKittyBuffer=__name(value=>{kittySequenceBufferRef.current=value},"updateKittyBuffer");const clearKittyTimeout=__name(()=>{if(kittySequenceTimeout){clearTimeout(kittySequenceTimeout);kittySequenceTimeout=null}},"clearKittyTimeout");const startKittyTimeout=__name(()=>{clearKittyTimeout();kittySequenceTimeout=setTimeout(()=>{if(kittySequenceBufferRef.current){while(kittySequenceBufferRef.current){const parsed=parseKittyPrefix(kittySequenceBufferRef.current);if(parsed){kittySequenceBufferRef.current=kittySequenceBufferRef.current.slice(parsed.length);broadcast(parsed.key);continue}const plain=parsePlainTextPrefix(kittySequenceBufferRef.current);if(plain){kittySequenceBufferRef.current=kittySequenceBufferRef.current.slice(plain.length);broadcast(plain.key);continue}break}if(kittySequenceBufferRef.current){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer timeout, clearing:",kittySequenceBufferRef.current)}kittySequenceBufferRef.current=""}}},KITTY_SEQUENCE_TIMEOUT_MS)},"startKittyTimeout");const clearKittyBufferAndTimeout=__name(()=>{clearKittyTimeout();kittySequenceBufferRef.current=""},"clearKittyBufferAndTimeout");const clearPasteIdleTimeout=__name(()=>{if(pasteIdleTimeout){clearTimeout(pasteIdleTimeout);pasteIdleTimeout=null}},"clearPasteIdleTimeout");const forceFlushStuckPaste=__name(()=>{clearPasteIdleTimeout();if(!isPaste&&pasteChunks.length===0)return;const buffered=pasteChunks.join("");isPaste=false;pasteChunks=[];pasteAlreadyFlushed=true;if(buffered.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:buffered})}},"forceFlushStuckPaste");const onPasteIdleTimeout=__name(()=>{const idleFor=Date.now()-lastPasteChunkAt;if(idleFor>=PASTE_IDLE_TIMEOUT_MS){forceFlushStuckPaste()}else{pasteIdleTimeout=setTimeout(onPasteIdleTimeout,PASTE_IDLE_TIMEOUT_MS-idleFor)}},"onPasteIdleTimeout");const startPasteIdleTimeout=__name(()=>{lastPasteChunkAt=Date.now();if(pasteIdleTimeout)return;pasteIdleTimeout=setTimeout(onPasteIdleTimeout,PASTE_IDLE_TIMEOUT_MS)},"startPasteIdleTimeout");const createPrintableKey=__name(char=>{const printableName=char===" "?"space":/^[A-Za-z]$/.test(char)?char.toLowerCase():char;return{name:printableName,ctrl:false,meta:false,shift:false,paste:false,sequence:char,kittyProtocol:true}},"createPrintableKey");const parseKittyPrefix=__name(buffer=>{const revTabLegacy=new RegExp(`^${ESC2}\\[Z`);let m=buffer.match(revTabLegacy);if(m){return{key:{name:"tab",ctrl:false,meta:false,shift:true,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}const revTabParam=new RegExp(`^${ESC2}\\[1;(\\d+)Z`);m=buffer.match(revTabParam);if(m){let mods=parseInt(m[1],10);if(mods>=KITTY_MODIFIER_EVENT_TYPES_OFFSET){mods-=KITTY_MODIFIER_EVENT_TYPES_OFFSET}const bits=mods-KITTY_MODIFIER_BASE;const alt=(bits&MODIFIER_ALT_BIT)===MODIFIER_ALT_BIT||(bits&MODIFIER_SUPER_BIT)===MODIFIER_SUPER_BIT;const ctrl=(bits&MODIFIER_CTRL_BIT)===MODIFIER_CTRL_BIT;return{key:{name:"tab",ctrl,meta:alt,shift:true,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}const arrowPrefix=new RegExp(`^${ESC2}\\[1;(\\d+)([ABCDHFPQSR])`);m=buffer.match(arrowPrefix);if(m){let mods=parseInt(m[1],10);if(mods>=KITTY_MODIFIER_EVENT_TYPES_OFFSET){mods-=KITTY_MODIFIER_EVENT_TYPES_OFFSET}const bits=mods-KITTY_MODIFIER_BASE;const shift=(bits&MODIFIER_SHIFT_BIT)===MODIFIER_SHIFT_BIT;const alt=(bits&MODIFIER_ALT_BIT)===MODIFIER_ALT_BIT||(bits&MODIFIER_SUPER_BIT)===MODIFIER_SUPER_BIT;const ctrl=(bits&MODIFIER_CTRL_BIT)===MODIFIER_CTRL_BIT;const sym=m[2];const symbolToName={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end",P:"f1",Q:"f2",R:"f3",S:"f4"};const name=symbolToName[sym]||"";if(!name)return null;return{key:{name,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}const csiUPrefix=new RegExp(`^${ESC2}\\[(\\d+)(?::\\d+)*(?:;(\\d+)(?::\\d+)*)?(?:;(\\d+))?([u~])`);m=buffer.match(csiUPrefix);if(m){let keyCode=parseInt(m[1],10);let modifiers=m[2]?parseInt(m[2],10):KITTY_MODIFIER_BASE;if(modifiers>=KITTY_MODIFIER_EVENT_TYPES_OFFSET){modifiers-=KITTY_MODIFIER_EVENT_TYPES_OFFSET}const modifierBits=modifiers-KITTY_MODIFIER_BASE;const shift=(modifierBits&MODIFIER_SHIFT_BIT)===MODIFIER_SHIFT_BIT;const alt=(modifierBits&MODIFIER_ALT_BIT)===MODIFIER_ALT_BIT||(modifierBits&MODIFIER_SUPER_BIT)===MODIFIER_SUPER_BIT;const ctrl=(modifierBits&MODIFIER_CTRL_BIT)===MODIFIER_CTRL_BIT;const terminator=m[4];if(keyCode===CHAR_CODE_ESC&&terminator==="~"&&m[3]){keyCode=parseInt(m[3],10)}if(terminator==="~"){let name2=null;switch(keyCode){case 1:name2="home";break;case 2:name2="insert";break;case 3:name2="delete";break;case 4:name2="end";break;case 5:name2="pageup";break;case 6:name2="pagedown";break;default:break}if(name2){return{key:{name:name2,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}}const kittyKeyCodeToName={[CHAR_CODE_ESC]:"escape",[KITTY_KEYCODE_TAB]:"tab",[KITTY_KEYCODE_BACKSPACE]:"backspace",[KITTY_KEYCODE_ENTER]:"return",[KITTY_KEYCODE_NUMPAD_ENTER]:"return"};const name=kittyKeyCodeToName[keyCode];if(name){return{key:{name,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}if(!ctrl){const keypadChar=KITTY_KEYPAD_PRINTABLE_KEYCODE_TO_CHAR[keyCode];if(keypadChar){return{key:{name:keypadChar,ctrl:false,meta:alt,shift,paste:false,sequence:keypadChar,kittyProtocol:true},length:m[0].length}}}const keypadName=KITTY_KEYPAD_FUNCTIONAL_KEYCODE_TO_NAME[keyCode];if(keypadName){return{key:{name:keypadName,ctrl,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}if(terminator==="u"&&!ctrl&&keyCode>=32&&keyCode!==127&&keyCode<=1114111&&!(keyCode>=57344&&keyCode<=63743)){return{key:{...createPrintableKey(String.fromCodePoint(keyCode)),meta:alt,shift},length:m[0].length}}if(ctrl&&keyCode>="a".charCodeAt(0)&&keyCode<="z".charCodeAt(0)){const letter=String.fromCharCode(keyCode);return{key:{name:letter,ctrl:true,meta:alt,shift,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}}const legacyFuncKey=new RegExp(`^${ESC2}\\[([ABCDHF])`);m=buffer.match(legacyFuncKey);if(m){const sym=m[1];const nameMap={A:"up",B:"down",C:"right",D:"left",H:"home",F:"end"};const name=nameMap[sym];return{key:{name,ctrl:false,meta:false,shift:false,paste:false,sequence:buffer.slice(0,m[0].length),kittyProtocol:true},length:m[0].length}}return null},"parseKittyPrefix");const getCompleteCsiSequenceLength=__name(buffer=>{if(!buffer.startsWith(`${ESC2}[`)){return null}for(let i=2;i<buffer.length;i++){const code=buffer.charCodeAt(i);if(code>=64&&code<=126){return i+1}if(code<32||code>63){return 0}}return null},"getCompleteCsiSequenceLength");const parsePlainTextPrefix=__name(buffer=>{if(!buffer||buffer.startsWith(ESC2)){return null}const[char]=Array.from(buffer);if(!char){return null}return{key:createPrintableKey(char),length:char.length}},"parsePlainTextPrefix");const broadcast=__name(key=>{noteInteraction();for(const handler of subscribers){handler(key)}},"broadcast");const TERMINAL_RESPONSE_RE=/^\x1b\[[?>][\d;]*[uc]$/;const handleKeypress=__name(async(_,key)=>{if(TERMINAL_RESPONSE_RE.test(key.sequence)){return}if(key.sequence===FOCUS_IN||key.sequence===FOCUS_OUT){return}if(isPaste){resetSgrMouse()}else if(swallowingSgrMouse){if(key.ctrl&&key.name==="c"){resetSgrMouse()}else if(key.name==="paste-start"){resetSgrMouse()}else{sgrMouseBuffer+=key.sequence;if(key.name==="m"||key.sequence==="M"){swallowingSgrMouse=false;if(sgrMouseTimeout){clearTimeout(sgrMouseTimeout);sgrMouseTimeout=null}const parsed=parseSGRMouseEvent(sgrMouseBuffer);if(parsed){for(const handler of mouseSubscribers){handler(parsed.event)}}sgrMouseBuffer=""}else if(sgrMouseBuffer.length>=MAX_SGR_MOUSE_SEQUENCE_LENGTH){resetSgrMouse()}return}}if(!isPaste&&key.sequence===`${ESC2}[<`){swallowingSgrMouse=true;sgrMouseBuffer=`${ESC2}[<`;if(sgrMouseTimeout){clearTimeout(sgrMouseTimeout)}sgrMouseTimeout=setTimeout(()=>{swallowingSgrMouse=false;sgrMouseBuffer="";sgrMouseTimeout=null},KITTY_SEQUENCE_TIMEOUT_MS);return}const isCtrlCKey=key.ctrl&&key.name==="c"||key.sequence===`${ESC2}${KITTY_CTRL_C}`;if(isCtrlCKey){if(isPaste||pasteChunks.length>0){isPaste=false;pasteChunks=[];pasteAlreadyFlushed=true;clearPasteIdleTimeout()}if(kittySequenceBufferRef.current&&debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer cleared on Ctrl+C:",kittySequenceBufferRef.current)}clearKittyBufferAndTimeout();if(key.sequence===`${ESC2}${KITTY_CTRL_C}`){broadcast({name:"c",ctrl:true,meta:false,shift:false,paste:false,sequence:key.sequence,kittyProtocol:true})}else{broadcast(key)}return}if(key.name==="paste-start"){isPaste=true;pasteAlreadyFlushed=false;startPasteIdleTimeout();return}if(key.name==="paste-end"){clearPasteIdleTimeout();if(pasteAlreadyFlushed){pasteAlreadyFlushed=false;isPaste=false;pasteChunks=[];return}isPaste=false;const buffered=pasteChunks.join("");pasteChunks=[];if(buffered.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:buffered})}else{let clipboardImageUnavailable=false;const hasImage=await clipboardHasImage(()=>{clipboardImageUnavailable=true});broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,pasteImage:hasImage,clipboardImageUnavailable,sequence:buffered})}return}if(isPaste){pasteChunks.push(key.sequence);startPasteIdleTimeout();return}if(key.name==="return"&&waitingForEnterAfterBackslash){if(backslashTimeout){clearTimeout(backslashTimeout);backslashTimeout=null}waitingForEnterAfterBackslash=false;broadcast({...key,shift:true,sequence:"\r"});return}if(key.sequence==="\\"&&!key.name){waitingForEnterAfterBackslash=true;backslashTimeout=setTimeout(()=>{waitingForEnterAfterBackslash=false;backslashTimeout=null;broadcast(key)},BACKSLASH_ENTER_DETECTION_WINDOW_MS);return}if(waitingForEnterAfterBackslash&&key.name!=="return"){if(backslashTimeout){clearTimeout(backslashTimeout);backslashTimeout=null}waitingForEnterAfterBackslash=false;broadcast({name:"",sequence:"\\",ctrl:false,meta:false,shift:false,paste:false})}if(["up","down","left","right"].includes(key.name)){broadcast(key);return}const isModifyOtherKeysSequence=key.sequence?.startsWith(`${ESC2}[27`)??false;if(kittyProtocolEnabled||kittySequenceBufferRef.current||isModifyOtherKeysSequence){if(kittySequenceBufferRef.current||key.sequence.startsWith(`${ESC2}[`)&&!key.sequence.startsWith(PASTE_MODE_PREFIX)&&!key.sequence.startsWith(PASTE_MODE_SUFFIX)&&!key.sequence.startsWith(FOCUS_IN)&&!key.sequence.startsWith(FOCUS_OUT)){updateKittyBuffer(kittySequenceBufferRef.current+key.sequence);startKittyTimeout();if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer accumulating:",kittySequenceBufferRef.current)}let bufferedInputHandled=false;while(kittySequenceBufferRef.current){const parsed=parseKittyPrefix(kittySequenceBufferRef.current);if(parsed){if(debugKeystrokeLogging){const parsedSequence=kittySequenceBufferRef.current.slice(0,parsed.length);if(kittySequenceBufferRef.current.length>parsed.length){debugLogger.debug("[DEBUG] Kitty sequence parsed successfully (prefix):",parsedSequence)}else{debugLogger.debug("[DEBUG] Kitty sequence parsed successfully:",parsedSequence)}}updateKittyBuffer(kittySequenceBufferRef.current.slice(parsed.length));if(!kittySequenceBufferRef.current){clearKittyTimeout()}broadcast(parsed.key);bufferedInputHandled=true;continue}const completeUnsupportedCsiLength=getCompleteCsiSequenceLength(kittySequenceBufferRef.current);if(completeUnsupportedCsiLength){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Dropping unsupported complete CSI sequence:",kittySequenceBufferRef.current.slice(0,completeUnsupportedCsiLength))}updateKittyBuffer(kittySequenceBufferRef.current.slice(completeUnsupportedCsiLength));if(!kittySequenceBufferRef.current){clearKittyTimeout()}bufferedInputHandled=true;continue}const plainTextPrefix=parsePlainTextPrefix(kittySequenceBufferRef.current);if(plainTextPrefix){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Recovered plain text after kitty sequence:",plainTextPrefix.key.sequence)}updateKittyBuffer(kittySequenceBufferRef.current.slice(plainTextPrefix.length));if(!kittySequenceBufferRef.current){clearKittyTimeout()}broadcast(plainTextPrefix.key);bufferedInputHandled=true;continue}const nextStart=kittySequenceBufferRef.current.indexOf(`${ESC2}[`,1);if(nextStart>0){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Skipping incomplete/invalid CSI prefix:",kittySequenceBufferRef.current.slice(0,nextStart))}updateKittyBuffer(kittySequenceBufferRef.current.slice(nextStart));if(!kittySequenceBufferRef.current){clearKittyTimeout()}bufferedInputHandled=true;continue}break}if(bufferedInputHandled)return;if(config?.getDebugMode()||debugKeystrokeLogging){const codes=Array.from(kittySequenceBufferRef.current).map(ch=>ch.charCodeAt(0));debugLogger.warn("Kitty sequence buffer has char codes:",codes)}if(kittySequenceBufferRef.current.length>MAX_KITTY_SEQUENCE_LENGTH){if(debugKeystrokeLogging){debugLogger.debug("[DEBUG] Kitty buffer overflow, clearing:",kittySequenceBufferRef.current)}if(config){const event=new KittySequenceOverflowEvent(kittySequenceBufferRef.current.length,kittySequenceBufferRef.current);logKittySequenceOverflow(config,event)}clearKittyBufferAndTimeout()}else{return}}}if(key.name==="return"&&key.sequence===`${ESC2}\r`){key.meta=true}const composedKeyName=Object.hasOwn(OPTION_COMPOSED_GLYPHS,key.sequence)?OPTION_COMPOSED_GLYPHS[key.sequence]:void 0;if(process.platform==="darwin"&&!isPaste&&composedKeyName){key.name=composedKeyName;key.meta=true}broadcast({...key,paste:isPaste})},"handleKeypress");const clearRawFlushTimeout=__name(()=>{if(rawFlushTimeout){clearTimeout(rawFlushTimeout);rawFlushTimeout=null}},"clearRawFlushTimeout");const createPasteKeyEvent=__name((name="",sequence="")=>({name,ctrl:false,meta:false,shift:false,paste:false,sequence}),"createPasteKeyEvent");const shouldFlushRawDataAsPaste=__name(data=>{if(data.includes(27))return false;const hasReturn=data.includes(13);const hasEmbeddedTab=data.length>1&&data.includes(9);const isSingleReturn=data.length<=2&&hasReturn;return!isSingleReturn&&(hasReturn||hasEmbeddedTab)},"shouldFlushRawDataAsPaste");const flushRawBuffer=__name(()=>{if(!rawDataBuffer.length){return}const pasteModePrefixBuffer=Buffer.from(PASTE_MODE_PREFIX);const pasteModeSuffixBuffer=Buffer.from(PASTE_MODE_SUFFIX);const data=rawDataBuffer;let cursor=0;while(cursor<data.length){const prefixPos=data.indexOf(pasteModePrefixBuffer,cursor);const suffixPos=data.indexOf(pasteModeSuffixBuffer,cursor);const hasPrefix=prefixPos!==-1&&prefixPos+pasteModePrefixBuffer.length<=data.length;const hasSuffix=suffixPos!==-1&&suffixPos+pasteModeSuffixBuffer.length<=data.length;let markerPos=-1;let markerLength=0;let markerType=null;if(hasPrefix&&(!hasSuffix||prefixPos<suffixPos)){markerPos=prefixPos;markerLength=pasteModePrefixBuffer.length;markerType="prefix"}else if(hasSuffix){markerPos=suffixPos;markerLength=pasteModeSuffixBuffer.length;markerType="suffix"}if(markerPos===-1){break}const nextData=data.slice(cursor,markerPos);if(nextData.length>0){keypressStream.write(nextData)}if(markerType==="prefix"){handleKeypress(void 0,createPasteKeyEvent("paste-start"))}else if(markerType==="suffix"){handleKeypress(void 0,createPasteKeyEvent("paste-end"))}cursor=markerPos+markerLength}rawDataBuffer=data.slice(cursor);if(rawDataBuffer.length===0){return}if(isPaste||!shouldFlushRawDataAsPaste(rawDataBuffer)){keypressStream.write(rawDataBuffer)}else{handleKeypress(void 0,createPasteKeyEvent("paste-start"));keypressStream.write(rawDataBuffer);handleKeypress(void 0,createPasteKeyEvent("paste-end"))}rawDataBuffer=Buffer.alloc(0);clearRawFlushTimeout()},"flushRawBuffer");const handleRawKeypress=__name(_data=>{const data=Buffer.isBuffer(_data)?_data:Buffer.from(_data,"utf8");rawDataBuffer=Buffer.concat([rawDataBuffer,data]);clearRawFlushTimeout();const isReturnChar=rawDataBuffer.length<=2&&rawDataBuffer.includes(13);if(isReturnChar){rawFlushTimeout=setTimeout(flushRawBuffer,100)}else{flushRawBuffer()}},"handleRawKeypress");const pasteModePrefixBuf=Buffer.from(PASTE_MODE_PREFIX);const pasteModeSuffixBuf=Buffer.from(PASTE_MODE_SUFFIX);function partialMarkerTailLength(chunk,marker,minLen=2){const maxCheck=Math.min(chunk.length,marker.length-1);for(let len=maxCheck;len>=minLen;len--){const tail=chunk.subarray(chunk.length-len);if(marker.subarray(0,len).equals(tail)){return len}}return 0}__name(partialMarkerTailLength,"partialMarkerTailLength");let rawStdinTail=Buffer.alloc(0);let rawPasteAccumulating=false;let rawPasteChunks=[];let rawPasteReceivedBytes=0;let rawPasteIdleTimeout=null;const clearRawPasteIdleTimeout=__name(()=>{if(rawPasteIdleTimeout){clearTimeout(rawPasteIdleTimeout);rawPasteIdleTimeout=null}},"clearRawPasteIdleTimeout");const forceFlushRawPaste=__name(()=>{clearRawPasteIdleTimeout();if(!rawPasteAccumulating&&rawPasteChunks.length===0&&rawStdinTail.length===0)return;if(rawStdinTail.length>0){rawPasteChunks.push(rawStdinTail);rawStdinTail=Buffer.alloc(0)}const content=Buffer.concat(rawPasteChunks);rawPasteChunks=[];rawPasteAccumulating=false;broadcastPasteFromRaw(content)},"forceFlushRawPaste");const startRawPasteIdleTimeout=__name(()=>{clearRawPasteIdleTimeout();rawPasteIdleTimeout=setTimeout(forceFlushRawPaste,PASTE_IDLE_TIMEOUT_MS)},"startRawPasteIdleTimeout");const broadcastPasteFromRaw=__name(content=>{pasteAlreadyFlushed=true;setPasteProgress({active:false,receivedBytes:0});const text=content.toString("utf-8");if(text.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:text})}else{let clipboardImageUnavailable=false;void clipboardHasImage(()=>{clipboardImageUnavailable=true}).then(hasImage=>{broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,pasteImage:hasImage,clipboardImageUnavailable,sequence:""})})}},"broadcastPasteFromRaw");const handleStdinData=__name(data=>{const raw=Buffer.isBuffer(data)?data:Buffer.from(data,"utf8");const buf=rawStdinTail.length>0?Buffer.concat([rawStdinTail,raw]):raw;rawStdinTail=Buffer.alloc(0);let cursor=0;while(cursor<buf.length){if(rawPasteAccumulating){const suffixIdx=buf.indexOf(pasteModeSuffixBuf,cursor);if(suffixIdx===-1){const remaining=buf.subarray(cursor);const tailLen=partialMarkerTailLength(remaining,pasteModeSuffixBuf,1);const contentEnd=remaining.length-tailLen;if(contentEnd>0){const chunk=remaining.subarray(0,contentEnd);rawPasteChunks.push(chunk);rawPasteReceivedBytes+=chunk.length;setPasteProgress(prev=>({...prev,receivedBytes:rawPasteReceivedBytes}))}if(tailLen>0){rawStdinTail=Buffer.from(remaining.subarray(contentEnd))}startRawPasteIdleTimeout();cursor=buf.length}else{clearRawPasteIdleTimeout();if(suffixIdx>cursor){rawPasteChunks.push(buf.subarray(cursor,suffixIdx))}const pasteContent=Buffer.concat(rawPasteChunks);rawPasteChunks=[];rawPasteAccumulating=false;broadcastPasteFromRaw(pasteContent);cursor=suffixIdx+pasteModeSuffixBuf.length}}else{const prefixIdx=buf.indexOf(pasteModePrefixBuf,cursor);if(prefixIdx===-1){const remaining=buf.subarray(cursor);if(remaining.length>0){const tailLen=partialMarkerTailLength(remaining,pasteModePrefixBuf);if(tailLen>0){const safe=remaining.subarray(0,remaining.length-tailLen);if(safe.length>0)keypressStream.write(safe);rawStdinTail=Buffer.from(remaining.subarray(remaining.length-tailLen))}else{keypressStream.write(remaining)}}cursor=buf.length}else{if(prefixIdx>cursor){keypressStream.write(buf.subarray(cursor,prefixIdx))}rawPasteAccumulating=true;rawPasteChunks=[];rawPasteReceivedBytes=0;startRawPasteIdleTimeout();setPasteProgress({active:true,receivedBytes:0});cursor=prefixIdx+pasteModePrefixBuf.length}}}},"handleStdinData");let rl;if(usePassthrough){rl=readline.createInterface({input:keypressStream,escapeCodeTimeout:0});readline.emitKeypressEvents(keypressStream,rl);keypressStream.on("keypress",handleKeypress);stdin.on("data",handleRawKeypress)}else{rl=readline.createInterface({input:keypressStream,escapeCodeTimeout:0});readline.emitKeypressEvents(keypressStream,rl);keypressStream.on("keypress",handleKeypress);stdin.on("keypress",handleKeypress);stdin.on("data",handleStdinData)}let replayPending=false;if(capturedInput.length>0){debugLogger.debug(`Replaying ${capturedInput.length} bytes of captured input`);replayPending=true;setImmediate(()=>{if(!replayPending)return;try{stdin.emit("data",capturedInput)}catch(err){debugLogger.error("Failed to replay captured input:",err)}})}return()=>{replayPending=false;if(usePassthrough){keypressStream.removeListener("keypress",handleKeypress);stdin.removeListener("data",handleRawKeypress)}else{keypressStream.removeListener("keypress",handleKeypress);stdin.removeListener("keypress",handleKeypress);stdin.removeListener("data",handleStdinData)}rl.close();setRawMode(false);if(backslashTimeout){clearTimeout(backslashTimeout);backslashTimeout=null}clearKittyBufferAndTimeout();clearPasteIdleTimeout();clearRawPasteIdleTimeout();resetSgrMouse();if(rawFlushTimeout){clearTimeout(rawFlushTimeout);rawFlushTimeout=null}if(rawPasteAccumulating||rawPasteChunks.length>0){forceFlushRawPaste()}else if(isPaste){const buffered=pasteChunks.join("");if(buffered.length>0){broadcast({name:"",ctrl:false,meta:false,shift:false,paste:true,sequence:buffered})}pasteChunks=[]}}},[stdin,setRawMode,kittyProtocolEnabled,debugKeystrokeLogging,pasteWorkaround,config,subscribers,mouseSubscribers,initialCapturedInput]);return(0,import_jsx_runtime.jsx)(KeypressContext.Provider,{value:{subscribe,unsubscribe,subscribeMouse,unsubscribeMouse,pasteWorkaround,pasteProgress},children})}__name(KeypressProvider,"KeypressProvider");init_esbuild_shims();var import_react3=__toESM(require_react(),1);var import_jsx_runtime2=__toESM(require_jsx_runtime(),1);var ContextMenuContext=(0,import_react3.createContext)({menu:null,isMenuOpen:__name(()=>false,"isMenuOpen"),selectedIndex:0,openMenu:__name(()=>{},"openMenu"),closeMenu:__name(()=>{},"closeMenu"),setSelectedIndex:__name(()=>{},"setSelectedIndex"),executeIndex:__name(()=>{},"executeIndex")});var ContextMenuProvider=__name(({children,onMenuChange})=>{const[menu,setMenu]=(0,import_react3.useState)(null);const[selectedIndex,setSelectedIndexState]=(0,import_react3.useState)(0);const menuRef=(0,import_react3.useRef)(null);menuRef.current=menu;const isMenuOpen=(0,import_react3.useCallback)(()=>menuRef.current!==null,[]);const openMenu=(0,import_react3.useCallback)((items,position)=>{if(items.length===0)return;menuRef.current={items,position};onMenuChange?.(true);setMenu(menuRef.current);setSelectedIndexState(0)},[onMenuChange]);const closeMenu=(0,import_react3.useCallback)(()=>{menuRef.current=null;setMenu(null)},[]);(0,import_react3.useEffect)(()=>{onMenuChange?.(menu!==null)},[menu,onMenuChange]);const setSelectedIndex=(0,import_react3.useCallback)(index=>{setSelectedIndexState(index)},[]);const executeIndex=(0,import_react3.useCallback)(index=>{const current=menuRef.current;menuRef.current=null;setMenu(null);current?.items[index]?.onSelect()},[]);const value=(0,import_react3.useMemo)(()=>({menu,isMenuOpen,selectedIndex,openMenu,closeMenu,setSelectedIndex,executeIndex}),[menu,isMenuOpen,selectedIndex,openMenu,closeMenu,setSelectedIndex,executeIndex]);return(0,import_jsx_runtime2.jsx)(ContextMenuContext.Provider,{value,children})},"ContextMenuProvider");function useContextMenu(){return(0,import_react3.useContext)(ContextMenuContext)}__name(useContextMenu,"useContextMenu");function contextMenuSize(items){const longest=items.reduce((max,item)=>Math.max(max,item.label.length),0);return{width:longest+4,height:items.length+2}}__name(contextMenuSize,"contextMenuSize");function clampMenuPosition(desired,size,terminalColumns,terminalRows){return{x:Math.max(0,Math.min(desired.x,terminalColumns-size.width)),y:Math.max(0,Math.min(desired.y,terminalRows-size.height))}}__name(clampMenuPosition,"clampMenuPosition");function useKeypress(onKeypress,{isActive}){const{subscribe,unsubscribe}=useKeypressContext();const{menu,isMenuOpen}=useContextMenu();const onKeypressRef=(0,import_react4.useRef)(onKeypress);onKeypressRef.current=key=>{if(menu===null&&isMenuOpen())return;onKeypress(key)};const handleKeypress=(0,import_react4.useCallback)(key=>{onKeypressRef.current(key)},[]);(0,import_react4.useEffect)(()=>{if(!isActive){return}subscribe(handleKeypress);return()=>{unsubscribe(handleKeypress)}},[isActive,handleKeypress,subscribe,unsubscribe])}__name(useKeypress,"useKeypress");export{enableMouseEvents,disableMouseEvents,ContextMenuProvider,useContextMenu,contextMenuSize,clampMenuPosition,useKeypress,useFocus,useKeypressContext,KeypressProvider};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen
@@ -1,7 +1,7 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{EXTENSION_CONTEXT_BUDGET,buildExtensionMentionContext,buildExtensionRef,getSanitizedExtensionDisplayName,matchExtensionByRef,parseExtensionRef,sanitizeDisplayText}from"./chunk-P5543CFV.js";import{t}from"./chunk-FK5L2WVV.js";import{SessionReferenceService,readManyFiles}from"./chunk-3MBYQYPC.js";import{emptyMcpResourceText,formatMcpResourceContents,summarizeMcpResource}from"./chunk-46VUDNCL.js";import{SessionService}from"./chunk-PFKTTUGS.js";import{shouldRunVisionBridge}from"./chunk-MJEL7DIE.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{isSubpath,unescapePath,unescapeShellSpecials}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs/promises";import*as path from"node:path";init_esbuild_shims();function matchMcpServerPrefix(input,serverNames){let serverName=null;for(const name of serverNames){if(input.startsWith(`${name}:`)&&(serverName===null||name.length>serverName.length)){serverName=name}}if(serverName===null)return null;return{serverName,rest:input.slice(serverName.length+1)}}__name(matchMcpServerPrefix,"matchMcpServerPrefix");function buildMcpResourceRef(serverName,uri){return`${serverName}:${uri}`}__name(buildMcpResourceRef,"buildMcpResourceRef");init_esbuild_shims();init_esbuild_shims();var MAX_SUGGESTIONS_TO_SHOW=8;var MAX_SUGGESTION_LABEL_WIDTH=150;function prepareSuggestionLabel(label,matchedIndex,userInput,isExpanded=false){const hasMatch=matchedIndex!==void 0&&matchedIndex>=0&&matchedIndex<label.length&&userInput.length>0;if(!hasMatch){return{before:!isExpanded&&label.length>MAX_SUGGESTION_LABEL_WIDTH?label.slice(0,MAX_SUGGESTION_LABEL_WIDTH)+"...":label,match:"",after:""}}const matchLength=userInput.length;let before="";let match="";let after="";if(isExpanded||label.length<=MAX_SUGGESTION_LABEL_WIDTH){before=label.slice(0,matchedIndex);match=label.slice(matchedIndex,matchedIndex+matchLength);after=label.slice(matchedIndex+matchLength)}else if(matchLength>=MAX_SUGGESTION_LABEL_WIDTH){match=label.slice(matchedIndex,matchedIndex+MAX_SUGGESTION_LABEL_WIDTH-1)+"..."}else{const contextSpace=MAX_SUGGESTION_LABEL_WIDTH-matchLength;const beforeSpace=Math.floor(contextSpace/2);const afterSpace=Math.ceil(contextSpace/2);let start=matchedIndex-beforeSpace;let end=matchedIndex+matchLength+afterSpace;if(start<0){end+=-start;start=0}if(end>label.length){start-=end-label.length;end=label.length}start=Math.max(0,start);const finalMatchIndex=matchedIndex-start;const slicedLabel=label.slice(start,end);before=slicedLabel.slice(0,finalMatchIndex);match=slicedLabel.slice(finalMatchIndex,finalMatchIndex+matchLength);after=slicedLabel.slice(finalMatchIndex+matchLength);if(start>0){before=before.length>=3?"..."+before.slice(3):"..."}if(end<label.length){after=after.length>=3?after.slice(0,-3)+"...":"..."}}return{before,match,after}}__name(prepareSuggestionLabel,"prepareSuggestionLabel");function normalizeDescription(description){return description.replace(/\s+/g," ").trim()}__name(normalizeDescription,"normalizeDescription");function getExtensionSuggestions(config,pattern){if(!config)return[];if(config.isTrustedFolder?.()===false)return[];const extensions=config.getActiveExtensions?.()??[];if(extensions.length===0)return[];const query=pattern.toLowerCase();return extensions.map(ext=>({ext,safeLabel:sanitizeDisplayText(ext.displayName||ext.name)||ext.name})).filter(({safeLabel,ext})=>{const label=safeLabel.toLowerCase();const name=ext.name.toLowerCase();return label.includes(query)||name.includes(query)}).sort((a,b)=>{const aName=a.safeLabel.toLowerCase();const bName=b.safeLabel.toLowerCase();const aPrefix=aName.startsWith(query)?0:1;const bPrefix=bName.startsWith(query)?0:1;if(aPrefix!==bPrefix)return aPrefix-bPrefix;return aName.localeCompare(bName)}).slice(0,MAX_SUGGESTIONS_TO_SHOW).map(({ext,safeLabel})=>({label:safeLabel,value:buildExtensionRef(ext.name),description:ext.config.description?sanitizeDisplayText(ext.config.description)??void 0:void 0,sourceBadge:t("Extension"),isDirectory:false,category:"extension"}))}__name(getExtensionSuggestions,"getExtensionSuggestions");init_esbuild_shims();var SESSION_MENTION_PREFIX="session:";var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function isSessionId(value){return UUID_RE.test(value.trim())}__name(isSessionId,"isSessionId");function parseSessionRef(pathName){if(!pathName.startsWith(SESSION_MENTION_PREFIX))return null;const rawRemainder=pathName.slice(SESSION_MENTION_PREFIX.length).trim();const remainder=process.platform==="win32"?unescapeShellSpecials(rawRemainder):rawRemainder;if(remainder.length===0)return null;return isSessionId(remainder)?{id:remainder}:{title:remainder}}__name(parseSessionRef,"parseSessionRef");function buildSessionRef(idOrTitle){return`${SESSION_MENTION_PREFIX}${idOrTitle}`}__name(buildSessionRef,"buildSessionRef");init_esbuild_shims();var MCP_SERVER_REF_PREFIX="mcp:";function parseMcpServerRef(pathName){if(!pathName.startsWith(MCP_SERVER_REF_PREFIX))return null;const name=pathName.slice(MCP_SERVER_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseMcpServerRef,"parseMcpServerRef");function buildMcpServerRef(serverName){return`${MCP_SERVER_REF_PREFIX}${serverName}`}__name(buildMcpServerRef,"buildMcpServerRef");function matchMcpServerByRef(name,servers){const lower=name.toLowerCase();const matchedName=Object.keys(servers).find(serverName=>serverName.toLowerCase()===lower);if(!matchedName)return void 0;return{serverName:matchedName,server:servers[matchedName]}}__name(matchMcpServerByRef,"matchMcpServerByRef");function buildMcpServerContextText(config,serverName){const lines=[`--- MCP Server: ${serverName} ---`,`The user explicitly mentioned this MCP server. Prefer using tools and resources from this server when relevant for this turn. This is advisory context, not a hard restriction.`];const prompts=config.getPromptRegistry?.()?.getPromptsByServer(serverName)??[];const resources=config.getResourceRegistry?.()?.getResourcesByServer(serverName)??[];const details=[];if(resources.length>0){details.push(`- Resources: ${resources.length}`)}if(prompts.length>0){details.push(`- Prompts: ${prompts.length}`)}if(details.length>0){lines.push("Available capabilities from this MCP server:");lines.push(...details)}lines.push(`--- End MCP Server: ${serverName} ---`);return lines.join("\n")}__name(buildMcpServerContextText,"buildMcpServerContextText");function parseAllAtCommands(query){const parts=[];let currentIndex=0;while(currentIndex<query.length){let atIndex=-1;let nextSearchIndex=currentIndex;while(nextSearchIndex<query.length){if(query[nextSearchIndex]==="@"&&(nextSearchIndex===0||query[nextSearchIndex-1]!=="\\")){atIndex=nextSearchIndex;break}nextSearchIndex++}if(atIndex===-1){if(currentIndex<query.length){parts.push({type:"text",content:query.substring(currentIndex)})}break}if(atIndex>currentIndex){parts.push({type:"text",content:query.substring(currentIndex,atIndex)})}const isUrlRef=/^https?:\/\//i.test(query.slice(atIndex+1));const NON_URL_CHAR=/[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]/;let pathEndIndex=atIndex+1;let inEscape=false;while(pathEndIndex<query.length){const char=query[pathEndIndex];if(inEscape){inEscape=false}else if(char==="\\"){inEscape=true}else if(isUrlRef){if(NON_URL_CHAR.test(char))break}else if(/[,\s;!?()[\]{}]/.test(char)){break}else if(char==="."){const nextChar=pathEndIndex+1<query.length?query[pathEndIndex+1]:"";if(nextChar===""||/\s/.test(nextChar)){break}}pathEndIndex++}let rawAtPath=query.substring(atIndex,pathEndIndex);if(isUrlRef){const trimmed=rawAtPath.replace(/[.,;:!?]+$/,"");pathEndIndex=atIndex+trimmed.length;rawAtPath=trimmed}const atPath=unescapePath(rawAtPath);parts.push({type:"atPath",content:atPath});currentIndex=pathEndIndex}return parts.filter(part=>!(part.type==="text"&&part.content.trim()===""))}__name(parseAllAtCommands,"parseAllAtCommands");function extractAtPathCommands(query){return parseAllAtCommands(query).flatMap(part=>part.type==="atPath"&&part.content!=="@"?[part.content.substring(1)]:[])}__name(extractAtPathCommands,"extractAtPathCommands");function parseMcpResourceRef(pathName,mcpServerNames){const match=matchMcpServerPrefix(pathName,mcpServerNames);if(!match||!match.rest)return null;return{serverName:match.serverName,uri:match.rest}}__name(parseMcpResourceRef,"parseMcpResourceRef");async function resolveAtCommandQuery({query,config,onDebugMessage,messageId:userMessageTimestamp,signal}){const commandParts=parseAllAtCommands(query);const atPathCommandParts=commandParts.filter(part=>part.type==="atPath");if(atPathCommandParts.length===0){return{processedQuery:[{text:query}],shouldProceed:true}}const fileDiscovery=config.getFileService();const respectFileIgnore=config.getFileFilteringOptions();const configuredProjectTempDir=Storage.getGlobalTempDir();const projectTempDir=await fs.realpath(configuredProjectTempDir).catch(()=>path.resolve(configuredProjectTempDir));const pathSpecsToRead=[];const atPathToResolvedSpecMap=new Map;const contentLabelsForDisplay=[];const displayPaths=new Map;const displayPathsByCanonicalPath=new Map;const ignoredByReason={git:[],qwen:[],both:[]};const getIgnoreReason=__name(candidate=>{const gitIgnored=respectFileIgnore.respectGitIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:true,respectQwenIgnore:false});const qwenIgnored=respectFileIgnore.respectQwenIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:false,respectQwenIgnore:true});return gitIgnored&&qwenIgnored?"both":gitIgnored?"git":qwenIgnored?"qwen":void 0},"getIgnoreReason");const mcpServerNames=new Set(Object.keys(config.getMcpServers()||{}));const mcpResourceRefs=[];const mcpServerMentions=[];const activeExtensions=config.getActiveExtensions?.()??[];const extensionMentions=[];const sessionMentions=[];const urlMediaRefs=[];const rememberedMediaRefs=[];for(const atPathPart of atPathCommandParts){const originalAtPath=atPathPart.content;if(originalAtPath==="@"){onDebugMessage("Lone @ detected, will be treated as text in the modified query.");continue}const pathName=originalAtPath.substring(1);if(/^https?:\/\//i.test(pathName)&&config.isOmniEnabled?.()){const omni=await import("./omni-IFTMWBMU.js");if(omni.isOmniDeliveryActive(config)&&omni.parseHttpUrlRef(pathName)){if(!urlMediaRefs.some(r=>r.url===pathName)){urlMediaRefs.push({originalAtPath,url:pathName})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}}const extRef=parseExtensionRef(pathName);if(extRef){const extension=matchExtensionByRef(extRef.name,activeExtensions);if(extension){if(!extensionMentions.some(m=>m.extension.name===extension.name)){extensionMentions.push({originalAtPath,extension})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}onDebugMessage(`Extension "${extRef.name}" not found among active extensions. Available: ${activeExtensions.map(e=>e.name).join(", ")||"(none)"}`);continue}const sessionRef=parseSessionRef(pathName);if(sessionRef){if(!sessionMentions.some(m=>(m.ref.id??m.ref.title)===(sessionRef.id??sessionRef.title))){sessionMentions.push({originalAtPath,ref:sessionRef})}atPathToResolvedSpecMap.set(originalAtPath,buildSessionRef(sessionRef.id??sessionRef.title));continue}const resourceRef=parseMcpResourceRef(pathName,mcpServerNames);if(resourceRef){mcpResourceRefs.push({originalAtPath,...resourceRef});atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}const mcpServerRef=parseMcpServerRef(pathName);if(mcpServerRef){const matched=matchMcpServerByRef(mcpServerRef.name,config.getMcpServers()||{});if(matched){if(!mcpServerMentions.some(m=>m.serverName===matched.serverName)){mcpServerMentions.push({originalAtPath,serverName:matched.serverName})}atPathToResolvedSpecMap.set(originalAtPath,buildMcpServerRef(matched.serverName));continue}onDebugMessage(`MCP server "${mcpServerRef.name}" not found among configured MCP servers. Available: ${Object.keys(config.getMcpServers()||{}).join(", ")||"(none)"}`);continue}const workspaceContext=config.getWorkspaceContext();const absolutePathName=path.isAbsolute(pathName)?pathName:path.resolve(workspaceContext.getDirectories()[0]||"",pathName);if(!isSubpath(configuredProjectTempDir,absolutePathName)&&!isSubpath(projectTempDir,absolutePathName)&&!workspaceContext.isPathWithinWorkspace(pathName)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const ignoredReason=getIgnoreReason(pathName);if(ignoredReason){const reason=ignoredReason;ignoredByReason[reason].push(pathName);const reasonText=reason==="both"?"ignored by both git and qwen":reason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}let resolvedSuccessfully=false;let sawNotFound=false;let deferredIgnoreReason;for(const dir of config.getWorkspaceContext().getDirectories()){try{const absolutePath=path.resolve(dir,pathName);const canonicalPath=await fs.realpath(absolutePath);const stats=await fs.stat(canonicalPath);if(!isSubpath(configuredProjectTempDir,canonicalPath)&&!isSubpath(projectTempDir,canonicalPath)&&!workspaceContext.isPathWithinWorkspace(canonicalPath)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const canonicalIgnoreReason=getIgnoreReason(canonicalPath);if(canonicalIgnoreReason){deferredIgnoreReason=canonicalIgnoreReason;const reasonText=canonicalIgnoreReason==="both"?"ignored by both git and qwen":canonicalIgnoreReason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}if(stats.isDirectory()){onDebugMessage(`Path ${pathName} resolved to directory.`)}else{onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`)}pathSpecsToRead.push(canonicalPath);atPathToResolvedSpecMap.set(originalAtPath,pathName);contentLabelsForDisplay.push(pathName);displayPaths.set(canonicalPath,pathName);const canonicalDisplays=displayPathsByCanonicalPath.get(canonicalPath)??new Set;canonicalDisplays.add(pathName);displayPathsByCanonicalPath.set(canonicalPath,canonicalDisplays);resolvedSuccessfully=true}catch(error){if(isNodeError(error)&&error.code==="ENOENT"){sawNotFound=true;continue}else{onDebugMessage(`Error stating path ${pathName}: ${getErrorMessage(error)}. Path ${pathName} will be skipped.`)}}if(resolvedSuccessfully){break}}if(!resolvedSuccessfully&&sawNotFound){let reanchored=false;if(config.isOmniEnabled?.()){const{reanchorRememberedMedia}=await import("./omni-IFTMWBMU.js");for(const dir of config.getWorkspaceContext().getDirectories()){const anchor=await reanchorRememberedMedia(config,path.resolve(dir,pathName));if(!anchor)continue;rememberedMediaRefs.push({originalAtPath,pathName,annotation:anchor.annotation});atPathToResolvedSpecMap.set(originalAtPath,pathName);onDebugMessage(`Path ${pathName} is gone but remembered; re-anchored as ${anchor.resourceId} (bytes unavailable).`);reanchored=true;break}}if(!reanchored){onDebugMessage(`Path ${pathName} not found. Path ${pathName} will be skipped.`)}}if(!resolvedSuccessfully&&deferredIgnoreReason){ignoredByReason[deferredIgnoreReason].push(pathName)}}const buildInitialQueryText=__name(()=>{let text="";for(let i=0;i<commandParts.length;i++){const part=commandParts[i];if(part.type==="text"){text+=part.content}else{const resolvedSpec=atPathToResolvedSpecMap.get(part.content);if(i>0&&text.length>0&&!text.endsWith(" ")){const prevPart=commandParts[i-1];if(prevPart.type==="text"||prevPart.type==="atPath"){text+=" "}}if(resolvedSpec){text+=`@${resolvedSpec}`}else{if(i>0&&text.length>0&&!text.endsWith(" ")&&!part.content.startsWith(" ")){text+=" "}text+=part.content}}}return text.trim()},"buildInitialQueryText");let initialQueryText=buildInitialQueryText();const totalIgnored=ignoredByReason["git"].length+ignoredByReason["qwen"].length+ignoredByReason["both"].length;if(totalIgnored>0){const messages=[];if(ignoredByReason["git"].length){messages.push(`Git-ignored: ${ignoredByReason["git"].join(", ")}`)}if(ignoredByReason["qwen"].length){messages.push(`Qwen-ignored: ${ignoredByReason["qwen"].join(", ")}`)}if(ignoredByReason["both"].length){messages.push(`Ignored by both: ${ignoredByReason["both"].join(", ")}`)}const message=`Ignored ${totalIgnored} files:
4
- ${messages.join("\n")}`;onDebugMessage(message)}const resourceReads=await Promise.allSettled(mcpResourceRefs.map(ref=>config.getToolRegistry().readMcpResource(ref.serverName,ref.uri,{signal})));const urlMediaParts=[];const urlMediaDisplays=[];const urlMediaLabels=[];if(urlMediaRefs.length>0){const core=await import("./omni-IFTMWBMU.js");for(let i=0;i<urlMediaRefs.length;i++){const ref=urlMediaRefs[i];const callId=`client-url-media-${userMessageTimestamp}-${i}`;const hostLabel=(()=>{try{return new URL(ref.url).hostname}catch{return"invalid-url"}})();let tempPartPath;try{const store=new core.OmniObjectStore(config.storage.getQwenDir());const downloadsDir=path.join(store.getOmniRootDir(),"downloads");const downloaded=await core.downloadMediaUrl({url:ref.url,downloadsDir,maxBytes:core.effectiveMaxDownloadFileBytes(config),signal});tempPartPath=downloaded.partPath;const urlBase=path.basename(new URL(ref.url).pathname)||hostLabel;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};const sniffedModality=await core.sniffFileModality(downloaded.partPath);if(sniffedModality&&!modalities[sniffedModality]){urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Skipped ${urlBase}: the active model does not accept ${sniffedModality} input.`,confirmationDetails:void 0});continue}const delivery=await core.processMediaForOmniDelivery(downloaded.partPath,config,{signal,displayName:urlBase,sourceUrl:ref.url});const transcriptParts=core.buildTranscriptParts(urlBase,delivery.transcripts);const additionalParts=core.buildAdditionalMediaParts(urlBase,delivery.additionalMedia);const handleParts=delivery.resourceId?[{text:core.formatResourceHandleText(urlBase,delivery.resourceId)}]:[];if(delivery.omission){urlMediaParts.push(...handleParts);urlMediaParts.push({text:core.formatOmissionText(urlBase,delivery.omission.reason)});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Media omitted by the omni transport guard: ${urlBase}`,confirmationDetails:void 0});continue}if(!delivery.fileUri&&transcriptParts.length>0){urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} and delivered as transcript (omni policy).`,confirmationDetails:void 0});continue}urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push({fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName:urlBase}});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} (${delivery.recognized.modality}, ${(delivery.recognized.sizeBytes/1024/1024).toFixed(1)}MB) and delivered via omni upload${delivery.degraded?" (degraded by media policy)":""}.`,confirmationDetails:void 0})}catch(error){if(signal.aborted){if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}return{processedQuery:null,shouldProceed:false,toolDisplays:[...urlMediaDisplays],filesRead:urlMediaLabels}}const reason=getErrorMessage(error);onDebugMessage(`Failed to localize media URL ${ref.url}: ${reason}`);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Failed to fetch media from ${hostLabel}: ${reason}`,confirmationDetails:void 0})}finally{if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}}}}const resourceParts=[];const resourceDisplays=[];const resourceLabels=[];for(let i=0;i<mcpResourceRefs.length;i++){const ref=mcpResourceRefs[i];const label=`${ref.serverName}:${ref.uri}`;const callId=`client-mcp-resource-${userMessageTimestamp}-${i}`;const outcome=resourceReads[i];if(outcome.status==="rejected"){onDebugMessage(`Failed to read MCP resource ${label}: ${getErrorMessage(outcome.reason)}`);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Error",resultDisplay:`Failed to read resource ${label}: ${getErrorMessage(outcome.reason)}`,confirmationDetails:void 0});continue}const formatted=formatMcpResourceContents(outcome.value,label);if(formatted.parts.length>0){resourceParts.push(...formatted.parts)}else{resourceParts.push({text:emptyMcpResourceText(formatted,label)})}resourceLabels.push(label);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Success",resultDisplay:summarizeMcpResource(formatted),confirmationDetails:void 0})}if(pathSpecsToRead.length===0&&mcpResourceRefs.length===0&&mcpServerMentions.length===0&&extensionMentions.length===0&&sessionMentions.length===0&&urlMediaRefs.length===0){onDebugMessage("No valid file paths found in @ commands to read.");if(initialQueryText==="@"&&query.trim()==="@"){return{processedQuery:[{text:query}],shouldProceed:true}}else if(!initialQueryText&&query){return{processedQuery:[{text:query}],shouldProceed:true}}return{processedQuery:[{text:initialQueryText||query}],shouldProceed:true}}let extensionContextBudgetRemaining=EXTENSION_CONTEXT_BUDGET;const scopedMentionEntries=[];for(let i=0;i<extensionMentions.length;i++){const{originalAtPath,extension}=extensionMentions[i];const displayName=getSanitizedExtensionDisplayName(extension);const callId=`client-extension-${userMessageTimestamp}-${i}`;const context=await buildExtensionMentionContext(extension,{remainingBudget:extensionContextBudgetRemaining,signal,onDebugMessage});extensionContextBudgetRemaining=context.remainingBudget;scopedMentionEntries.push({originalAtPath,part:{text:context.text},label:buildExtensionRef(extension.name),display:{callId,name:"Activate Extension",description:`Activated extension ${displayName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}for(let i=0;i<mcpServerMentions.length;i++){const{originalAtPath,serverName}=mcpServerMentions[i];scopedMentionEntries.push({originalAtPath,part:{text:buildMcpServerContextText(config,serverName)},label:buildMcpServerRef(serverName),display:{callId:`client-mcp-server-${userMessageTimestamp}-${i}`,name:"Activate MCP Server",description:`Activated MCP server ${serverName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const resolvedSessionIds=new Set;for(let i=0;i<sessionMentions.length;i++){const{originalAtPath,ref}=sessionMentions[i];const callId=`client-session-${userMessageTimestamp}-${i}`;let sessionId=ref.id;if(!sessionId&&ref.title){let matches=[];try{matches=await new SessionService(config.getProjectRoot()).findSessionsByTitle(ref.title)}catch(error){const reason=`Could not look up sessions matching "@${originalAtPath.substring(1)}" (${getErrorMessage(error)}); try a session id instead.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(matches.length===1){sessionId=matches[0].sessionId}else{const reason=matches.length===0?`No session matches "@${originalAtPath.substring(1)}".`:`"@${originalAtPath.substring(1)}" is ambiguous (${matches.length} matches); use the picker or a session id.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}}if(!sessionId){const reason=`Session reference "@${originalAtPath.substring(1)}" could not be resolved.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??ref.id??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??ref.id??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(resolvedSessionIds.has(sessionId)){onDebugMessage(`Session reference "@${originalAtPath.substring(1)}" resolves to session ${sessionId}, which was already referenced; skipping duplicate.`);continue}resolvedSessionIds.add(sessionId);let resolved;try{resolved=await new SessionReferenceService(config.getProjectRoot()).resolve(sessionId,ref.title?{title:ref.title}:{})}catch(error){const reason=`Failed to load session "${sessionId}" (${getErrorMessage(error)}); the transcript may be corrupted or unreadable.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if("notFound"in resolved){const reason=`Session "${sessionId}" not found in this project.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}scopedMentionEntries.push({originalAtPath,part:{text:resolved.text},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Referenced session "${resolved.meta.title}"${resolved.truncated?" (truncated)":""}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const scopedMentionOrder=new Map(atPathCommandParts.map((part,index)=>[part.content,index]));scopedMentionEntries.sort((a,b)=>(scopedMentionOrder.get(a.originalAtPath)??Number.MAX_SAFE_INTEGER)-(scopedMentionOrder.get(b.originalAtPath)??Number.MAX_SAFE_INTEGER));const scopedMentionParts=scopedMentionEntries.map(entry=>entry.part);const scopedMentionLabels=scopedMentionEntries.map(entry=>entry.label);const scopedMentionDisplays=scopedMentionEntries.map(entry=>entry.display);const fileParts=[];let fileDisplays=[];const revalidatedPathSpecs=[];const revalidatedDisplayPaths=new Map;const validatedPathIdentities=new Map;const pruneSkippedPath=__name(approvedPath=>{const displayPath=displayPaths.get(approvedPath);const displayLabels=displayPathsByCanonicalPath.get(approvedPath)??new Set(displayPath?[displayPath]:[]);for(const[originalAtPath,resolvedSpec]of atPathToResolvedSpecMap){if(resolvedSpec===approvedPath||displayLabels.has(resolvedSpec)){atPathToResolvedSpecMap.delete(originalAtPath)}}for(let index=contentLabelsForDisplay.length-1;index>=0;index--){const label=contentLabelsForDisplay[index];if(label===approvedPath||displayLabels.has(label)){contentLabelsForDisplay.splice(index,1)}}},"pruneSkippedPath");for(const approvedPath of pathSpecsToRead){try{const currentPath=await fs.realpath(approvedPath);const stats=await fs.stat(currentPath);if(currentPath===approvedPath&&(stats.isFile()||stats.isDirectory())&&(isSubpath(configuredProjectTempDir,currentPath)||isSubpath(projectTempDir,currentPath)||config.getWorkspaceContext().isPathWithinWorkspace(currentPath))&&getIgnoreReason(currentPath)===void 0){revalidatedPathSpecs.push(currentPath);const displayPath=displayPaths.get(approvedPath);if(displayPath)revalidatedDisplayPaths.set(currentPath,displayPath);validatedPathIdentities.set(currentPath,{dev:stats.dev,ino:stats.ino})}else{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} failed revalidation and will be skipped.`)}}catch{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} changed before it could be read and will be skipped.`)}}initialQueryText=buildInitialQueryText();if(revalidatedPathSpecs.length>0){try{const result=await readManyFiles(config,{paths:revalidatedPathSpecs,signal,preserveUnsupportedImageForBridge:shouldRunVisionBridge(config),validatedPathIdentities,displayPaths:revalidatedDisplayPaths});const parts=Array.isArray(result.contentParts)?result.contentParts:[result.contentParts];fileDisplays=result.files.map((file,index)=>({callId:`client-read-${userMessageTimestamp}-${index}`,name:file.isDirectory?"Read Directory":"Read File",description:`@${path.basename(file.filePath)}`,status:file.error?"Error":"Success",resultDisplay:file.error?`Failed to read ${path.basename(file.filePath)}: ${file.error}`:void 0,confirmationDetails:void 0}));if(parts.length>0&&!result.error){for(const part of parts){fileParts.push(typeof part==="string"?{text:part}:part)}}else{onDebugMessage("readManyFiles returned no content or empty content.")}}catch(error){const errorToolCallDisplay={callId:`client-read-${userMessageTimestamp}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:`Error reading files (${contentLabelsForDisplay.join(", ")}): ${getErrorMessage(error)}`,confirmationDetails:void 0};const errorMessage=typeof errorToolCallDisplay.resultDisplay==="string"?errorToolCallDisplay.resultDisplay:void 0;const labelsOnError=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels];return{processedQuery:null,shouldProceed:false,toolDisplays:[...scopedMentionDisplays,...resourceDisplays,...urlMediaDisplays,errorToolCallDisplay],filesRead:labelsOnError,recording:{filesRead:labelsOnError,status:"error",message:errorMessage}}}}const rememberedMediaParts=rememberedMediaRefs.flatMap(ref=>[{text:ref.annotation},{text:`\u3010\u5A92\u4F53\u7F3A\u5931\u3011${ref.pathName}\uFF1A\u6587\u4EF6\u5DF2\u4E0D\u5728\u78C1\u76D8\u4E0A\uFF0C\u65E0\u6CD5\u6295\u9012\u753B\u9762/\u97F3\u9891\u3002\u5176\u5904\u7406\u8BB0\u5FC6\u4ECD\u53EF\u7528\u2014\u2014\u7528\u4E0A\u9762\u7684\u53E5\u67C4\u8C03\u7528 omni_recall_media_memory \u53D6\u56DE\u3002`}]);const processedQueryParts=[{text:initialQueryText},...scopedMentionParts,...fileParts,...resourceParts,...urlMediaParts,...rememberedMediaParts];const allLabels=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels,...rememberedMediaRefs.map(ref=>`${ref.pathName} (\u8BB0\u5FC6)`)];return{processedQuery:processedQueryParts,shouldProceed:true,toolDisplays:[...scopedMentionDisplays,...fileDisplays,...resourceDisplays,...urlMediaDisplays],filesRead:allLabels,recording:{filesRead:allLabels,status:"success"}}}__name(resolveAtCommandQuery,"resolveAtCommandQuery");async function handleAtCommand(params){const result=await resolveAtCommandQuery(params);if(result.recording){const chatRecorder=params.config.getChatRecordingService?.();chatRecorder?.recordAtCommand({filesRead:result.recording.filesRead,status:result.recording.status,...result.recording.message?{message:result.recording.message}:{},userText:params.query})}if(params.addItem&&result.toolDisplays&&result.toolDisplays.length>0){const toolGroupItem={type:"tool_group",tools:result.toolDisplays};params.addItem(toolGroupItem,params.messageId)}return{processedQuery:result.processedQuery,shouldProceed:result.shouldProceed,toolDisplays:result.toolDisplays,filesRead:result.filesRead}}__name(handleAtCommand,"handleAtCommand");export{matchMcpServerPrefix,buildMcpResourceRef,MAX_SUGGESTIONS_TO_SHOW,MAX_SUGGESTION_LABEL_WIDTH,prepareSuggestionLabel,normalizeDescription,getExtensionSuggestions,SESSION_MENTION_PREFIX,buildSessionRef,parseMcpServerRef,buildMcpServerRef,matchMcpServerByRef,buildMcpServerContextText,extractAtPathCommands,resolveAtCommandQuery,handleAtCommand};
3
+ import{EXTENSION_CONTEXT_BUDGET,buildExtensionMentionContext,buildExtensionRef,getSanitizedExtensionDisplayName,matchExtensionByRef,parseExtensionRef,sanitizeDisplayText}from"./chunk-EHM4KL2U.js";import{t}from"./chunk-5YULNQF3.js";import{SessionReferenceService,readManyFiles}from"./chunk-G3COGFSZ.js";import{emptyMcpResourceText,formatMcpResourceContents,summarizeMcpResource}from"./chunk-46VUDNCL.js";import{SessionService}from"./chunk-POMEWCFJ.js";import{shouldRunVisionBridge}from"./chunk-MJEL7DIE.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{isSubpath,unescapePath,unescapeShellSpecials}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage,isNodeError}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs/promises";import*as path from"node:path";init_esbuild_shims();function matchMcpServerPrefix(input,serverNames){let serverName=null;for(const name of serverNames){if(input.startsWith(`${name}:`)&&(serverName===null||name.length>serverName.length)){serverName=name}}if(serverName===null)return null;return{serverName,rest:input.slice(serverName.length+1)}}__name(matchMcpServerPrefix,"matchMcpServerPrefix");function buildMcpResourceRef(serverName,uri){return`${serverName}:${uri}`}__name(buildMcpResourceRef,"buildMcpResourceRef");init_esbuild_shims();init_esbuild_shims();var MAX_SUGGESTIONS_TO_SHOW=8;var MAX_SUGGESTION_LABEL_WIDTH=150;function prepareSuggestionLabel(label,matchedIndex,userInput,isExpanded=false){const hasMatch=matchedIndex!==void 0&&matchedIndex>=0&&matchedIndex<label.length&&userInput.length>0;if(!hasMatch){return{before:!isExpanded&&label.length>MAX_SUGGESTION_LABEL_WIDTH?label.slice(0,MAX_SUGGESTION_LABEL_WIDTH)+"...":label,match:"",after:""}}const matchLength=userInput.length;let before="";let match="";let after="";if(isExpanded||label.length<=MAX_SUGGESTION_LABEL_WIDTH){before=label.slice(0,matchedIndex);match=label.slice(matchedIndex,matchedIndex+matchLength);after=label.slice(matchedIndex+matchLength)}else if(matchLength>=MAX_SUGGESTION_LABEL_WIDTH){match=label.slice(matchedIndex,matchedIndex+MAX_SUGGESTION_LABEL_WIDTH-1)+"..."}else{const contextSpace=MAX_SUGGESTION_LABEL_WIDTH-matchLength;const beforeSpace=Math.floor(contextSpace/2);const afterSpace=Math.ceil(contextSpace/2);let start=matchedIndex-beforeSpace;let end=matchedIndex+matchLength+afterSpace;if(start<0){end+=-start;start=0}if(end>label.length){start-=end-label.length;end=label.length}start=Math.max(0,start);const finalMatchIndex=matchedIndex-start;const slicedLabel=label.slice(start,end);before=slicedLabel.slice(0,finalMatchIndex);match=slicedLabel.slice(finalMatchIndex,finalMatchIndex+matchLength);after=slicedLabel.slice(finalMatchIndex+matchLength);if(start>0){before=before.length>=3?"..."+before.slice(3):"..."}if(end<label.length){after=after.length>=3?after.slice(0,-3)+"...":"..."}}return{before,match,after}}__name(prepareSuggestionLabel,"prepareSuggestionLabel");function normalizeDescription(description){return description.replace(/\s+/g," ").trim()}__name(normalizeDescription,"normalizeDescription");function getExtensionSuggestions(config,pattern){if(!config)return[];if(config.isTrustedFolder?.()===false)return[];const extensions=config.getActiveExtensions?.()??[];if(extensions.length===0)return[];const query=pattern.toLowerCase();return extensions.map(ext=>({ext,safeLabel:sanitizeDisplayText(ext.displayName||ext.name)||ext.name})).filter(({safeLabel,ext})=>{const label=safeLabel.toLowerCase();const name=ext.name.toLowerCase();return label.includes(query)||name.includes(query)}).sort((a,b)=>{const aName=a.safeLabel.toLowerCase();const bName=b.safeLabel.toLowerCase();const aPrefix=aName.startsWith(query)?0:1;const bPrefix=bName.startsWith(query)?0:1;if(aPrefix!==bPrefix)return aPrefix-bPrefix;return aName.localeCompare(bName)}).slice(0,MAX_SUGGESTIONS_TO_SHOW).map(({ext,safeLabel})=>({label:safeLabel,value:buildExtensionRef(ext.name),description:ext.config.description?sanitizeDisplayText(ext.config.description)??void 0:void 0,sourceBadge:t("Extension"),isDirectory:false,category:"extension"}))}__name(getExtensionSuggestions,"getExtensionSuggestions");init_esbuild_shims();var SESSION_MENTION_PREFIX="session:";var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function isSessionId(value){return UUID_RE.test(value.trim())}__name(isSessionId,"isSessionId");function parseSessionRef(pathName){if(!pathName.startsWith(SESSION_MENTION_PREFIX))return null;const rawRemainder=pathName.slice(SESSION_MENTION_PREFIX.length).trim();const remainder=process.platform==="win32"?unescapeShellSpecials(rawRemainder):rawRemainder;if(remainder.length===0)return null;return isSessionId(remainder)?{id:remainder}:{title:remainder}}__name(parseSessionRef,"parseSessionRef");function buildSessionRef(idOrTitle){return`${SESSION_MENTION_PREFIX}${idOrTitle}`}__name(buildSessionRef,"buildSessionRef");init_esbuild_shims();var MCP_SERVER_REF_PREFIX="mcp:";function parseMcpServerRef(pathName){if(!pathName.startsWith(MCP_SERVER_REF_PREFIX))return null;const name=pathName.slice(MCP_SERVER_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseMcpServerRef,"parseMcpServerRef");function buildMcpServerRef(serverName){return`${MCP_SERVER_REF_PREFIX}${serverName}`}__name(buildMcpServerRef,"buildMcpServerRef");function matchMcpServerByRef(name,servers){const lower=name.toLowerCase();const matchedName=Object.keys(servers).find(serverName=>serverName.toLowerCase()===lower);if(!matchedName)return void 0;return{serverName:matchedName,server:servers[matchedName]}}__name(matchMcpServerByRef,"matchMcpServerByRef");function buildMcpServerContextText(config,serverName){const lines=[`--- MCP Server: ${serverName} ---`,`The user explicitly mentioned this MCP server. Prefer using tools and resources from this server when relevant for this turn. This is advisory context, not a hard restriction.`];const prompts=config.getPromptRegistry?.()?.getPromptsByServer(serverName)??[];const resources=config.getResourceRegistry?.()?.getResourcesByServer(serverName)??[];const details=[];if(resources.length>0){details.push(`- Resources: ${resources.length}`)}if(prompts.length>0){details.push(`- Prompts: ${prompts.length}`)}if(details.length>0){lines.push("Available capabilities from this MCP server:");lines.push(...details)}lines.push(`--- End MCP Server: ${serverName} ---`);return lines.join("\n")}__name(buildMcpServerContextText,"buildMcpServerContextText");function parseAllAtCommands(query){const parts=[];let currentIndex=0;while(currentIndex<query.length){let atIndex=-1;let nextSearchIndex=currentIndex;while(nextSearchIndex<query.length){if(query[nextSearchIndex]==="@"&&(nextSearchIndex===0||query[nextSearchIndex-1]!=="\\")){atIndex=nextSearchIndex;break}nextSearchIndex++}if(atIndex===-1){if(currentIndex<query.length){parts.push({type:"text",content:query.substring(currentIndex)})}break}if(atIndex>currentIndex){parts.push({type:"text",content:query.substring(currentIndex,atIndex)})}const isUrlRef=/^https?:\/\//i.test(query.slice(atIndex+1));const NON_URL_CHAR=/[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]/;let pathEndIndex=atIndex+1;let inEscape=false;while(pathEndIndex<query.length){const char=query[pathEndIndex];if(inEscape){inEscape=false}else if(char==="\\"){inEscape=true}else if(isUrlRef){if(NON_URL_CHAR.test(char))break}else if(/[,\s;!?()[\]{}]/.test(char)){break}else if(char==="."){const nextChar=pathEndIndex+1<query.length?query[pathEndIndex+1]:"";if(nextChar===""||/\s/.test(nextChar)){break}}pathEndIndex++}let rawAtPath=query.substring(atIndex,pathEndIndex);if(isUrlRef){const trimmed=rawAtPath.replace(/[.,;:!?]+$/,"");pathEndIndex=atIndex+trimmed.length;rawAtPath=trimmed}const atPath=unescapePath(rawAtPath);parts.push({type:"atPath",content:atPath});currentIndex=pathEndIndex}return parts.filter(part=>!(part.type==="text"&&part.content.trim()===""))}__name(parseAllAtCommands,"parseAllAtCommands");function extractAtPathCommands(query){return parseAllAtCommands(query).flatMap(part=>part.type==="atPath"&&part.content!=="@"?[part.content.substring(1)]:[])}__name(extractAtPathCommands,"extractAtPathCommands");function parseMcpResourceRef(pathName,mcpServerNames){const match=matchMcpServerPrefix(pathName,mcpServerNames);if(!match||!match.rest)return null;return{serverName:match.serverName,uri:match.rest}}__name(parseMcpResourceRef,"parseMcpResourceRef");async function resolveAtCommandQuery({query,config,onDebugMessage,messageId:userMessageTimestamp,signal}){const commandParts=parseAllAtCommands(query);const atPathCommandParts=commandParts.filter(part=>part.type==="atPath");if(atPathCommandParts.length===0){return{processedQuery:[{text:query}],shouldProceed:true}}const fileDiscovery=config.getFileService();const respectFileIgnore=config.getFileFilteringOptions();const configuredProjectTempDir=Storage.getGlobalTempDir();const projectTempDir=await fs.realpath(configuredProjectTempDir).catch(()=>path.resolve(configuredProjectTempDir));const pathSpecsToRead=[];const atPathToResolvedSpecMap=new Map;const contentLabelsForDisplay=[];const displayPaths=new Map;const displayPathsByCanonicalPath=new Map;const ignoredByReason={git:[],qwen:[],both:[]};const getIgnoreReason=__name(candidate=>{const gitIgnored=respectFileIgnore.respectGitIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:true,respectQwenIgnore:false});const qwenIgnored=respectFileIgnore.respectQwenIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:false,respectQwenIgnore:true});return gitIgnored&&qwenIgnored?"both":gitIgnored?"git":qwenIgnored?"qwen":void 0},"getIgnoreReason");const mcpServerNames=new Set(Object.keys(config.getMcpServers()||{}));const mcpResourceRefs=[];const mcpServerMentions=[];const activeExtensions=config.getActiveExtensions?.()??[];const extensionMentions=[];const sessionMentions=[];const urlMediaRefs=[];const rememberedMediaRefs=[];for(const atPathPart of atPathCommandParts){const originalAtPath=atPathPart.content;if(originalAtPath==="@"){onDebugMessage("Lone @ detected, will be treated as text in the modified query.");continue}const pathName=originalAtPath.substring(1);if(/^https?:\/\//i.test(pathName)&&config.isOmniEnabled?.()){const omni=await import("./omni-DJ5RGNKA.js");if(omni.isOmniDeliveryActive(config)&&omni.parseHttpUrlRef(pathName)){if(!urlMediaRefs.some(r=>r.url===pathName)){urlMediaRefs.push({originalAtPath,url:pathName})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}}const extRef=parseExtensionRef(pathName);if(extRef){const extension=matchExtensionByRef(extRef.name,activeExtensions);if(extension){if(!extensionMentions.some(m=>m.extension.name===extension.name)){extensionMentions.push({originalAtPath,extension})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}onDebugMessage(`Extension "${extRef.name}" not found among active extensions. Available: ${activeExtensions.map(e=>e.name).join(", ")||"(none)"}`);continue}const sessionRef=parseSessionRef(pathName);if(sessionRef){if(!sessionMentions.some(m=>(m.ref.id??m.ref.title)===(sessionRef.id??sessionRef.title))){sessionMentions.push({originalAtPath,ref:sessionRef})}atPathToResolvedSpecMap.set(originalAtPath,buildSessionRef(sessionRef.id??sessionRef.title));continue}const resourceRef=parseMcpResourceRef(pathName,mcpServerNames);if(resourceRef){mcpResourceRefs.push({originalAtPath,...resourceRef});atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}const mcpServerRef=parseMcpServerRef(pathName);if(mcpServerRef){const matched=matchMcpServerByRef(mcpServerRef.name,config.getMcpServers()||{});if(matched){if(!mcpServerMentions.some(m=>m.serverName===matched.serverName)){mcpServerMentions.push({originalAtPath,serverName:matched.serverName})}atPathToResolvedSpecMap.set(originalAtPath,buildMcpServerRef(matched.serverName));continue}onDebugMessage(`MCP server "${mcpServerRef.name}" not found among configured MCP servers. Available: ${Object.keys(config.getMcpServers()||{}).join(", ")||"(none)"}`);continue}const workspaceContext=config.getWorkspaceContext();const absolutePathName=path.isAbsolute(pathName)?pathName:path.resolve(workspaceContext.getDirectories()[0]||"",pathName);if(!isSubpath(configuredProjectTempDir,absolutePathName)&&!isSubpath(projectTempDir,absolutePathName)&&!workspaceContext.isPathWithinWorkspace(pathName)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const ignoredReason=getIgnoreReason(pathName);if(ignoredReason){const reason=ignoredReason;ignoredByReason[reason].push(pathName);const reasonText=reason==="both"?"ignored by both git and qwen":reason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}let resolvedSuccessfully=false;let sawNotFound=false;let deferredIgnoreReason;for(const dir of config.getWorkspaceContext().getDirectories()){try{const absolutePath=path.resolve(dir,pathName);const canonicalPath=await fs.realpath(absolutePath);const stats=await fs.stat(canonicalPath);if(!isSubpath(configuredProjectTempDir,canonicalPath)&&!isSubpath(projectTempDir,canonicalPath)&&!workspaceContext.isPathWithinWorkspace(canonicalPath)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const canonicalIgnoreReason=getIgnoreReason(canonicalPath);if(canonicalIgnoreReason){deferredIgnoreReason=canonicalIgnoreReason;const reasonText=canonicalIgnoreReason==="both"?"ignored by both git and qwen":canonicalIgnoreReason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}if(stats.isDirectory()){onDebugMessage(`Path ${pathName} resolved to directory.`)}else{onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`)}pathSpecsToRead.push(canonicalPath);atPathToResolvedSpecMap.set(originalAtPath,pathName);contentLabelsForDisplay.push(pathName);displayPaths.set(canonicalPath,pathName);const canonicalDisplays=displayPathsByCanonicalPath.get(canonicalPath)??new Set;canonicalDisplays.add(pathName);displayPathsByCanonicalPath.set(canonicalPath,canonicalDisplays);resolvedSuccessfully=true}catch(error){if(isNodeError(error)&&error.code==="ENOENT"){sawNotFound=true;continue}else{onDebugMessage(`Error stating path ${pathName}: ${getErrorMessage(error)}. Path ${pathName} will be skipped.`)}}if(resolvedSuccessfully){break}}if(!resolvedSuccessfully&&sawNotFound){let reanchored=false;if(config.isOmniEnabled?.()){const{reanchorRememberedMedia}=await import("./omni-DJ5RGNKA.js");for(const dir of config.getWorkspaceContext().getDirectories()){const anchor=await reanchorRememberedMedia(config,path.resolve(dir,pathName));if(!anchor)continue;rememberedMediaRefs.push({originalAtPath,pathName,annotation:anchor.annotation});atPathToResolvedSpecMap.set(originalAtPath,pathName);onDebugMessage(`Path ${pathName} is gone but remembered; re-anchored as ${anchor.resourceId} (bytes unavailable).`);reanchored=true;break}}if(!reanchored){onDebugMessage(`Path ${pathName} not found. Path ${pathName} will be skipped.`)}}if(!resolvedSuccessfully&&deferredIgnoreReason){ignoredByReason[deferredIgnoreReason].push(pathName)}}const buildInitialQueryText=__name(()=>{let text="";for(let i=0;i<commandParts.length;i++){const part=commandParts[i];if(part.type==="text"){text+=part.content}else{const resolvedSpec=atPathToResolvedSpecMap.get(part.content);if(i>0&&text.length>0&&!text.endsWith(" ")){const prevPart=commandParts[i-1];if(prevPart.type==="text"||prevPart.type==="atPath"){text+=" "}}if(resolvedSpec){text+=`@${resolvedSpec}`}else{if(i>0&&text.length>0&&!text.endsWith(" ")&&!part.content.startsWith(" ")){text+=" "}text+=part.content}}}return text.trim()},"buildInitialQueryText");let initialQueryText=buildInitialQueryText();const totalIgnored=ignoredByReason["git"].length+ignoredByReason["qwen"].length+ignoredByReason["both"].length;if(totalIgnored>0){const messages=[];if(ignoredByReason["git"].length){messages.push(`Git-ignored: ${ignoredByReason["git"].join(", ")}`)}if(ignoredByReason["qwen"].length){messages.push(`Qwen-ignored: ${ignoredByReason["qwen"].join(", ")}`)}if(ignoredByReason["both"].length){messages.push(`Ignored by both: ${ignoredByReason["both"].join(", ")}`)}const message=`Ignored ${totalIgnored} files:
4
+ ${messages.join("\n")}`;onDebugMessage(message)}const resourceReads=await Promise.allSettled(mcpResourceRefs.map(ref=>config.getToolRegistry().readMcpResource(ref.serverName,ref.uri,{signal})));const urlMediaParts=[];const urlMediaDisplays=[];const urlMediaLabels=[];if(urlMediaRefs.length>0){const core=await import("./omni-DJ5RGNKA.js");for(let i=0;i<urlMediaRefs.length;i++){const ref=urlMediaRefs[i];const callId=`client-url-media-${userMessageTimestamp}-${i}`;const hostLabel=(()=>{try{return new URL(ref.url).hostname}catch{return"invalid-url"}})();let tempPartPath;try{const store=new core.OmniObjectStore(config.storage.getQwenDir());const downloadsDir=path.join(store.getOmniRootDir(),"downloads");const downloaded=await core.downloadMediaUrl({url:ref.url,downloadsDir,maxBytes:core.effectiveMaxDownloadFileBytes(config),signal});tempPartPath=downloaded.partPath;const urlBase=path.basename(new URL(ref.url).pathname)||hostLabel;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};const sniffedModality=await core.sniffFileModality(downloaded.partPath);if(sniffedModality&&!modalities[sniffedModality]){urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Skipped ${urlBase}: the active model does not accept ${sniffedModality} input.`,confirmationDetails:void 0});continue}const delivery=await core.processMediaForOmniDelivery(downloaded.partPath,config,{signal,displayName:urlBase,sourceUrl:ref.url});const transcriptParts=core.buildTranscriptParts(urlBase,delivery.transcripts);const additionalParts=core.buildAdditionalMediaParts(urlBase,delivery.additionalMedia);const handleParts=delivery.resourceId?[{text:core.formatResourceHandleText(urlBase,delivery.resourceId)}]:[];if(delivery.omission){urlMediaParts.push(...handleParts);urlMediaParts.push({text:core.formatOmissionText(urlBase,delivery.omission.reason)});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Media omitted by the omni transport guard: ${urlBase}`,confirmationDetails:void 0});continue}if(!delivery.fileUri&&transcriptParts.length>0){urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} and delivered as transcript (omni policy).`,confirmationDetails:void 0});continue}urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push({fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName:urlBase}});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} (${delivery.recognized.modality}, ${(delivery.recognized.sizeBytes/1024/1024).toFixed(1)}MB) and delivered via omni upload${delivery.degraded?" (degraded by media policy)":""}.`,confirmationDetails:void 0})}catch(error){if(signal.aborted){if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}return{processedQuery:null,shouldProceed:false,toolDisplays:[...urlMediaDisplays],filesRead:urlMediaLabels}}const reason=getErrorMessage(error);onDebugMessage(`Failed to localize media URL ${ref.url}: ${reason}`);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Failed to fetch media from ${hostLabel}: ${reason}`,confirmationDetails:void 0})}finally{if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}}}}const resourceParts=[];const resourceDisplays=[];const resourceLabels=[];for(let i=0;i<mcpResourceRefs.length;i++){const ref=mcpResourceRefs[i];const label=`${ref.serverName}:${ref.uri}`;const callId=`client-mcp-resource-${userMessageTimestamp}-${i}`;const outcome=resourceReads[i];if(outcome.status==="rejected"){onDebugMessage(`Failed to read MCP resource ${label}: ${getErrorMessage(outcome.reason)}`);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Error",resultDisplay:`Failed to read resource ${label}: ${getErrorMessage(outcome.reason)}`,confirmationDetails:void 0});continue}const formatted=formatMcpResourceContents(outcome.value,label);if(formatted.parts.length>0){resourceParts.push(...formatted.parts)}else{resourceParts.push({text:emptyMcpResourceText(formatted,label)})}resourceLabels.push(label);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Success",resultDisplay:summarizeMcpResource(formatted),confirmationDetails:void 0})}if(pathSpecsToRead.length===0&&mcpResourceRefs.length===0&&mcpServerMentions.length===0&&extensionMentions.length===0&&sessionMentions.length===0&&urlMediaRefs.length===0){onDebugMessage("No valid file paths found in @ commands to read.");if(initialQueryText==="@"&&query.trim()==="@"){return{processedQuery:[{text:query}],shouldProceed:true}}else if(!initialQueryText&&query){return{processedQuery:[{text:query}],shouldProceed:true}}return{processedQuery:[{text:initialQueryText||query}],shouldProceed:true}}let extensionContextBudgetRemaining=EXTENSION_CONTEXT_BUDGET;const scopedMentionEntries=[];for(let i=0;i<extensionMentions.length;i++){const{originalAtPath,extension}=extensionMentions[i];const displayName=getSanitizedExtensionDisplayName(extension);const callId=`client-extension-${userMessageTimestamp}-${i}`;const context=await buildExtensionMentionContext(extension,{remainingBudget:extensionContextBudgetRemaining,signal,onDebugMessage});extensionContextBudgetRemaining=context.remainingBudget;scopedMentionEntries.push({originalAtPath,part:{text:context.text},label:buildExtensionRef(extension.name),display:{callId,name:"Activate Extension",description:`Activated extension ${displayName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}for(let i=0;i<mcpServerMentions.length;i++){const{originalAtPath,serverName}=mcpServerMentions[i];scopedMentionEntries.push({originalAtPath,part:{text:buildMcpServerContextText(config,serverName)},label:buildMcpServerRef(serverName),display:{callId:`client-mcp-server-${userMessageTimestamp}-${i}`,name:"Activate MCP Server",description:`Activated MCP server ${serverName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const resolvedSessionIds=new Set;for(let i=0;i<sessionMentions.length;i++){const{originalAtPath,ref}=sessionMentions[i];const callId=`client-session-${userMessageTimestamp}-${i}`;let sessionId=ref.id;if(!sessionId&&ref.title){let matches=[];try{matches=await new SessionService(config.getProjectRoot()).findSessionsByTitle(ref.title)}catch(error){const reason=`Could not look up sessions matching "@${originalAtPath.substring(1)}" (${getErrorMessage(error)}); try a session id instead.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(matches.length===1){sessionId=matches[0].sessionId}else{const reason=matches.length===0?`No session matches "@${originalAtPath.substring(1)}".`:`"@${originalAtPath.substring(1)}" is ambiguous (${matches.length} matches); use the picker or a session id.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}}if(!sessionId){const reason=`Session reference "@${originalAtPath.substring(1)}" could not be resolved.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??ref.id??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??ref.id??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(resolvedSessionIds.has(sessionId)){onDebugMessage(`Session reference "@${originalAtPath.substring(1)}" resolves to session ${sessionId}, which was already referenced; skipping duplicate.`);continue}resolvedSessionIds.add(sessionId);let resolved;try{resolved=await new SessionReferenceService(config.getProjectRoot()).resolve(sessionId,ref.title?{title:ref.title}:{})}catch(error){const reason=`Failed to load session "${sessionId}" (${getErrorMessage(error)}); the transcript may be corrupted or unreadable.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if("notFound"in resolved){const reason=`Session "${sessionId}" not found in this project.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}scopedMentionEntries.push({originalAtPath,part:{text:resolved.text},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Referenced session "${resolved.meta.title}"${resolved.truncated?" (truncated)":""}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const scopedMentionOrder=new Map(atPathCommandParts.map((part,index)=>[part.content,index]));scopedMentionEntries.sort((a,b)=>(scopedMentionOrder.get(a.originalAtPath)??Number.MAX_SAFE_INTEGER)-(scopedMentionOrder.get(b.originalAtPath)??Number.MAX_SAFE_INTEGER));const scopedMentionParts=scopedMentionEntries.map(entry=>entry.part);const scopedMentionLabels=scopedMentionEntries.map(entry=>entry.label);const scopedMentionDisplays=scopedMentionEntries.map(entry=>entry.display);const fileParts=[];let fileDisplays=[];const revalidatedPathSpecs=[];const revalidatedDisplayPaths=new Map;const validatedPathIdentities=new Map;const pruneSkippedPath=__name(approvedPath=>{const displayPath=displayPaths.get(approvedPath);const displayLabels=displayPathsByCanonicalPath.get(approvedPath)??new Set(displayPath?[displayPath]:[]);for(const[originalAtPath,resolvedSpec]of atPathToResolvedSpecMap){if(resolvedSpec===approvedPath||displayLabels.has(resolvedSpec)){atPathToResolvedSpecMap.delete(originalAtPath)}}for(let index=contentLabelsForDisplay.length-1;index>=0;index--){const label=contentLabelsForDisplay[index];if(label===approvedPath||displayLabels.has(label)){contentLabelsForDisplay.splice(index,1)}}},"pruneSkippedPath");for(const approvedPath of pathSpecsToRead){try{const currentPath=await fs.realpath(approvedPath);const stats=await fs.stat(currentPath);if(currentPath===approvedPath&&(stats.isFile()||stats.isDirectory())&&(isSubpath(configuredProjectTempDir,currentPath)||isSubpath(projectTempDir,currentPath)||config.getWorkspaceContext().isPathWithinWorkspace(currentPath))&&getIgnoreReason(currentPath)===void 0){revalidatedPathSpecs.push(currentPath);const displayPath=displayPaths.get(approvedPath);if(displayPath)revalidatedDisplayPaths.set(currentPath,displayPath);validatedPathIdentities.set(currentPath,{dev:stats.dev,ino:stats.ino})}else{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} failed revalidation and will be skipped.`)}}catch{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} changed before it could be read and will be skipped.`)}}initialQueryText=buildInitialQueryText();if(revalidatedPathSpecs.length>0){try{const result=await readManyFiles(config,{paths:revalidatedPathSpecs,signal,preserveUnsupportedImageForBridge:shouldRunVisionBridge(config),validatedPathIdentities,displayPaths:revalidatedDisplayPaths});const parts=Array.isArray(result.contentParts)?result.contentParts:[result.contentParts];fileDisplays=result.files.map((file,index)=>({callId:`client-read-${userMessageTimestamp}-${index}`,name:file.isDirectory?"Read Directory":"Read File",description:`@${path.basename(file.filePath)}`,status:file.error?"Error":"Success",resultDisplay:file.error?`Failed to read ${path.basename(file.filePath)}: ${file.error}`:void 0,confirmationDetails:void 0}));if(parts.length>0&&!result.error){for(const part of parts){fileParts.push(typeof part==="string"?{text:part}:part)}}else{onDebugMessage("readManyFiles returned no content or empty content.")}}catch(error){const errorToolCallDisplay={callId:`client-read-${userMessageTimestamp}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:`Error reading files (${contentLabelsForDisplay.join(", ")}): ${getErrorMessage(error)}`,confirmationDetails:void 0};const errorMessage=typeof errorToolCallDisplay.resultDisplay==="string"?errorToolCallDisplay.resultDisplay:void 0;const labelsOnError=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels];return{processedQuery:null,shouldProceed:false,toolDisplays:[...scopedMentionDisplays,...resourceDisplays,...urlMediaDisplays,errorToolCallDisplay],filesRead:labelsOnError,recording:{filesRead:labelsOnError,status:"error",message:errorMessage}}}}const rememberedMediaParts=rememberedMediaRefs.flatMap(ref=>[{text:ref.annotation},{text:`\u3010\u5A92\u4F53\u7F3A\u5931\u3011${ref.pathName}\uFF1A\u6587\u4EF6\u5DF2\u4E0D\u5728\u78C1\u76D8\u4E0A\uFF0C\u65E0\u6CD5\u6295\u9012\u753B\u9762/\u97F3\u9891\u3002\u5176\u5904\u7406\u8BB0\u5FC6\u4ECD\u53EF\u7528\u2014\u2014\u7528\u4E0A\u9762\u7684\u53E5\u67C4\u8C03\u7528 omni_recall_media_memory \u53D6\u56DE\u3002`}]);const processedQueryParts=[{text:initialQueryText},...scopedMentionParts,...fileParts,...resourceParts,...urlMediaParts,...rememberedMediaParts];const allLabels=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels,...rememberedMediaRefs.map(ref=>`${ref.pathName} (\u8BB0\u5FC6)`)];return{processedQuery:processedQueryParts,shouldProceed:true,toolDisplays:[...scopedMentionDisplays,...fileDisplays,...resourceDisplays,...urlMediaDisplays],filesRead:allLabels,recording:{filesRead:allLabels,status:"success"}}}__name(resolveAtCommandQuery,"resolveAtCommandQuery");async function handleAtCommand(params){const result=await resolveAtCommandQuery(params);if(result.recording){const chatRecorder=params.config.getChatRecordingService?.();chatRecorder?.recordAtCommand({filesRead:result.recording.filesRead,status:result.recording.status,...result.recording.message?{message:result.recording.message}:{},userText:params.query})}if(params.addItem&&result.toolDisplays&&result.toolDisplays.length>0){const toolGroupItem={type:"tool_group",tools:result.toolDisplays};params.addItem(toolGroupItem,params.messageId)}return{processedQuery:result.processedQuery,shouldProceed:result.shouldProceed,toolDisplays:result.toolDisplays,filesRead:result.filesRead}}__name(handleAtCommand,"handleAtCommand");export{matchMcpServerPrefix,buildMcpResourceRef,MAX_SUGGESTIONS_TO_SHOW,MAX_SUGGESTION_LABEL_WIDTH,prepareSuggestionLabel,normalizeDescription,getExtensionSuggestions,SESSION_MENTION_PREFIX,buildSessionRef,parseMcpServerRef,buildMcpServerRef,matchMcpServerByRef,buildMcpServerContextText,extractAtPathCommands,resolveAtCommandQuery,handleAtCommand};
5
5
  /**
6
6
  * @license
7
7
  * Copyright 2025 Google LLC