@hostclubeos/miraos 0.0.7-beta → 0.0.9-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/chunks/{MaxSizedBox-CBUPHLMW.js → MaxSizedBox-6CGCRBRO.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-EXZJQKTK.js → StandaloneSessionPicker-7VQOS4TU.js} +1 -1
  3. package/chunks/{acp-subagent-executor-BMIXP52W.js → acp-subagent-executor-BFQRCU7R.js} +1 -1
  4. package/chunks/{acpAgent-JC4KGTLW.js → acpAgent-PCXQRPNU.js} +3 -3
  5. package/chunks/{advisor-5RUG3VFZ.js → advisor-WDZ5N5ZP.js} +1 -1
  6. package/chunks/{agent-SGQ7AEZI.js → agent-I7Q3IPSS.js} +1 -1
  7. package/chunks/{agent-headless-ZGCZ2DA7.js → agent-headless-6LOYWI5T.js} +1 -1
  8. package/chunks/{agent-host-client-HY5GPSHM.js → agent-host-client-PZZKCNQF.js} +1 -1
  9. package/chunks/{agent-host-connections-KGTBS37X.js → agent-host-connections-TWWSRTKJ.js} +1 -1
  10. package/chunks/{autofix-pr-E62FC67X.js → autofix-pr-RQPGPQ4D.js} +1 -1
  11. package/chunks/{batch-OUC6FGCQ.js → batch-UJD5TSBN.js} +1 -1
  12. package/chunks/{bridge-FLEIBB5V.js → bridge-4TYLRPXZ.js} +1 -1
  13. package/chunks/{channel-settings-store-QG6HREVH.js → channel-settings-store-RENJMOQ5.js} +1 -1
  14. package/chunks/{chunk-K7VOBDFT.js → chunk-24PHAWM3.js} +1 -1
  15. package/chunks/{chunk-7F5IYTVE.js → chunk-26JPBN6V.js} +1 -1
  16. package/chunks/{chunk-V5Z6OEKJ.js → chunk-2MQH3J4U.js} +1 -1
  17. package/chunks/{chunk-UOYXBAN7.js → chunk-2RXOWQSQ.js} +1 -1
  18. package/chunks/{chunk-H2QXWIRZ.js → chunk-323HUW2T.js} +1 -1
  19. package/chunks/{chunk-KNW2OD46.js → chunk-3BHXE7CB.js} +1 -1
  20. package/chunks/{chunk-RWFOQXPU.js → chunk-3GYAEXAA.js} +1 -1
  21. package/chunks/{chunk-W6IOHGWW.js → chunk-3YBZW4HP.js} +1 -1
  22. package/chunks/{chunk-23543L6E.js → chunk-4RJ2RRGZ.js} +1 -1
  23. package/chunks/{chunk-2PB6TEZU.js → chunk-5DIW4X4P.js} +1 -1
  24. package/chunks/{chunk-4346FNTB.js → chunk-5GB6JNJX.js} +1 -1
  25. package/chunks/{chunk-VRAHMOQQ.js → chunk-5HSNCG73.js} +2 -2
  26. package/chunks/{chunk-PQOQONLN.js → chunk-6HDMM7TJ.js} +1 -1
  27. package/chunks/{chunk-K7KY7FIB.js → chunk-6STNGEYC.js} +1 -1
  28. package/chunks/{chunk-7VP4KALB.js → chunk-7EFWNFJJ.js} +1 -1
  29. package/chunks/{chunk-ATVRF62A.js → chunk-7EWIKIJI.js} +1 -1
  30. package/chunks/{chunk-T5PDEAU5.js → chunk-7TB6VG72.js} +1 -1
  31. package/chunks/{chunk-4WYKHP7Q.js → chunk-7TLL4JLR.js} +1 -1
  32. package/chunks/{chunk-JDABSS6M.js → chunk-AOMXZNMX.js} +1 -1
  33. package/chunks/{chunk-FK5L2WVV.js → chunk-AUM57JI2.js} +1 -1
  34. package/chunks/{chunk-KK6SQPYG.js → chunk-AW5UCOZO.js} +1 -1
  35. package/chunks/{chunk-WC72OWF2.js → chunk-C6HVNDQT.js} +2 -2
  36. package/chunks/{chunk-BSLIVO6O.js → chunk-CC6E5CQV.js} +1 -1
  37. package/chunks/{chunk-AIAYQAPA.js → chunk-CLKUQP27.js} +1 -1
  38. package/chunks/{chunk-2QYFSBJY.js → chunk-DFMQQM4M.js} +1 -1
  39. package/chunks/{chunk-MMGNOY3U.js → chunk-DP7LJTG2.js} +5 -5
  40. package/chunks/{chunk-MYS5NQXO.js → chunk-DQT5VL7G.js} +1 -1
  41. package/chunks/{chunk-FC7SJIAS.js → chunk-E4QOAV5O.js} +1 -1
  42. package/chunks/{chunk-3MBYQYPC.js → chunk-E4REGDEZ.js} +1 -1
  43. package/chunks/{chunk-WCLAVBNR.js → chunk-EAG7VZJJ.js} +1 -1
  44. package/chunks/{chunk-GQ24VFGQ.js → chunk-EFO6J22W.js} +1 -1
  45. package/chunks/{chunk-6RDYPRV6.js → chunk-EMR4QK2F.js} +1 -1
  46. package/chunks/{chunk-WZTO3EYG.js → chunk-EYECE2PH.js} +1 -1
  47. package/chunks/{chunk-UWMLSAQY.js → chunk-EZDXHUHB.js} +1 -1
  48. package/chunks/{chunk-T3A53XMM.js → chunk-FJFTKA4H.js} +1 -1
  49. package/chunks/{chunk-W2ZVZ6LS.js → chunk-FSLDNLNU.js} +1 -1
  50. package/chunks/{chunk-O6Z3KO6R.js → chunk-FSRXTX3N.js} +1 -1
  51. package/chunks/{chunk-TFITRCIC.js → chunk-FWSXFRIQ.js} +1 -1
  52. package/chunks/{chunk-TU5QHOJC.js → chunk-G4ATLMDH.js} +1 -1
  53. package/chunks/{chunk-DF6TBGS2.js → chunk-GAS3HKRX.js} +1 -1
  54. package/chunks/{chunk-YVN32EUM.js → chunk-GFFL2LR2.js} +1 -1
  55. package/chunks/{chunk-TLZM3DMY.js → chunk-GYFIY7TD.js} +1 -1
  56. package/chunks/{chunk-PGKFDR73.js → chunk-GYXRI4P5.js} +1 -1
  57. package/chunks/{chunk-3KFLO5W3.js → chunk-H3U7DXIU.js} +1 -1
  58. package/chunks/{chunk-YN6WXB6B.js → chunk-HEDVPRMD.js} +1 -1
  59. package/chunks/{chunk-JJDF5FHA.js → chunk-HI3644FQ.js} +1 -1
  60. package/chunks/{chunk-HASJX2YS.js → chunk-HTHYLMBO.js} +1 -1
  61. package/chunks/{chunk-4MGTY3CJ.js → chunk-IW7RPDV2.js} +1 -1
  62. package/chunks/{chunk-SCHCTQCG.js → chunk-IXQI4K6O.js} +1 -1
  63. package/chunks/chunk-IYH3IZL4.js +13 -0
  64. package/chunks/{chunk-EF3HUB7S.js → chunk-J52J35K4.js} +1 -1
  65. package/chunks/{chunk-TXL535SJ.js → chunk-J7L5IHLG.js} +1 -1
  66. package/chunks/{chunk-N7WQH6L4.js → chunk-JHS5B4N7.js} +2 -2
  67. package/chunks/{chunk-P5543CFV.js → chunk-JRSO5ZGU.js} +1 -1
  68. package/chunks/{chunk-G35E5UB3.js → chunk-JS6VAGRQ.js} +1 -1
  69. package/chunks/{chunk-Z4JY3HGO.js → chunk-KAFPULGU.js} +1 -1
  70. package/chunks/{chunk-RNPVWQ3V.js → chunk-LDP47G5M.js} +1 -1
  71. package/chunks/{chunk-EW3EVEYN.js → chunk-LMZZWPKA.js} +1 -1
  72. package/chunks/{chunk-5RYDKYIR.js → chunk-LNCELICB.js} +1 -1
  73. package/chunks/{chunk-JDHMSERR.js → chunk-LY2DRNTZ.js} +1 -1
  74. package/chunks/{chunk-7W5DOBKY.js → chunk-MMGGGYSJ.js} +1 -1
  75. package/chunks/{chunk-CUY6CVSL.js → chunk-MTBU2ZIM.js} +1 -1
  76. package/chunks/{chunk-TWJ4XBED.js → chunk-N27KICJQ.js} +1 -1
  77. package/chunks/{chunk-JQOLNQQN.js → chunk-NHYFTK4O.js} +1 -1
  78. package/chunks/{chunk-NGH27AWP.js → chunk-NRDHXSEE.js} +1 -1
  79. package/chunks/{chunk-3GJ56V2J.js → chunk-NV5VVTYQ.js} +1 -1
  80. package/chunks/{chunk-VJUTDS6C.js → chunk-OEDMFKZL.js} +1 -1
  81. package/chunks/{chunk-PVHBBTAU.js → chunk-OQAVMR6K.js} +1 -1
  82. package/chunks/{chunk-IF3SWUYT.js → chunk-OY3Y6EMV.js} +1 -1
  83. package/chunks/{chunk-SOCXRMZM.js → chunk-OZL4ZMGQ.js} +2 -2
  84. package/chunks/{chunk-GLQWA4W2.js → chunk-PKSPKVFH.js} +1 -1
  85. package/chunks/{chunk-KYK53GFP.js → chunk-PNFKCYZT.js} +1 -1
  86. package/chunks/{chunk-7SAR6NXA.js → chunk-PTWHFVGG.js} +2 -2
  87. package/chunks/{chunk-RBA3TP7L.js → chunk-QJ6ZTZFC.js} +1 -1
  88. package/chunks/{chunk-PFECH6U6.js → chunk-QRGWB7IX.js} +1 -1
  89. package/chunks/{chunk-VBJV7T47.js → chunk-QRP2GXQD.js} +1 -1
  90. package/chunks/{chunk-WJLHLFIR.js → chunk-RES5ET63.js} +1 -1
  91. package/chunks/{chunk-GY4ID3EB.js → chunk-ROSJCTWB.js} +1 -1
  92. package/chunks/{chunk-4KIFAVR2.js → chunk-RR3NFNWL.js} +1 -1
  93. package/chunks/{chunk-2ZWVSKPK.js → chunk-RYQDRFLW.js} +1 -1
  94. package/chunks/{chunk-NVD63O5H.js → chunk-S7CWSAUQ.js} +1 -1
  95. package/chunks/{chunk-66DZADDA.js → chunk-SAJKF4WS.js} +1 -1
  96. package/chunks/chunk-SINRWOVD.js +36 -0
  97. package/chunks/{chunk-HSN5QUS7.js → chunk-SJNQ6I23.js} +1 -1
  98. package/chunks/{chunk-3NB3FFLR.js → chunk-T2GM4S4G.js} +3 -3
  99. package/chunks/{chunk-GN7ODRDE.js → chunk-TCQJO42E.js} +1 -1
  100. package/chunks/{chunk-67PM7M5R.js → chunk-TIIDF23U.js} +2 -2
  101. package/chunks/{chunk-USR2Y7B3.js → chunk-TKH5R7RZ.js} +1 -1
  102. package/chunks/{chunk-GTQULDIL.js → chunk-TSRTZD3X.js} +1 -1
  103. package/chunks/{chunk-GXNGLDUN.js → chunk-UXSXKLRH.js} +1 -1
  104. package/chunks/{chunk-JJQJFMPL.js → chunk-UYI5AMPI.js} +1 -1
  105. package/chunks/{chunk-SHKSVOTG.js → chunk-VO6SPDH4.js} +1 -1
  106. package/chunks/{chunk-AE6E2YKY.js → chunk-VRIHYTDI.js} +1 -1
  107. package/chunks/{chunk-6T25QVBX.js → chunk-VT47A26Q.js} +1 -1
  108. package/chunks/{chunk-2VW4HXVF.js → chunk-VZOZUCZX.js} +1 -1
  109. package/chunks/{chunk-724YPZRX.js → chunk-WLEGTKGA.js} +1 -1
  110. package/chunks/{chunk-ZOWMHZWO.js → chunk-XHCJN4A2.js} +1 -1
  111. package/chunks/{chunk-J773THNP.js → chunk-XTRZ5PHG.js} +1 -1
  112. package/chunks/{chunk-H65ZVST6.js → chunk-Y4GZOZWD.js} +1 -1
  113. package/chunks/{chunk-E6LRCLLE.js → chunk-YUCAGV52.js} +2 -2
  114. package/chunks/{chunk-FS67DOZQ.js → chunk-YWQM4TSO.js} +1 -1
  115. package/chunks/{chunk-P42MFWO2.js → chunk-YYTOHY4V.js} +1 -1
  116. package/chunks/{chunk-PSSJDUZB.js → chunk-Z25W2S5N.js} +1 -1
  117. package/chunks/{chunk-VF2UWWI2.js → chunk-Z6GECBAJ.js} +1 -1
  118. package/chunks/{chunk-HZ4L4MDM.js → chunk-ZJU4B4WX.js} +1 -1
  119. package/chunks/{chunk-RRMTSVGU.js → chunk-ZSHDQPAO.js} +1 -1
  120. package/chunks/{chunk-PFKTTUGS.js → chunk-ZUWLTGSR.js} +6 -6
  121. package/chunks/{codex-subagent-executor-UCDGQFTR.js → codex-subagent-executor-2V4NB7IR.js} +1 -1
  122. package/chunks/{config-utils-Z6F4DVLG.js → config-utils-5B2LYCON.js} +1 -1
  123. package/chunks/{contextCommand-HMVZT56Y.js → contextCommand-UPQGRXWK.js} +1 -1
  124. package/chunks/{core-runtime-AV7CJXOL.js → core-runtime-DPMH2BXK.js} +1 -1
  125. package/chunks/{create-sub-session-NNKVHZKT.js → create-sub-session-EJVB3FE5.js} +1 -1
  126. package/chunks/{cron-create-HWZDFVPA.js → cron-create-V2A7PMQC.js} +1 -1
  127. package/chunks/{daemon-git-worktree-guard-Q3C45X7T.js → daemon-git-worktree-guard-YEIMR2X7.js} +1 -1
  128. package/chunks/{daemon-status-provider-UX574XBB.js → daemon-status-provider-6BRB5TG3.js} +1 -1
  129. package/chunks/{daemon-trust-policy-6D4KJANB.js → daemon-trust-policy-BEXVFO4M.js} +1 -1
  130. package/chunks/{daemon-trust-policy-monitor-BZ46W4IA.js → daemon-trust-policy-monitor-BVS6LXBX.js} +1 -1
  131. package/chunks/{deferred-core-runtime-YC5XIWEI.js → deferred-core-runtime-NTKFHL5J.js} +1 -1
  132. package/chunks/{edit-LOWDEKPX.js → edit-LRG3TMHP.js} +1 -1
  133. package/chunks/{enterPlanMode-NGSATDRH.js → enterPlanMode-KOUSHJHR.js} +1 -1
  134. package/chunks/{environment-CVIB5DW4.js → environment-54CM3OXE.js} +1 -1
  135. package/chunks/{errors-USKSVZFO.js → errors-D6XR3NH4.js} +1 -1
  136. package/chunks/{execution-tool-QSJLRU5N.js → execution-tool-7RZ2JLEK.js} +1 -1
  137. package/chunks/{execution-worker-TQEIC4AJ.js → execution-worker-LXQ7WAFG.js} +1 -1
  138. package/chunks/{exitPlanMode-AW2HOTIK.js → exitPlanMode-4FGFA2QC.js} +1 -1
  139. package/chunks/{fast-path-OQWHYDXC.js → fast-path-4B7OKPYK.js} +1 -1
  140. package/chunks/{glob-7U6FQSWZ.js → glob-N2D7SY23.js} +1 -1
  141. package/chunks/{goal-tools-5ZB6GPCJ.js → goal-tools-7RNSDRFO.js} +1 -1
  142. package/chunks/{handleAutoUpdate-MLUFTWFP.js → handleAutoUpdate-PKKJQAKG.js} +1 -1
  143. package/chunks/{i18n-QAPQLOC3.js → i18n-F3OAHCLJ.js} +1 -1
  144. package/chunks/{initializer-B27IZ7K4.js → initializer-OL3DDWR7.js} +1 -1
  145. package/chunks/{installationInfo-SAMHABWV.js → installationInfo-D2L743RV.js} +1 -1
  146. package/chunks/{interactive-mod-session-7LQ5CYUR.js → interactive-mod-session-2GXRCQKR.js} +1 -1
  147. package/chunks/{list-TDMJQDQO.js → list-PU7ZXBY5.js} +1 -1
  148. package/chunks/{llm-R2RFT63S.js → llm-V42HGUVH.js} +4 -4
  149. package/chunks/{loadedSettingsAdapter-ZQK5KMEW.js → loadedSettingsAdapter-KAEVWWRX.js} +1 -1
  150. package/chunks/{local-AONDQYFL.js → local-KM5F5RAB.js} +1 -1
  151. package/chunks/{local-execution-environment-WJVCE26F.js → local-execution-environment-OEO2KW3M.js} +1 -1
  152. package/chunks/{loggingContentGenerator-ALSG42YA.js → loggingContentGenerator-DQLXSDZR.js} +1 -1
  153. package/chunks/{loop-wakeup-LFU4LDJM.js → loop-wakeup-CJICM24Y.js} +1 -1
  154. package/chunks/{manage-memory-FBL6CHX2.js → manage-memory-7CV6LF4C.js} +1 -1
  155. package/chunks/{managed-execution-engine-FX7FDAWW.js → managed-execution-engine-JEAIQ7L4.js} +1 -1
  156. package/chunks/{managed-local-serve-DRNC6PTL.js → managed-local-serve-KA37YWRW.js} +1 -1
  157. package/chunks/{managed-npm-update-2MKV7UOI.js → managed-npm-update-TSUUH3NN.js} +1 -1
  158. package/chunks/{managed-runtime-attestation-worker-DBAHM5MN.js → managed-runtime-attestation-worker-PUZ2ECM5.js} +1 -1
  159. package/chunks/{managed-runtime-bootstrap-K3GRKDNQ.js → managed-runtime-bootstrap-SERIRKPD.js} +1 -1
  160. package/chunks/{managed-runtime-session-worker-YN4KML7A.js → managed-runtime-session-worker-UOXK63YX.js} +1 -1
  161. package/chunks/{managed-runtime-ssh-worker-AVNBWFYC.js → managed-runtime-ssh-worker-VKZYIX6R.js} +1 -1
  162. package/chunks/{managed-session-authority-MFEINLXC.js → managed-session-authority-5FYS3G3M.js} +1 -1
  163. package/chunks/{mcp-TS5PX5FY.js → mcp-TRPV3K74.js} +1 -1
  164. package/chunks/{memory-JVT5LAWJ.js → memory-5CMNRPM2.js} +1 -1
  165. package/chunks/{model-call-collection-TNBMD3YL.js → model-call-collection-S4JKVFUO.js} +1 -1
  166. package/chunks/{model-configuration-6KTQQTMO.js → model-configuration-NEIDLKWQ.js} +1 -1
  167. package/chunks/{modelConfigUtils-LCZZ3EQU.js → modelConfigUtils-LZLQOZKJ.js} +1 -1
  168. package/chunks/{monitor-KCCNIKLE.js → monitor-5MNKK5AO.js} +1 -1
  169. package/chunks/{nonInteractiveCli-2GHQYHGW.js → nonInteractiveCli-DDTGU2ER.js} +1 -1
  170. package/chunks/{nonInteractiveToolExecutor-R5CTTWKD.js → nonInteractiveToolExecutor-N7PCYCKO.js} +1 -1
  171. package/chunks/{notebook-edit-KIWE2XOA.js → notebook-edit-7HIBTFFW.js} +1 -1
  172. package/chunks/{omni-IFTMWBMU.js → omni-MX7BMOL5.js} +1 -1
  173. package/chunks/{openaiContentGenerator-XP3VPU6C.js → openaiContentGenerator-NOIIZNRX.js} +1 -1
  174. package/chunks/{openaiResponsesContentGenerator-ZJ6C22EA.js → openaiResponsesContentGenerator-5JJ6G7RS.js} +1 -1
  175. package/chunks/{pidfile-42P24JIA.js → pidfile-OHAGZOTV.js} +1 -1
  176. package/chunks/{processUtils-I2XOO5U2.js → processUtils-TCDNCYVB.js} +1 -1
  177. package/chunks/{prompt-terminal-ledger-7EW46VQ4.js → prompt-terminal-ledger-4ZUOCMOS.js} +1 -1
  178. package/chunks/{reactive-degrade-O4JO7MOX.js → reactive-degrade-C7CGUJNP.js} +1 -1
  179. package/chunks/{read-file-VGC4O7F2.js → read-file-L4ZF6VDG.js} +1 -1
  180. package/chunks/{resumeHistoryUtils-QMVIHQRW.js → resumeHistoryUtils-WK3I4OIL.js} +1 -1
  181. package/chunks/{review-NDK2B7XI.js → review-F6JGI2LP.js} +1 -1
  182. package/chunks/{ripGrep-JY4PZABK.js → ripGrep-L6M2GPCM.js} +1 -1
  183. package/chunks/{run-qwen-serve-P5X5OZUH.js → run-qwen-serve-D5HB55SC.js} +1 -1
  184. package/chunks/{runtime-OL7B72CH.js → runtime-CH3RAOQL.js} +1 -1
  185. package/chunks/{sandboxConfig-EJTMWZHD.js → sandboxConfig-EADWCO37.js} +1 -1
  186. package/chunks/{scheduled-tasks-XQSZWZXG.js → scheduled-tasks-PBKD4BHY.js} +1 -1
  187. package/chunks/{scheduler-3TIRZEVB.js → scheduler-U5K3523K.js} +1 -1
  188. package/chunks/{search-memory-P5KOTUVV.js → search-memory-Y2IPKBDP.js} +1 -1
  189. package/chunks/{send-message-KFSKFXLX.js → send-message-JJQG2S6D.js} +1 -1
  190. package/chunks/{serve-UHEH433U.js → serve-2ZYS47MO.js} +1 -1
  191. package/chunks/{server-ARYDETSZ.js → server-5GMO4IHU.js} +3 -3
  192. package/chunks/{session-HKWGCZF2.js → session-LLOOVSHK.js} +1 -1
  193. package/chunks/{session-attachments-root-O3YQ7HWD.js → session-attachments-root-XCLXH2XO.js} +1 -1
  194. package/chunks/{session-execution-engine-selector-LZBHS3UO.js → session-execution-engine-selector-5QPWJZSF.js} +1 -1
  195. package/chunks/{session-pr-refresh-L5Z5WCXS.js → session-pr-refresh-MDBOAN3R.js} +1 -1
  196. package/chunks/{sessionService-MMPZUN5X.js → sessionService-VKAHCTCC.js} +1 -1
  197. package/chunks/{settings-7PYHXPN4.js → settings-ULEB2IYZ.js} +1 -1
  198. package/chunks/{shell-E6QLKRVU.js → shell-RBEKIYKU.js} +1 -1
  199. package/chunks/{skill-55IZUUM5.js → skill-GEVOEFMZ.js} +1 -1
  200. package/chunks/{skill-settings-A2M5BPH7.js → skill-settings-4IMGLYJW.js} +1 -1
  201. package/chunks/{spawnChannel-KWU26CB7.js → spawnChannel-B7L5PWQ6.js} +1 -1
  202. package/chunks/{standalone-update-32WYZ3BJ.js → standalone-update-SYQM6NOC.js} +1 -1
  203. package/chunks/{start-opentui-ui-S7A4FBGP.js → start-opentui-ui-N427PLF4.js} +2 -2
  204. package/chunks/{startInteractiveUI-DY6DWFW7.js → startInteractiveUI-AS6GZKJJ.js} +1 -1
  205. package/chunks/{team-create-ARICYIQB.js → team-create-MN6FHUHU.js} +1 -1
  206. package/chunks/{team-plan-approval-JPRE6Q3R.js → team-plan-approval-OUYBIT7H.js} +1 -1
  207. package/chunks/{terminal-image-renderer-HVIZ2VNE.js → terminal-image-renderer-MXZDUEOS.js} +1 -1
  208. package/chunks/{theme-manager-UEPLIBUP.js → theme-manager-QOYSKWFK.js} +1 -1
  209. package/chunks/{tool-call-EFJKXI3Z.js → tool-call-Q5NLEQFD.js} +1 -1
  210. package/chunks/{tool-result-media-LMIYNXSD.js → tool-result-media-NZJZTOBQ.js} +1 -1
  211. package/chunks/{tool-search-D7HQTRQG.js → tool-search-D6Y45RNQ.js} +1 -1
  212. package/chunks/{total-session-admission-67QMR44O.js → total-session-admission-36W7MDHP.js} +1 -1
  213. package/chunks/{trustedFolders-HARYVS3F.js → trustedFolders-XW5VH6HK.js} +1 -1
  214. package/chunks/{update-relaunch-NVNPOK5J.js → update-relaunch-KQPR2HAP.js} +1 -1
  215. package/chunks/{updateCheck-7NMXUCTN.js → updateCheck-SRW67WAX.js} +1 -1
  216. package/chunks/{upload-config-W2SICJ32.js → upload-config-BTJNYMRX.js} +1 -1
  217. package/chunks/{useAutoAcceptIndicator-ELMIP4TJ.js → useAutoAcceptIndicator-N3RRUBSL.js} +1 -1
  218. package/chunks/{validateNonInterActiveAuth-P2F6MYO6.js → validateNonInterActiveAuth-SWNH4FY4.js} +1 -1
  219. package/chunks/{version-2ZFKVIIW.js → version-6R6LSGXO.js} +1 -1
  220. package/chunks/{web-fetch-537RS6IX.js → web-fetch-Y7LBAU3R.js} +1 -1
  221. package/chunks/{web-search-O27MYFSW.js → web-search-IB4NYYUH.js} +1 -1
  222. package/chunks/{workflow-6QF4RMYM.js → workflow-TR4YIPJO.js} +1 -1
  223. package/chunks/{workflow-ancestor-trust-CABLU3VV.js → workflow-ancestor-trust-AHDUBOR7.js} +1 -1
  224. package/chunks/{workspace-agents-5WP3PY7W.js → workspace-agents-MY2NFL6A.js} +1 -1
  225. package/chunks/{workspace-providers-status-7G2EJJEO.js → workspace-providers-status-DNCCKFVE.js} +1 -1
  226. package/chunks/{workspace-recovery-worker-ICCIDEWU.js → workspace-recovery-worker-22VK4T4R.js} +1 -1
  227. package/chunks/{workspace-registration-store-WHXMNQQQ.js → workspace-registration-store-64TGRRGC.js} +1 -1
  228. package/chunks/{workspace-registry-NXBODLYH.js → workspace-registry-E6LFL5GL.js} +1 -1
  229. package/chunks/{workspace-runtime-coordinator-CJXS273B.js → workspace-runtime-coordinator-UHJHBIQT.js} +1 -1
  230. package/chunks/{workspace-service-HUDE2RXN.js → workspace-service-OVEYIQOC.js} +1 -1
  231. package/chunks/{workspace-skills-status-FJC6U62F.js → workspace-skills-status-3NKXA5SK.js} +1 -1
  232. package/chunks/{workspace-trust-reconciler-ZIQ3A5ZB.js → workspace-trust-reconciler-JF7YHR52.js} +1 -1
  233. package/chunks/{write-file-652YGG7I.js → write-file-FSTHYKKZ.js} +1 -1
  234. package/chunks/{zoom-image-YEH4O74G.js → zoom-image-JP3EUDXE.js} +1 -1
  235. package/cli.js +2 -2
  236. package/execution-worker.js +1 -1
  237. package/package.json +2 -2
  238. package/chunks/chunk-56PVVXUG.js +0 -8
  239. package/chunks/chunk-AJ75BPTA.js +0 -31
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{t}from"./chunk-FK5L2WVV.js";import{computeThresholds,estimateContextTextTokens,formatContextFileDisplayPath,getAutoMemorySnapshot,getMainSessionBaseSystemPrompt,withoutAutoMemorySnapshots}from"./chunk-PFKTTUGS.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{DiscoveredMCPTool,uiTelemetryService}from"./chunk-MJEL7DIE.js";import{getAllMemoryFilenames}from"./chunk-6JHMYZNS.js";import{DEFAULT_TOKEN_LIMIT}from"./chunk-EV2CXPMN.js";import{resolveSlimmingConfig}from"./chunk-Q6UAOTP3.js";import{AUTO_MEMORY_SNAPSHOT_METADATA,buildAvailableSkillsReminder,getStartupContextLength,isSkillListingReminder}from"./chunk-DMM5LJWL.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{isSubpath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();import*as fs from"node:fs/promises";var EXTENSION_REF_PREFIX="ext:";var EXTENSION_CONTEXT_BUDGET=2e5;var EXTENSION_CONTEXT_FILE_CAP=5e4;function parseExtensionRef(pathName){if(!pathName.startsWith(EXTENSION_REF_PREFIX))return null;const name=pathName.slice(EXTENSION_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseExtensionRef,"parseExtensionRef");function buildExtensionRef(extensionName){return`${EXTENSION_REF_PREFIX}${extensionName}`}__name(buildExtensionRef,"buildExtensionRef");function matchExtensionByRef(name,extensions){const lower=name.toLowerCase();return extensions.find(ext=>ext.name.toLowerCase()===lower||ext.config.name.toLowerCase()===lower)}__name(matchExtensionByRef,"matchExtensionByRef");var BIDI_CONTROL_RE=/[‎‏؜⁦⁧⁨⁩‪‫‬‭‮]/g;function sanitizeDisplayText(raw){const stripped=stripTerminalControlSequences(raw).replace(BIDI_CONTROL_RE,"").replace(/\s+/g," ").trim();return stripped.length>0?stripped:null}__name(sanitizeDisplayText,"sanitizeDisplayText");function getSanitizedExtensionDisplayName(extension){return sanitizeDisplayText(extension.displayName||extension.name)||extension.name}__name(getSanitizedExtensionDisplayName,"getSanitizedExtensionDisplayName");function buildExtensionContextText(extension){const displayName=getSanitizedExtensionDisplayName(extension);const lines=[];lines.push(`--- Extension: ${displayName} (untrusted third-party content) ---`);if(extension.config.description){const desc=sanitizeDisplayText(extension.config.description);if(desc){lines.push(desc);lines.push("")}}const capabilities=[];if(extension.skills&&extension.skills.length>0){const skillNames=extension.skills.map(s=>sanitizeDisplayText(qualifySkillName(extension.name,s.name))||s.name).join(", ");capabilities.push(`- Skills: ${skillNames} (invoke via /<skill-name>)`)}if(extension.mcpServers&&Object.keys(extension.mcpServers).length>0){const serverNames=Object.keys(extension.mcpServers).map(n=>sanitizeDisplayText(n)||n).join(", ");capabilities.push(`- MCP Servers: ${serverNames}`)}if(extension.agents&&extension.agents.length>0){const agentNames=extension.agents.map(a=>sanitizeDisplayText(a.name)||a.name).join(", ");capabilities.push(`- Agents: ${agentNames}`)}if(capabilities.length>0){lines.push("Available capabilities from this extension:");lines.push(...capabilities);lines.push("")}lines.push(`--- End Extension: ${displayName} ---`);return lines.join("\n")}__name(buildExtensionContextText,"buildExtensionContextText");async function buildExtensionMentionContext(extension,options){let contextText=buildExtensionContextText(extension);let remainingBudget=options.remainingBudget;if(extension.contextFiles.length===0){return{text:contextText,remainingBudget}}const fileReads=await Promise.allSettled(extension.contextFiles.map(async contextFilePath=>{let realPath;let realExtPath;try{realPath=await fs.realpath(contextFilePath);realExtPath=await fs.realpath(extension.path)}catch{options.onDebugMessage?.(`Skipping unreadable context file: ${contextFilePath}`);return null}if(!isSubpath(realExtPath,realPath)){options.onDebugMessage?.(`Skipping context file outside extension directory: ${contextFilePath}`);return null}return fs.readFile(realPath,{encoding:"utf-8",signal:options.signal})}));for(let i=0;i<fileReads.length;i++){const outcome=fileReads[i];if(outcome.status==="rejected"){options.onDebugMessage?.(`Failed to read extension context file ${extension.contextFiles[i]}: ${getErrorMessage(outcome.reason)}`);continue}const content=outcome.value;if(!content||!content.trim())continue;if(remainingBudget<=0){options.onDebugMessage?.("Extension context budget exhausted, skipping remaining files.");break}const cap=Math.min(EXTENSION_CONTEXT_FILE_CAP,remainingBudget);const cappedContent=content.length>cap?content.slice(0,cap)+"\n... (truncated)":content;contextText+=`
3
+ import{t}from"./chunk-AUM57JI2.js";import{computeThresholds,estimateContextTextTokens,formatContextFileDisplayPath,getAutoMemorySnapshot,getMainSessionBaseSystemPrompt,withoutAutoMemorySnapshots}from"./chunk-ZUWLTGSR.js";import{stripTerminalControlSequences}from"./chunk-R2EHHA2C.js";import{qualifySkillName}from"./chunk-CV2UAEZA.js";import{DiscoveredMCPTool,uiTelemetryService}from"./chunk-MJEL7DIE.js";import{getAllMemoryFilenames}from"./chunk-6JHMYZNS.js";import{DEFAULT_TOKEN_LIMIT}from"./chunk-EV2CXPMN.js";import{resolveSlimmingConfig}from"./chunk-Q6UAOTP3.js";import{AUTO_MEMORY_SNAPSHOT_METADATA,buildAvailableSkillsReminder,getStartupContextLength,isSkillListingReminder}from"./chunk-DMM5LJWL.js";import{ToolNames}from"./chunk-SBZFGYYS.js";import{Storage}from"./chunk-5VB4YX3Z.js";import{isSubpath}from"./chunk-2ZK2FGZQ.js";import{getErrorMessage}from"./chunk-E7MYPQGV.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as path from"node:path";init_esbuild_shims();import*as fs from"node:fs/promises";var EXTENSION_REF_PREFIX="ext:";var EXTENSION_CONTEXT_BUDGET=2e5;var EXTENSION_CONTEXT_FILE_CAP=5e4;function parseExtensionRef(pathName){if(!pathName.startsWith(EXTENSION_REF_PREFIX))return null;const name=pathName.slice(EXTENSION_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseExtensionRef,"parseExtensionRef");function buildExtensionRef(extensionName){return`${EXTENSION_REF_PREFIX}${extensionName}`}__name(buildExtensionRef,"buildExtensionRef");function matchExtensionByRef(name,extensions){const lower=name.toLowerCase();return extensions.find(ext=>ext.name.toLowerCase()===lower||ext.config.name.toLowerCase()===lower)}__name(matchExtensionByRef,"matchExtensionByRef");var BIDI_CONTROL_RE=/[‎‏؜⁦⁧⁨⁩‪‫‬‭‮]/g;function sanitizeDisplayText(raw){const stripped=stripTerminalControlSequences(raw).replace(BIDI_CONTROL_RE,"").replace(/\s+/g," ").trim();return stripped.length>0?stripped:null}__name(sanitizeDisplayText,"sanitizeDisplayText");function getSanitizedExtensionDisplayName(extension){return sanitizeDisplayText(extension.displayName||extension.name)||extension.name}__name(getSanitizedExtensionDisplayName,"getSanitizedExtensionDisplayName");function buildExtensionContextText(extension){const displayName=getSanitizedExtensionDisplayName(extension);const lines=[];lines.push(`--- Extension: ${displayName} (untrusted third-party content) ---`);if(extension.config.description){const desc=sanitizeDisplayText(extension.config.description);if(desc){lines.push(desc);lines.push("")}}const capabilities=[];if(extension.skills&&extension.skills.length>0){const skillNames=extension.skills.map(s=>sanitizeDisplayText(qualifySkillName(extension.name,s.name))||s.name).join(", ");capabilities.push(`- Skills: ${skillNames} (invoke via /<skill-name>)`)}if(extension.mcpServers&&Object.keys(extension.mcpServers).length>0){const serverNames=Object.keys(extension.mcpServers).map(n=>sanitizeDisplayText(n)||n).join(", ");capabilities.push(`- MCP Servers: ${serverNames}`)}if(extension.agents&&extension.agents.length>0){const agentNames=extension.agents.map(a=>sanitizeDisplayText(a.name)||a.name).join(", ");capabilities.push(`- Agents: ${agentNames}`)}if(capabilities.length>0){lines.push("Available capabilities from this extension:");lines.push(...capabilities);lines.push("")}lines.push(`--- End Extension: ${displayName} ---`);return lines.join("\n")}__name(buildExtensionContextText,"buildExtensionContextText");async function buildExtensionMentionContext(extension,options){let contextText=buildExtensionContextText(extension);let remainingBudget=options.remainingBudget;if(extension.contextFiles.length===0){return{text:contextText,remainingBudget}}const fileReads=await Promise.allSettled(extension.contextFiles.map(async contextFilePath=>{let realPath;let realExtPath;try{realPath=await fs.realpath(contextFilePath);realExtPath=await fs.realpath(extension.path)}catch{options.onDebugMessage?.(`Skipping unreadable context file: ${contextFilePath}`);return null}if(!isSubpath(realExtPath,realPath)){options.onDebugMessage?.(`Skipping context file outside extension directory: ${contextFilePath}`);return null}return fs.readFile(realPath,{encoding:"utf-8",signal:options.signal})}));for(let i=0;i<fileReads.length;i++){const outcome=fileReads[i];if(outcome.status==="rejected"){options.onDebugMessage?.(`Failed to read extension context file ${extension.contextFiles[i]}: ${getErrorMessage(outcome.reason)}`);continue}const content=outcome.value;if(!content||!content.trim())continue;if(remainingBudget<=0){options.onDebugMessage?.("Extension context budget exhausted, skipping remaining files.");break}const cap=Math.min(EXTENSION_CONTEXT_FILE_CAP,remainingBudget);const cappedContent=content.length>cap?content.slice(0,cap)+"\n... (truncated)":content;contextText+=`
4
4
 
5
5
  ${cappedContent}`;remainingBudget-=cappedContent.length}return{text:contextText,remainingBudget}}__name(buildExtensionMentionContext,"buildExtensionMentionContext");function currentTier(tokens,thresholds){if(tokens>=thresholds.hard)return"hard";if(tokens>=thresholds.auto)return"auto";if(tokens>=thresholds.warn)return"warn";return"safe"}__name(currentTier,"currentTier");function extensionContextFileOwners(config,workingDir){const owners=new Map;for(const extension of config.getActiveExtensions?.()??[]){const displayName=getSanitizedExtensionDisplayName(extension);for(const contextFile of extension.contextFiles??[]){const absolutePath=path.resolve(workingDir,contextFile);const fileLabel=formatContextFileDisplayPath(absolutePath,extension.path);owners.set(absolutePath,`${t("Extension")}: ${displayName} \xB7 ${fileLabel}`)}}return owners}__name(extensionContextFileOwners,"extensionContextFileOwners");function parseMemoryFiles(memoryContent,workingDir,extensionOwners=new Map,admissionRoot=workingDir){if(!memoryContent||memoryContent.trim().length===0)return[];const results=[];const root=path.resolve(admissionRoot);const globalDir=path.resolve(Storage.getGlobalQwenDir());const memoryFilenames=new Set(getAllMemoryFilenames());const openablePath=__name(absolutePath=>isSubpath(root,absolutePath)||path.resolve(path.dirname(absolutePath))===globalDir&&memoryFilenames.has(path.basename(absolutePath))?absolutePath:void 0,"openablePath");const regex=/--- Context from: (.+?) ---\n([\s\S]*?)--- End of Context from: \1 ---/g;let match;while((match=regex.exec(memoryContent))!==null){const filePath=match[1];const content=match[2];const absolutePath=path.resolve(workingDir,filePath);const owner=extensionOwners.get(absolutePath);const openPath=openablePath(absolutePath);results.push({path:owner??formatContextFileDisplayPath(absolutePath,workingDir),tokens:estimateContextTextTokens(content),...openPath!==void 0?{absolutePath:openPath}:{}})}if(results.length===0&&memoryContent.trim().length>0){results.push({path:t("memory"),tokens:estimateContextTextTokens(memoryContent)})}return results}__name(parseMemoryFiles,"parseMemoryFiles");function unescapeXml(text){return text.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&amp;/g,"&")}__name(unescapeXml,"unescapeXml");var SKILL_LISTING_ENTRY=/<skill>\n<name>\n([\s\S]*?)\n<\/name>[\s\S]*?<\/skill>/g;function measureSkillListing(text){const byName=new Map;for(const match of text.matchAll(SKILL_LISTING_ENTRY)){const name=unescapeXml(match[1]);byName.set(name.toLowerCase(),{name,tokens:estimateContextTextTokens(match[0])})}return{tokens:estimateContextTextTokens(text),byName}}__name(measureSkillListing,"measureSkillListing");function mergeSkillListing(into,from){into.tokens+=from.tokens;for(const[name,entry]of from.byName){into.byName.set(name,entry)}}__name(mergeSkillListing,"mergeSkillListing");function measureTailSkillListings(conversation){const listing={tokens:0,byName:new Map};const billedTexts=new Set;for(const content of conversation){for(const part of content.parts??[]){const text=part.text;if(typeof text!=="string"||!isSkillListingReminder(text))continue;const measured=measureSkillListing(text);if(measured.byName.size===0)continue;mergeSkillListing(listing,measured);billedTexts.add(text)}}return{listing,billedTexts}}__name(measureTailSkillListings,"measureTailSkillListings");function measureStartupPrelude(prelude){const skillListing={tokens:0,byName:new Map};let startupContextTokens=0;for(const content of prelude){for(const part of content.parts??[]){if(typeof part.text!=="string")continue;if(isSkillListingReminder(part.text)){mergeSkillListing(skillListing,measureSkillListing(part.text))}else{startupContextTokens+=estimateContextTextTokens(part.text)}}}return{skillListing,startupContextTokens}}__name(measureStartupPrelude,"measureStartupPrelude");function estimateFunctionResponseTokens(part,imageTokenEstimate){const response=part.functionResponse;let tokens=estimateContextTextTokens(JSON.stringify({id:response.id,name:response.name,response:response.response}));const nested=response.parts;if(Array.isArray(nested)){for(const inner of nested){if(inner.inlineData||inner.fileData){tokens+=imageTokenEstimate}else if(typeof inner.text==="string"){tokens+=estimateContextTextTokens(inner.text)}}}return tokens}__name(estimateFunctionResponseTokens,"estimateFunctionResponseTokens");function consumeBilledSkillBody(part,billedSkillBodies){if(billedSkillBodies.size===0)return false;const output=part.functionResponse?.response?.output;if(typeof output!=="string")return false;if(billedSkillBodies.delete(output))return true;for(const body of billedSkillBodies){if(output.startsWith(`${body}
6
6
  `)){billedSkillBodies.delete(body);return true}}return false}__name(consumeBilledSkillBody,"consumeBilledSkillBody");function estimateConversationTokens(conversation,billing){let tokens=0;const remainingSkillBodies=new Set(billing.billedSkillBodies);for(const content of conversation){for(const part of content.parts??[]){if(typeof part.text==="string"){if(billing.billedListingTexts.has(part.text))continue;tokens+=estimateContextTextTokens(part.text)}else if(part.inlineData||part.fileData){tokens+=billing.imageTokenEstimate}else if(part.functionCall){tokens+=estimateContextTextTokens(JSON.stringify(part.functionCall))}else if(part.functionResponse){if(part.functionResponse.name===ToolNames.SKILL&&consumeBilledSkillBody(part,remainingSkillBodies)){continue}tokens+=estimateFunctionResponseTokens(part,billing.imageTokenEstimate)}}}return tokens}__name(estimateConversationTokens,"estimateConversationTokens");async function collectContextData(config,showDetails){const modelName=config.getModel()||"unknown";const contentGeneratorConfig=config.getContentGeneratorConfig();const contextWindowSize=contentGeneratorConfig.contextWindowSize??DEFAULT_TOKEN_LIMIT;const llmClient=config.getLlmClient?.();const activeChat=llmClient?.isInitialized?.()?llmClient.getChat():void 0;const apiTotalTokens=activeChat?activeChat.getLastPromptTokenCount():uiTelemetryService.getLastPromptTokenCount();const apiCachedTokens=activeChat?.getLastCachedContentTokenCount?.()??uiTelemetryService.getLastCachedContentTokenCount();const history=activeChat?.getHistoryShallow?.()??activeChat?.getHistory?.()??[];const preludeLength=getStartupContextLength(history);const prelude=measureStartupPrelude(withoutAutoMemorySnapshots(history.slice(0,preludeLength)));const conversationHistory=withoutAutoMemorySnapshots(history.slice(preludeLength));const tailSkillListings=measureTailSkillListings(conversationHistory);let conversationTokens=0;const systemPromptText=getMainSessionBaseSystemPrompt(config);const systemPromptTokens=estimateContextTextTokens(systemPromptText);const toolRegistry=config.getToolRegistry();const allTools=toolRegistry?toolRegistry.getAllTools():[];const toolDeclarations=toolRegistry?toolRegistry.getFunctionDeclarations():[];const toolsJsonStr=JSON.stringify(toolDeclarations);const allToolsTokens=estimateContextTextTokens(toolsJsonStr);const builtinTools=[];const mcpTools=[];for(const declaration of toolDeclarations){const tool=allTools.find(tool2=>tool2.name===declaration.name);const toolJsonStr=JSON.stringify(declaration);const tokens=estimateContextTextTokens(toolJsonStr);if(tool instanceof DiscoveredMCPTool){mcpTools.push({name:`${tool.serverName}__${tool.serverToolName||tool.name}`,tokens})}else if(declaration.name!==ToolNames.SKILL){builtinTools.push({name:declaration.name,tokens})}}const memoryContent=config.getUserMemory();const instructionFiles=parseMemoryFiles(memoryContent,config.getWorkingDir(),extensionContextFileOwners(config,config.getWorkingDir()),config.storage.getProjectRoot());const memoryFiles=[];const instructionFilesTokens=instructionFiles.reduce((sum,f)=>sum+f.tokens,0);const catalog=config.getAutoMemoryContext?.()??"";const snapshots=catalog?history.flatMap(content=>(content.parts??[]).filter(part=>part.partMetadata?.[AUTO_MEMORY_SNAPSHOT_METADATA]===true)):[];const pendingSnapshot=getAutoMemorySnapshot(history,catalog);if(pendingSnapshot)snapshots.push(pendingSnapshot);const autoMemoryTokens=estimateContextTextTokens(config.getAutoMemoryPrompt())+snapshots.reduce((sum,part)=>sum+estimateContextTextTokens(part.text??""),0);if(autoMemoryTokens>0){memoryFiles.push({path:t("auto memory"),tokens:autoMemoryTokens})}const memoryFilesTokens=memoryFiles.reduce((sum,f)=>sum+f.tokens,0);const skillTool=allTools.find(tool=>tool.name===ToolNames.SKILL);const skillDeclaration=toolDeclarations.find(declaration=>declaration.name===ToolNames.SKILL);const skillToolDefinitionTokens=skillDeclaration?estimateContextTextTokens(JSON.stringify(skillDeclaration)):0;const loadedContentNames=skillTool&&"getLoadedSkillContentNames"in skillTool?skillTool.getLoadedSkillContentNames():new Map;const bodyTokensByName=new Map;for(const[content,name]of loadedContentNames){bodyTokensByName.set(name,(bodyTokensByName.get(name)??0)+estimateContextTextTokens(content))}const loadedBodiesTokens=[...bodyTokensByName.values()].reduce((sum,tokens)=>sum+tokens,0);const skillManager=config.getSkillManager();const skillConfigs=skillManager?await skillManager.listSkills():[];const enabledSkillNames=new Set(skillConfigs.filter(skill=>config.isSkillEnabled(skill)).map(skill=>skill.name.toLowerCase()));let skillListing=prelude.skillListing;if(!activeChat){const reminder=await buildAvailableSkillsReminder(config);if(reminder){skillListing=measureSkillListing(reminder.reminder)}}mergeSkillListing(skillListing,tailSkillListings.listing);const billedSkillBodies=new Set(loadedContentNames.keys());const skills=skillConfigs.map(skill=>{const listingTokens=skillListing.byName.get(skill.name.toLowerCase())?.tokens??0;const bodyTokens=bodyTokensByName.get(skill.name);const isLoaded=bodyTokens!==void 0;return{name:skill.name,tokens:listingTokens,loaded:isLoaded,bodyTokens}});const discoveredNames=new Set(skillConfigs.map(skill=>skill.name));for(const[name,bodyTokens]of bodyTokensByName){if(!discoveredNames.has(name)){skills.push({name,tokens:skillListing.byName.get(name.toLowerCase())?.tokens??0,loaded:true,bodyTokens})}}const rowedNames=new Set(skills.map(s=>s.name.toLowerCase()));for(const[key,entry]of skillListing.byName){enabledSkillNames.add(key);if(rowedNames.has(key))continue;rowedNames.add(key);skills.push({name:entry.name,tokens:entry.tokens,loaded:false})}conversationTokens=estimateConversationTokens(conversationHistory,{imageTokenEstimate:resolveSlimmingConfig(config.getChatCompression?.()).imageTokenEstimate,billedSkillBodies,billedListingTexts:tailSkillListings.billedTexts});const skillsTokens=skillToolDefinitionTokens+skillListing.tokens+loadedBodiesTokens;const startupContextTokens=prelude.startupContextTokens;const thresholds=computeThresholds(contextWindowSize,config.getAutoCompactThreshold());const autocompactBuffer=Math.max(0,Math.round(contextWindowSize-thresholds.auto));const rawOverhead=systemPromptTokens+allToolsTokens+instructionFilesTokens+memoryFilesTokens+skillListing.tokens+loadedBodiesTokens+startupContextTokens;const rawContent=rawOverhead+conversationTokens;const hasTokenCount=apiTotalTokens>0;const isEstimated=!hasTokenCount||activeChat?.isLastPromptTokenCountEstimated()===true;const mcpToolsTotalTokens=mcpTools.reduce((sum,tool)=>sum+tool.tokens,0);const totalTokens=hasTokenCount?apiTotalTokens:0;const clampDeficit=Math.max(0,skillToolDefinitionTokens+mcpToolsTotalTokens-allToolsTokens);const clampedMcpTools=Math.max(0,mcpToolsTotalTokens-clampDeficit);const clampedSkills=skillsTokens-Math.max(0,clampDeficit-mcpToolsTotalTokens);const clampedBuiltinTools=Math.max(0,allToolsTokens-skillToolDefinitionTokens-clampedMcpTools);const mcpDetailShare=mcpToolsTotalTokens>0?clampedMcpTools/mcpToolsTotalTokens:1;const detailMcpTools=mcpDetailShare<1?mcpTools.map(item=>({...item,tokens:Math.round(item.tokens*mcpDetailShare)})):mcpTools;const tierTokens=hasTokenCount?apiTotalTokens:rawContent;const freeSpace=Math.max(0,contextWindowSize-tierTokens-autocompactBuffer);const breakdown={systemPrompt:systemPromptTokens,builtinTools:clampedBuiltinTools,mcpTools:clampedMcpTools,instructionFiles:instructionFilesTokens,memoryFiles:memoryFilesTokens,skills:clampedSkills,startupContext:startupContextTokens,messages:conversationTokens,cachedTokens:hasTokenCount?apiCachedTokens:0,freeSpace,autocompactBuffer,thresholds,currentTier:currentTier(tierTokens,thresholds)};return{type:"context_usage",modelName,totalTokens,contextWindowSize,breakdown,builtinTools:showDetails?builtinTools:[],mcpTools:showDetails?detailMcpTools:[],instructionFiles:showDetails?instructionFiles:[],memoryFiles:showDetails?memoryFiles:[],skills:showDetails?skills.filter(skill=>skill.loaded||enabledSkillNames.has(skill.name.toLowerCase())):[],isEstimated,showDetails}}__name(collectContextData,"collectContextData");function fmtTokens(tokens){if(tokens>=999950){return`${(tokens/1e6).toFixed(1)}m`}if(tokens>=1e3){return`${(tokens/1e3).toFixed(1)}k`}return`${tokens}`}__name(fmtTokens,"fmtTokens");function fmtCategoryRow(label,tokens,contextWindowSize,indent=" "){const percentage=contextWindowSize>0?(tokens/contextWindowSize*100).toFixed(1):"0.0";const right=`${fmtTokens(tokens)} tokens (${percentage}%)`;const leftPart=`${indent}${label}`;const totalWidth=56;const dots=Math.max(1,totalWidth-leftPart.length-right.length);return`${leftPart}${" ".repeat(dots)}${right}`}__name(fmtCategoryRow,"fmtCategoryRow");function formatNum(n){return Math.round(n).toLocaleString("en-US")}__name(formatNum,"formatNum");function formatContextUsageText(data){const{modelName,totalTokens,contextWindowSize,breakdown,builtinTools,mcpTools,instructionFiles=[],memoryFiles,skills,isEstimated,showDetails}=data;const hasTokenCount=totalTokens>0;const memoryLabel=breakdown.instructionFiles===void 0?"Memory files":"Auto memory";const lines=[];lines.push("## Context Usage");lines.push("");if(!hasTokenCount){const includesConversation=breakdown.messages>0;lines.push(includesConversation?"*No provider usage yet. These are local estimates, including the conversation.*":"*No API response yet. Send a message to see actual usage.*");lines.push("");lines.push(includesConversation?"**Estimated usage, including the conversation**":"**Estimated pre-conversation overhead**");lines.push(`Model: ${modelName} Context window: ${fmtTokens(contextWindowSize)} tokens`);lines.push("")}else{lines.push(`Model: ${modelName} Context window: ${fmtTokens(contextWindowSize)} tokens`);lines.push("");if(isEstimated){lines.push("*Token usage is estimated until provider usage is received.*");lines.push("")}lines.push(fmtCategoryRow("Used",totalTokens,contextWindowSize));if((breakdown.cachedTokens??0)>0){lines.push(fmtCategoryRow("Cached prefix",breakdown.cachedTokens,contextWindowSize," \u2514 "))}lines.push(fmtCategoryRow("Free",breakdown.freeSpace,contextWindowSize));lines.push("");lines.push("**Compaction thresholds**");lines.push(` Effective window: ${formatNum(breakdown.thresholds.effectiveWindow)} (window \u2212 ${formatNum(contextWindowSize-breakdown.thresholds.effectiveWindow)} reserve)`);lines.push(` Warn threshold: ${formatNum(breakdown.thresholds.warn)}`);lines.push(` Auto threshold: ${formatNum(breakdown.thresholds.auto)}`);lines.push(` Hard threshold: ${formatNum(breakdown.thresholds.hard)}`);lines.push(` Current tier: ${breakdown.currentTier}`);lines.push("");lines.push("**Usage by category**")}lines.push(fmtCategoryRow("System prompt",breakdown.systemPrompt,contextWindowSize));lines.push(fmtCategoryRow("Built-in tools",breakdown.builtinTools,contextWindowSize));if(breakdown.mcpTools>0){lines.push(fmtCategoryRow("MCP tools",breakdown.mcpTools,contextWindowSize))}if(breakdown.instructionFiles!==void 0){lines.push(fmtCategoryRow("Instruction files",breakdown.instructionFiles,contextWindowSize))}lines.push(fmtCategoryRow(memoryLabel,breakdown.memoryFiles,contextWindowSize));lines.push(fmtCategoryRow("Skills",breakdown.skills,contextWindowSize));if((breakdown.startupContext??0)>0){lines.push(fmtCategoryRow("Startup context",breakdown.startupContext,contextWindowSize))}if(hasTokenCount||breakdown.messages>0){lines.push(fmtCategoryRow("Messages",breakdown.messages,contextWindowSize))}if(showDetails){const sortedBuiltin=[...builtinTools].sort((a,b)=>b.tokens-a.tokens);const sortedMcp=[...mcpTools].sort((a,b)=>b.tokens-a.tokens);const sortedMemory=[...memoryFiles].sort((a,b)=>b.tokens-a.tokens);const sortedSkills=[...skills].sort((a,b)=>{if(!a.loaded!==!b.loaded)return a.loaded?-1:1;return b.tokens+(b.bodyTokens??0)-(a.tokens+(a.bodyTokens??0))});if(sortedBuiltin.length>0){lines.push("");lines.push("**Built-in tools**");for(const tool of sortedBuiltin){lines.push(fmtCategoryRow(tool.name,tool.tokens,contextWindowSize," \u2514 "))}}if(sortedMcp.length>0){lines.push("");lines.push("**MCP tools**");for(const tool of sortedMcp){lines.push(fmtCategoryRow(tool.name,tool.tokens,contextWindowSize," \u2514 "))}}if(instructionFiles.length>0){lines.push("","**Instruction files**");for(const file of[...instructionFiles].sort((a,b)=>b.tokens-a.tokens)){lines.push(fmtCategoryRow(file.path,file.tokens,contextWindowSize," \u2514 "))}}if(sortedMemory.length>0){lines.push("");lines.push("**"+memoryLabel+"**");for(const file of sortedMemory){lines.push(fmtCategoryRow(file.path,file.tokens,contextWindowSize," \u2514 "))}}if(sortedSkills.length>0){lines.push("");lines.push("**Skills**");for(const skill of sortedSkills){lines.push(fmtCategoryRow(skill.name,skill.tokens,contextWindowSize," \u2514 "));if(skill.loaded&&skill.bodyTokens&&skill.bodyTokens>0){lines.push(fmtCategoryRow("body loaded",skill.bodyTokens,contextWindowSize," \u2514 "))}}}}else{lines.push("");lines.push("*Run /context detail for per-item breakdown.*")}return lines.join("\n")}__name(formatContextUsageText,"formatContextUsageText");var contextCommand={name:"context",get description(){return t('Show context window usage breakdown. Use "/context detail" for per-item breakdown.')},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async(context,args)=>{const normalizedArgs=args?.trim().toLowerCase();const showDetails=normalizedArgs==="detail"||normalizedArgs==="-d";const executionMode=context.executionMode??"interactive";const{config}=context.services;if(!config){if(executionMode==="interactive"){context.ui.addItem({type:"error",text:t("Config not loaded.")},Date.now());return}return{type:"message",messageType:"error",content:t("Config not loaded.")}}const contextUsageItem=await collectContextData(config,showDetails);if(executionMode==="interactive"){context.ui.addItem(contextUsageItem,Date.now());return}return{type:"message",messageType:"info",content:formatContextUsageText(contextUsageItem)}},"action"),subCommands:[{name:"detail",get description(){return t("Show per-item context usage breakdown.")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:__name(async context=>{await contextCommand.action(context,"detail")},"action")}]};export{EXTENSION_CONTEXT_BUDGET,parseExtensionRef,buildExtensionRef,matchExtensionByRef,sanitizeDisplayText,getSanitizedExtensionDisplayName,buildExtensionMentionContext,collectContextData,formatContextUsageText,contextCommand};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{functionResponsePartsToString}from"./chunk-3NB3FFLR.js";import{observeHeadlessToolResultProjection,observeHeadlessToolResultWire}from"./chunk-SOCXRMZM.js";import{projectJsonStringToByteBudget}from"./chunk-WQUA4G2X.js";import{createNotStartedToolErrorResponse,parseAndFormatApiError,toolResultBoundaryArtifact}from"./chunk-PFKTTUGS.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{formatVisionBridgeNoticeDisplay,isVisionBridgeNoticeDisplay}from"./chunk-MJEL7DIE.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{randomUUID as randomUUID2}from"node:crypto";init_esbuild_shims();import{randomUUID}from"node:crypto";init_esbuild_shims();var HEADLESS_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET=65536;var HEADLESS_TOOL_RESULT_TEXT_TRUNCATION_MARKER="\n[... truncated for Headless transport ...]\n";function projectHeadlessToolResultContent(value){return projectJsonStringToByteBudget(value,HEADLESS_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET,HEADLESS_TOOL_RESULT_TEXT_TRUNCATION_MARKER)}__name(projectHeadlessToolResultContent,"projectHeadlessToolResultContent");var BaseJsonOutputAdapter=class{static{__name(this,"BaseJsonOutputAdapter")}config;mainAgentMessageState;subagentMessageStates=new Map;lastAssistantMessage=null;permissionDenials=[];constructor(config){this.config=config;this.mainAgentMessageState=this.createMessageState()}createMessageState(){return{messageId:null,blocks:[],openBlocks:new Set,usage:this.createUsage(),messageStarted:false,finalized:false,currentBlockType:null}}getMessageState(parentToolUseId){if(parentToolUseId===null){return this.mainAgentMessageState}let state=this.subagentMessageStates.get(parentToolUseId);if(!state){state=this.createMessageState();this.subagentMessageStates.set(parentToolUseId,state)}return state}createUsage(metadata){const usage={input_tokens:0,output_tokens:0};if(!metadata){return usage}if(typeof metadata.promptTokenCount==="number"){usage.input_tokens=metadata.promptTokenCount}if(typeof metadata.candidatesTokenCount==="number"){usage.output_tokens=metadata.candidatesTokenCount}if(typeof metadata.cachedContentTokenCount==="number"){usage.cache_read_input_tokens=metadata.cachedContentTokenCount}if(typeof metadata.totalTokenCount==="number"){usage.total_tokens=metadata.totalTokenCount}return usage}buildMessage(parentToolUseId){const state=this.getMessageState(parentToolUseId);if(!state.messageId){throw new Error("Message not started")}if(state.blocks.length>0){const blockTypes=new Set(state.blocks.map(block=>block.type));if(blockTypes.size>1){throw new Error(`Assistant message must contain only one type of ContentBlock, found: ${Array.from(blockTypes).join(", ")}`)}}const stopReason=state.blocks.length>0&&state.blocks.every(block=>block.type==="tool_use")?"tool_use":null;return{type:"assistant",uuid:state.messageId,session_id:this.config.getSessionId(),parent_tool_use_id:parentToolUseId,message:{id:state.messageId,type:"message",role:"assistant",model:this.config.getModel(),content:state.blocks,stop_reason:stopReason,usage:state.usage}}}finalizePendingBlocks(state,parentToolUseId){const actualParentToolUseId=parentToolUseId??null;const lastBlock=state.blocks[state.blocks.length-1];if(!lastBlock){return}const index=state.blocks.length-1;if(!state.openBlocks.has(index)){return}if(lastBlock.type==="text"||lastBlock.type==="thinking"){this.onBlockClosed(state,index,actualParentToolUseId);this.closeBlock(state,index)}}openBlock(state,index,_block){state.openBlocks.add(index)}closeBlock(state,index){if(!state.openBlocks.has(index)){return}state.openBlocks.delete(index)}ensureBlockTypeConsistency(state,targetType,parentToolUseId){if(state.currentBlockType===targetType){return}if(state.currentBlockType===null){state.currentBlockType=targetType;return}this.finalizeAssistantMessageInternal(state,parentToolUseId);this.startAssistantMessageInternal(state);state.currentBlockType=targetType}startAssistantMessageInternal(state){state.messageId=randomUUID();state.blocks=[];state.openBlocks=new Set;state.usage=this.createUsage();state.messageStarted=false;state.finalized=false;state.currentBlockType=null}finalizeAssistantMessageInternal(state,parentToolUseId){if(state.finalized){return this.buildMessage(parentToolUseId)}state.finalized=true;this.finalizePendingBlocks(state,parentToolUseId);const orderedOpenBlocks=Array.from(state.openBlocks).sort((a,b)=>a-b);for(const index of orderedOpenBlocks){this.onBlockClosed(state,index,parentToolUseId);this.closeBlock(state,index)}const message=this.buildMessage(parentToolUseId);if(state.messageStarted){this.emitMessageImpl(message)}return message}emitControlMessageImpl(_message){}onTextBlockCreated(_state,_index,_block,_parentToolUseId){}onTextAppended(_state,_index,_fragment,_parentToolUseId){}onThinkingBlockCreated(_state,_index,_block,_parentToolUseId){}onThinkingAppended(_state,_index,_fragment,_parentToolUseId){}onToolUseBlockCreated(_state,_index,_block,_parentToolUseId){}onToolUseInputSet(_state,_index,_input,_parentToolUseId){}onBlockClosed(_state,_index,_parentToolUseId){}onEnsureMessageStarted(_state,_parentToolUseId){}getSessionId(){return this.config.getSessionId()}getModel(){return this.config.getModel()}startAssistantMessage(){this.startAssistantMessageInternal(this.mainAgentMessageState)}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const state=this.mainAgentMessageState;const retainedBlocks=[];const retainedOpenBlocks=new Set;for(const[index,block]of state.blocks.entries()){if(block.type==="tool_use"&&discardedIds.has(block.id)){continue}const retainedIndex=retainedBlocks.length;retainedBlocks.push(block);if(state.openBlocks.has(index)){retainedOpenBlocks.add(retainedIndex)}}state.blocks=retainedBlocks;state.openBlocks=retainedOpenBlocks;state.currentBlockType=retainedBlocks.at(-1)?.type??null;state.messageStarted=retainedBlocks.length>0}return}this.startAssistantMessageInternal(this.mainAgentMessageState)}emitDiscardedAttemptToolResults(discardedToolCalls){const message="Skipped because the provider attempt was retried before execution.";for(const request of discardedToolCalls){this.emitToolResult(request,createNotStartedToolErrorResponse(request,message))}}processEvent(event){const state=this.mainAgentMessageState;if(state.finalized){return}switch(event.type){case"content":this.appendText(state,event.value,null);break;case"citation":if(typeof event.value==="string"){this.appendText(state,`
3
+ import{functionResponsePartsToString}from"./chunk-T2GM4S4G.js";import{observeHeadlessToolResultProjection,observeHeadlessToolResultWire}from"./chunk-OZL4ZMGQ.js";import{projectJsonStringToByteBudget}from"./chunk-WQUA4G2X.js";import{createNotStartedToolErrorResponse,parseAndFormatApiError,toolResultBoundaryArtifact}from"./chunk-ZUWLTGSR.js";import{shellResultText}from"./chunk-T7CHK6C2.js";import{formatVisionBridgeNoticeDisplay,isVisionBridgeNoticeDisplay}from"./chunk-MJEL7DIE.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{randomUUID as randomUUID2}from"node:crypto";init_esbuild_shims();import{randomUUID}from"node:crypto";init_esbuild_shims();var HEADLESS_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET=65536;var HEADLESS_TOOL_RESULT_TEXT_TRUNCATION_MARKER="\n[... truncated for Headless transport ...]\n";function projectHeadlessToolResultContent(value){return projectJsonStringToByteBudget(value,HEADLESS_TOOL_RESULT_TEXT_JSON_BYTE_BUDGET,HEADLESS_TOOL_RESULT_TEXT_TRUNCATION_MARKER)}__name(projectHeadlessToolResultContent,"projectHeadlessToolResultContent");var BaseJsonOutputAdapter=class{static{__name(this,"BaseJsonOutputAdapter")}config;mainAgentMessageState;subagentMessageStates=new Map;lastAssistantMessage=null;permissionDenials=[];constructor(config){this.config=config;this.mainAgentMessageState=this.createMessageState()}createMessageState(){return{messageId:null,blocks:[],openBlocks:new Set,usage:this.createUsage(),messageStarted:false,finalized:false,currentBlockType:null}}getMessageState(parentToolUseId){if(parentToolUseId===null){return this.mainAgentMessageState}let state=this.subagentMessageStates.get(parentToolUseId);if(!state){state=this.createMessageState();this.subagentMessageStates.set(parentToolUseId,state)}return state}createUsage(metadata){const usage={input_tokens:0,output_tokens:0};if(!metadata){return usage}if(typeof metadata.promptTokenCount==="number"){usage.input_tokens=metadata.promptTokenCount}if(typeof metadata.candidatesTokenCount==="number"){usage.output_tokens=metadata.candidatesTokenCount}if(typeof metadata.cachedContentTokenCount==="number"){usage.cache_read_input_tokens=metadata.cachedContentTokenCount}if(typeof metadata.totalTokenCount==="number"){usage.total_tokens=metadata.totalTokenCount}return usage}buildMessage(parentToolUseId){const state=this.getMessageState(parentToolUseId);if(!state.messageId){throw new Error("Message not started")}if(state.blocks.length>0){const blockTypes=new Set(state.blocks.map(block=>block.type));if(blockTypes.size>1){throw new Error(`Assistant message must contain only one type of ContentBlock, found: ${Array.from(blockTypes).join(", ")}`)}}const stopReason=state.blocks.length>0&&state.blocks.every(block=>block.type==="tool_use")?"tool_use":null;return{type:"assistant",uuid:state.messageId,session_id:this.config.getSessionId(),parent_tool_use_id:parentToolUseId,message:{id:state.messageId,type:"message",role:"assistant",model:this.config.getModel(),content:state.blocks,stop_reason:stopReason,usage:state.usage}}}finalizePendingBlocks(state,parentToolUseId){const actualParentToolUseId=parentToolUseId??null;const lastBlock=state.blocks[state.blocks.length-1];if(!lastBlock){return}const index=state.blocks.length-1;if(!state.openBlocks.has(index)){return}if(lastBlock.type==="text"||lastBlock.type==="thinking"){this.onBlockClosed(state,index,actualParentToolUseId);this.closeBlock(state,index)}}openBlock(state,index,_block){state.openBlocks.add(index)}closeBlock(state,index){if(!state.openBlocks.has(index)){return}state.openBlocks.delete(index)}ensureBlockTypeConsistency(state,targetType,parentToolUseId){if(state.currentBlockType===targetType){return}if(state.currentBlockType===null){state.currentBlockType=targetType;return}this.finalizeAssistantMessageInternal(state,parentToolUseId);this.startAssistantMessageInternal(state);state.currentBlockType=targetType}startAssistantMessageInternal(state){state.messageId=randomUUID();state.blocks=[];state.openBlocks=new Set;state.usage=this.createUsage();state.messageStarted=false;state.finalized=false;state.currentBlockType=null}finalizeAssistantMessageInternal(state,parentToolUseId){if(state.finalized){return this.buildMessage(parentToolUseId)}state.finalized=true;this.finalizePendingBlocks(state,parentToolUseId);const orderedOpenBlocks=Array.from(state.openBlocks).sort((a,b)=>a-b);for(const index of orderedOpenBlocks){this.onBlockClosed(state,index,parentToolUseId);this.closeBlock(state,index)}const message=this.buildMessage(parentToolUseId);if(state.messageStarted){this.emitMessageImpl(message)}return message}emitControlMessageImpl(_message){}onTextBlockCreated(_state,_index,_block,_parentToolUseId){}onTextAppended(_state,_index,_fragment,_parentToolUseId){}onThinkingBlockCreated(_state,_index,_block,_parentToolUseId){}onThinkingAppended(_state,_index,_fragment,_parentToolUseId){}onToolUseBlockCreated(_state,_index,_block,_parentToolUseId){}onToolUseInputSet(_state,_index,_input,_parentToolUseId){}onBlockClosed(_state,_index,_parentToolUseId){}onEnsureMessageStarted(_state,_parentToolUseId){}getSessionId(){return this.config.getSessionId()}getModel(){return this.config.getModel()}startAssistantMessage(){this.startAssistantMessageInternal(this.mainAgentMessageState)}restartAttempt(preserveText,discardedToolCalls){if(preserveText){const discardedIds=new Set(discardedToolCalls.map(request=>request.callId));if(discardedIds.size>0){const state=this.mainAgentMessageState;const retainedBlocks=[];const retainedOpenBlocks=new Set;for(const[index,block]of state.blocks.entries()){if(block.type==="tool_use"&&discardedIds.has(block.id)){continue}const retainedIndex=retainedBlocks.length;retainedBlocks.push(block);if(state.openBlocks.has(index)){retainedOpenBlocks.add(retainedIndex)}}state.blocks=retainedBlocks;state.openBlocks=retainedOpenBlocks;state.currentBlockType=retainedBlocks.at(-1)?.type??null;state.messageStarted=retainedBlocks.length>0}return}this.startAssistantMessageInternal(this.mainAgentMessageState)}emitDiscardedAttemptToolResults(discardedToolCalls){const message="Skipped because the provider attempt was retried before execution.";for(const request of discardedToolCalls){this.emitToolResult(request,createNotStartedToolErrorResponse(request,message))}}processEvent(event){const state=this.mainAgentMessageState;if(state.finalized){return}switch(event.type){case"content":this.appendText(state,event.value,null);break;case"citation":if(typeof event.value==="string"){this.appendText(state,`
4
4
  ${event.value}`,null)}break;case"thought":this.appendThinking(state,event.value.subject,event.value.description,null);break;case"tool_call_request":this.appendToolUse(state,event.value,null);break;case"finished":if(event.value?.usageMetadata){state.usage=this.createUsage(event.value.usageMetadata)}this.finalizePendingBlocks(state,null);break;case"error":{const errorText=parseAndFormatApiError(event.value.error,this.config.getContentGeneratorConfig()?.authType);this.appendText(state,errorText,null);break}case"model_fallback":this.emitSystemMessage("model_fallback",{fromModel:event.fromModel,toModel:event.toModel,statusCode:event.statusCode,fallbackIndex:event.fallbackIndex});break;default:break}}startSubagentAssistantMessage(parentToolUseId){const state=this.getMessageState(parentToolUseId);this.startAssistantMessageInternal(state)}finalizeSubagentAssistantMessage(parentToolUseId){const state=this.getMessageState(parentToolUseId);return this.finalizeAssistantMessageInternal(state,parentToolUseId)}emitSubagentErrorResult(errorMessage,numTurns,parentToolUseId){const state=this.getMessageState(parentToolUseId);if(state.messageStarted&&!state.finalized){this.finalizeSubagentAssistantMessage(parentToolUseId)}const errorResult=this.buildSubagentErrorResult(errorMessage,numTurns);this.emitMessageImpl(errorResult)}processSubagentToolCall(toolCall,parentToolUseId){const state=this.getMessageState(parentToolUseId);const hasText=state.blocks.some(b=>b.type==="text")||state.currentBlockType==="text"&&state.blocks.length>0;if(hasText){this.finalizeSubagentAssistantMessage(parentToolUseId);this.startSubagentAssistantMessage(parentToolUseId)}if(!state.messageId||!state.messageStarted){this.startAssistantMessageInternal(state)}this.ensureBlockTypeConsistency(state,"tool_use",parentToolUseId);this.ensureMessageStarted(state,parentToolUseId);this.finalizePendingBlocks(state,parentToolUseId);const{index}=this.createSubagentToolUseBlock(state,toolCall,parentToolUseId);this.processSubagentToolUseBlock(state,index,toolCall,parentToolUseId);this.finalizeSubagentAssistantMessage(parentToolUseId);this.startSubagentAssistantMessage(parentToolUseId)}processSubagentToolUseBlock(state,index,toolCall,parentToolUseId){const startBlock={type:"tool_use",id:toolCall.callId,name:toolCall.name,input:{}};this.onToolUseBlockCreated(state,index,startBlock,parentToolUseId);this.onToolUseInputSet(state,index,toolCall.args??{},parentToolUseId);this.onBlockClosed(state,index,parentToolUseId);this.closeBlock(state,index)}updateLastAssistantMessage(message){this.lastAssistantMessage=message}appendText(state,fragment,parentToolUseId){if(fragment.length===0){return}this.ensureBlockTypeConsistency(state,"text",parentToolUseId);this.ensureMessageStarted(state,parentToolUseId);let current=state.blocks[state.blocks.length-1];const isNewBlock=!current||current.type!=="text";if(isNewBlock){current={type:"text",text:""};const index2=state.blocks.length;state.blocks.push(current);this.openBlock(state,index2,current);this.onTextBlockCreated(state,index2,current,parentToolUseId)}current.text+=fragment;const index=state.blocks.length-1;this.onTextAppended(state,index,fragment,parentToolUseId)}appendThinking(state,subject,description,parentToolUseId){const actualParentToolUseId=parentToolUseId??null;const parts=[];if(subject&&subject.length>0){parts.push(subject)}if(description&&description.length>0){parts.push(description)}const fragment=parts.join(": ");if(!fragment){return}this.ensureBlockTypeConsistency(state,"thinking",actualParentToolUseId);this.ensureMessageStarted(state,actualParentToolUseId);let current=state.blocks[state.blocks.length-1];const isNewBlock=!current||current.type!=="thinking";if(isNewBlock){current={type:"thinking",thinking:"",signature:subject};const index2=state.blocks.length;state.blocks.push(current);this.openBlock(state,index2,current);this.onThinkingBlockCreated(state,index2,current,actualParentToolUseId)}current.thinking=`${current.thinking??""}${fragment}`;const index=state.blocks.length-1;this.onThinkingAppended(state,index,fragment,actualParentToolUseId)}appendToolUse(state,request,parentToolUseId){this.ensureBlockTypeConsistency(state,"tool_use",parentToolUseId);this.ensureMessageStarted(state,parentToolUseId);this.finalizePendingBlocks(state,parentToolUseId);const index=state.blocks.length;const block={type:"tool_use",id:request.callId,name:request.name,input:request.args};state.blocks.push(block);this.openBlock(state,index,block);const startBlock={type:"tool_use",id:request.callId,name:request.name,input:{}};this.onToolUseBlockCreated(state,index,startBlock,parentToolUseId);this.onToolUseInputSet(state,index,request.args??{},parentToolUseId);this.onBlockClosed(state,index,parentToolUseId);this.closeBlock(state,index)}ensureMessageStarted(state,parentToolUseId){if(state.messageStarted){return}state.messageStarted=true;this.onEnsureMessageStarted(state,parentToolUseId)}createSubagentToolUseBlock(state,toolCall,_parentToolUseId){const index=state.blocks.length;const block={type:"tool_use",id:toolCall.callId,name:toolCall.name,input:toolCall.args||{}};state.blocks.push(block);this.openBlock(state,index,block);return{block,index}}emitUserMessage(parts,parentToolUseId){const content=partsToContentBlock(parts);const message={type:"user",uuid:randomUUID(),session_id:this.getSessionId(),parent_tool_use_id:parentToolUseId??null,message:{role:"user",content}};this.emitMessageImpl(message)}checkResponsePartsForError(responseParts){return checkResponsePartsForError(responseParts)}emitToolResult(request,response,parentToolUseId=null){const responsePartsError=this.checkResponsePartsForError(response.responseParts);const hasError=Boolean(response.error)||Boolean(responsePartsError);if(response.error&&response.errorType==="execution_denied"){const denial={tool_name:request.name,tool_use_id:request.callId,tool_input:request.args};this.permissionDenials.push(denial)}const block={type:"tool_result",tool_use_id:request.callId,is_error:hasError};const content=toolResultContent(response);let projectedContent;if(content!==void 0){projectedContent=projectHeadlessToolResultContent(content);block.content=projectedContent}const message={type:"user",uuid:randomUUID(),session_id:this.getSessionId(),parent_tool_use_id:parentToolUseId,message:{role:"user",content:[block]}};if(content!==void 0&&projectedContent!==void 0){observeHeadlessToolResultProjection(message,content,projectedContent,request.callId,response.boundaryArtifact??toolResultBoundaryArtifact(response.persistedOutputFiles,response.artifacts))}this.emitMessageImpl(message)}emitSystemMessage(subtype,data){const systemMessage={type:"system",subtype,uuid:randomUUID(),session_id:this.getSessionId(),parent_tool_use_id:null,data};this.emitMessageImpl(systemMessage)}emitPermissionRequest(requestId,toolName,toolUseId,input,blockedPath=null,permissionSuggestions=null){const message={type:"control_request",request_id:requestId,request:{subtype:"can_use_tool",tool_name:toolName,tool_use_id:toolUseId,input,permission_suggestions:permissionSuggestions,blocked_path:blockedPath}};this.emitControlMessageImpl(message)}emitControlResponse(requestId,allowed){const message={type:"control_response",response:{subtype:"success",request_id:requestId,response:{allowed}}};this.emitControlMessageImpl(message)}emitControlError(requestId,errorMessage){const message={type:"control_response",response:{subtype:"error",request_id:requestId,error:errorMessage}};this.emitControlMessageImpl(message)}emitToolProgress(_request,_progress){}buildResultMessage(options,lastAssistantMessage){const usage=options.usage??createExtendedUsage();const resultText=options.summary??(lastAssistantMessage?extractTextFromBlocks(lastAssistantMessage.message.content):"");const baseUuid=randomUUID();const baseSessionId=this.getSessionId();if(options.isError){const errorMessage=options.errorMessage??"Unknown error";return{type:"result",subtype:options.subtype??"error_during_execution",uuid:baseUuid,session_id:baseSessionId,is_error:true,duration_ms:options.durationMs,duration_api_ms:options.apiDurationMs,num_turns:options.numTurns,usage,permission_denials:[...this.permissionDenials],error:{message:errorMessage}}}else{const hasStructured="structuredResult"in options;const normalizedStructured=hasStructured?options.structuredResult??null:void 0;const finalResult=hasStructured?JSON.stringify(normalizedStructured):resultText;const success={type:"result",subtype:options.subtype??"success",uuid:baseUuid,session_id:baseSessionId,is_error:false,duration_ms:options.durationMs,duration_api_ms:options.apiDurationMs,num_turns:options.numTurns,result:finalResult,usage,permission_denials:[...this.permissionDenials]};if(options.stats){success.stats=options.stats}if(hasStructured){success.structured_result=normalizedStructured}return success}}buildSubagentErrorResult(errorMessage,numTurns){const usage={input_tokens:0,output_tokens:0};return{type:"result",subtype:"error_during_execution",uuid:randomUUID(),session_id:this.getSessionId(),is_error:true,duration_ms:0,duration_api_ms:0,num_turns:numTurns,usage,permission_denials:[],error:{message:errorMessage}}}};function partsToContentBlock(parts){const blocks=[];let currentTextBlock=null;for(const part of parts){let textContent=null;if("text"in part&&typeof part.text==="string"){textContent=part.text}else if("functionResponse"in part&&part.functionResponse){const output=part.functionResponse.response?.["output"]??part.functionResponse.response?.["content"]??"";textContent=typeof output==="string"?output:JSON.stringify(output)}else{textContent=JSON.stringify(part)}if(textContent!==null&&textContent.length>0){if(currentTextBlock===null){currentTextBlock={type:"text",text:textContent};blocks.push(currentTextBlock)}else{currentTextBlock.text+=textContent}}}return blocks}__name(partsToContentBlock,"partsToContentBlock");function checkResponsePartsForError(responseParts){if(!responseParts||responseParts.length===0){return void 0}for(const part of responseParts){if("functionResponse"in part&&part.functionResponse?.response&&typeof part.functionResponse.response==="object"&&"error"in part.functionResponse.response&&part.functionResponse.response["error"]){const error=part.functionResponse.response["error"];return typeof error==="string"?error:String(error)}}return void 0}__name(checkResponsePartsForError,"checkResponsePartsForError");function mcpAppFallbackText(display){if(!display||typeof display!=="object"||!("type"in display)||display.type!=="mcp_app"||!("fallbackText"in display)||typeof display.fallbackText!=="string"){return void 0}const text=display.fallbackText.trim();return text.length>0?display.fallbackText:void 0}__name(mcpAppFallbackText,"mcpAppFallbackText");function toolResultContent(response){if(response.visionBridgeNotice){const content=toolResultContent({...response,visionBridgeNotice:void 0});return content?`${response.visionBridgeNotice}
5
5
  ${content}`:response.visionBridgeNotice}if(isVisionBridgeNoticeDisplay(response.resultDisplay)){const notice=formatVisionBridgeNoticeDisplay(response.resultDisplay);if(response.error){return`${notice}
6
6
  ${response.error.message}`}const responsePartsError2=checkResponsePartsForError(response.responseParts);if(responsePartsError2){return`${notice}
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{HOSTNAME_RE,isOwnerRepo,normalizeGhHostForUrl,normalizeSegment,shellQuotePath}from"./chunk-F2L3WXJO.js";import{GIT_TIMEOUT_MS,git,gitOpt,gitProbe,gitRaw,redirectedAncestor,refExists,releaseWorktree,repoRoot,sanitizedGitEnv}from"./chunk-RRMTSVGU.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{atomicWriteFileSync}from"./chunk-2GF3E5MI.js";import{writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stripVTControlCharacters}from"node:util";var ROUND_COMMANDS=new Set(["sync","snapshot","ci-log","push","reply","rerun"]);function nextStep(command,code){switch(code){case"busy":case"partial":return"retry";case"pr_closed":return command==="prepare"?"report":"stop";case"watched_elsewhere":if(command==="prepare")return"take_over";return ROUND_COMMANDS.has(command)?"end_task":"report";case"not_prepared":case"watch_stopped":case"task_replaced":return ROUND_COMMANDS.has(command)?"end_task":"report";case"worktree_dirty":if(command==="sync")return"discard";return command==="push"?"needs_human":"report";case"no_failed_job":return"rerun";case"no_background_fix":return"foreground";case"rerun_failed":case"push_failed":return"needs_human";case"plan_invalid":return"fix_plan";case"fix_in_flight":return"report";case"failed":if(command==="push"||command==="rerun")return"needs_human";return command==="reply"?"retry":"report";default:{const unknown=code;return unknown}}}__name(nextStep,"nextStep");var AutofixPrRefusal=class extends Error{constructor(code,message){super(message);this.code=code;this.name="AutofixPrRefusal"}static{__name(this,"AutofixPrRefusal")}};var MAX_REFUSAL_MESSAGE=8e3;var UNSAFE=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069\ufeff]/g;function refusalOf(command,error){const code=error instanceof AutofixPrRefusal?error.code:"failed";const whole=stripVTControlCharacters(error instanceof Error?error.message:String(error??"unknown error")).replace(UNSAFE,"");let message=whole;for(let half=MAX_REFUSAL_MESSAGE/2;JSON.stringify(message).length>MAX_REFUSAL_MESSAGE&&half>=1;half=Math.floor(half/2)){message=`${whole.slice(0,half)} \u2026 ${whole.slice(-half)}`}return{refused:code,next:nextStep(command,code),message}}__name(refusalOf,"refusalOf");function withRefusals(command){const name=String(command.command).split(" ")[0];return{...command,handler:__name(async argv=>{try{await command.handler(argv)}catch(error){if(!(error instanceof AutofixPrRefusal)&&error instanceof Error){const frames=(error.stack??"").split("\n").filter(line=>/^\s+at /.test(line));if(frames.length>0)writeStderrLine(frames.join("\n"))}writeStderrLine(JSON.stringify(refusalOf(name,error)));process.exitCode=1}},"handler")}}__name(withRefusals,"withRefusals");init_esbuild_shims();import{lstatSync as lstatSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2}from"node:fs";import{dirname as dirname2,join as join2}from"node:path";init_esbuild_shims();import{createHash,randomUUID}from"node:crypto";import{homedir}from"node:os";import{closeSync,constants,existsSync,fstatSync,linkSync,lstatSync,mkdirSync,openSync,readFileSync,readlinkSync,realpathSync,renameSync,rmSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,resolve}from"node:path";var REPLY_MARKER="<!-- qwen-autofix-pr:v1 -->";var WATCH_INTERVALS=[1,2,5,10,15,30,60];var MAX_NEEDS_HUMAN=20;var MAX_INSTRUCTIONS_CHARS=2e3;function rerunFloors(state){return[...state.rerunChecks??[],...(state.heldChecks??[]).map(entry=>entry.replace(/^\d+:/,""))]}__name(rerunFloors,"rerunFloors");var MAX_PUSHES=10;var MAX_CHECK_FIX_PUSHES=3;var MAX_FAILING_CHECKS=100;function withKnownHead(state,head){if(state.pushedShas.includes(head)||!state.failingChecks?.length){return{...state,lastKnownHeadSha:head}}const lastPush=state.pushedShas.at(-1);return{...state,lastKnownHeadSha:head,failingChecks:state.failingChecks.map(record=>({identity:record.identity,check:record.check,head:record.head,pushes:0,...lastPush===void 0?{}:{lastPush}}))}}__name(withKnownHead,"withKnownHead");function checkAttemptKey(check,headSha,attempt){return`${check}@${headSha}@${attempt}`}__name(checkAttemptKey,"checkAttemptKey");function watchRoot(){if(process.env["QWEN_CODE_SERVE"]==="1"){return git("rev-parse","--show-toplevel")}return repoRoot()}__name(watchRoot,"watchRoot");function parseWorktreePaths(nulOutput){const paths=[];for(const field of nulOutput.split("\0")){if(field.startsWith("worktree ")){paths.push(field.slice("worktree ".length))}}return paths}__name(parseWorktreePaths,"parseWorktreePaths");function cloneWorktreeRoots(){const z=gitOpt("worktree","list","--porcelain","-z");if(z!==null)return parseWorktreePaths(z);return[repoRoot()]}__name(cloneWorktreeRoots,"cloneWorktreeRoots");function findWatchRoot(prNumber){assertPositiveInteger(prNumber,"PR number");let found=null;for(const root of vouchedScanRoots(cloneWorktreeRoots())){const paths=autofixPrPaths(root,prNumber);let hasState;try{hasState=isRegularFile(paths.statePath)}catch{continue}if(!hasState)continue;if(found===null||!existsSync(autofixPrPaths(found,prNumber).worktreePath)&&existsSync(paths.worktreePath)){found=root}}return found}__name(findWatchRoot,"findWatchRoot");function resolveWatchRoot(prNumber){return findWatchRoot(prNumber)??watchRoot()}__name(resolveWatchRoot,"resolveWatchRoot");function anchorStoreRoot(){return process.env["QWEN_AUTOFIX_ANCHOR_DIR"]??join(homedir(),".qwen","autofix-anchors")}__name(anchorStoreRoot,"anchorStoreRoot");function anchorPath(repository,prNumber,cloneRoot){assertPositiveInteger(prNumber,"PR number");const slug=[normalizeGhHostForUrl(repository.host).replace(/:/g,"@"),normalizeSegment(repository.owner),normalizeSegment(repository.repo)].join("+").replace(/[^a-z0-9._@+-]/g,"_");const cloneKey=createHash("sha256").update(resolve(cloneRoot)).digest("hex").slice(0,16);return join(anchorStoreRoot(),slug,`${cloneKey}-pr-${prNumber}.json`)}__name(anchorPath,"anchorPath");function writeAnchor(repository,prNumber,trustRoot){const path=anchorPath(repository,prNumber,trustRoot);mkdirSync(dirname(path),{recursive:true});const anchor={trustRoot,...repository};atomicWriteFileSync(path,`${JSON.stringify(anchor,null,2)}
3
+ import{HOSTNAME_RE,isOwnerRepo,normalizeGhHostForUrl,normalizeSegment,shellQuotePath}from"./chunk-F2L3WXJO.js";import{GIT_TIMEOUT_MS,git,gitOpt,gitProbe,gitRaw,redirectedAncestor,refExists,releaseWorktree,repoRoot,sanitizedGitEnv}from"./chunk-ZSHDQPAO.js";import{isWithinRoot}from"./chunk-IDXJIDME.js";import{atomicWriteFileSync}from"./chunk-2GF3E5MI.js";import{writeStderrLine,writeStdoutLine}from"./chunk-M4ECEHLX.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stripVTControlCharacters}from"node:util";var ROUND_COMMANDS=new Set(["sync","snapshot","ci-log","push","reply","rerun"]);function nextStep(command,code){switch(code){case"busy":case"partial":return"retry";case"pr_closed":return command==="prepare"?"report":"stop";case"watched_elsewhere":if(command==="prepare")return"take_over";return ROUND_COMMANDS.has(command)?"end_task":"report";case"not_prepared":case"watch_stopped":case"task_replaced":return ROUND_COMMANDS.has(command)?"end_task":"report";case"worktree_dirty":if(command==="sync")return"discard";return command==="push"?"needs_human":"report";case"no_failed_job":return"rerun";case"no_background_fix":return"foreground";case"rerun_failed":case"push_failed":return"needs_human";case"plan_invalid":return"fix_plan";case"fix_in_flight":return"report";case"failed":if(command==="push"||command==="rerun")return"needs_human";return command==="reply"?"retry":"report";default:{const unknown=code;return unknown}}}__name(nextStep,"nextStep");var AutofixPrRefusal=class extends Error{constructor(code,message){super(message);this.code=code;this.name="AutofixPrRefusal"}static{__name(this,"AutofixPrRefusal")}};var MAX_REFUSAL_MESSAGE=8e3;var UNSAFE=/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069\ufeff]/g;function refusalOf(command,error){const code=error instanceof AutofixPrRefusal?error.code:"failed";const whole=stripVTControlCharacters(error instanceof Error?error.message:String(error??"unknown error")).replace(UNSAFE,"");let message=whole;for(let half=MAX_REFUSAL_MESSAGE/2;JSON.stringify(message).length>MAX_REFUSAL_MESSAGE&&half>=1;half=Math.floor(half/2)){message=`${whole.slice(0,half)} \u2026 ${whole.slice(-half)}`}return{refused:code,next:nextStep(command,code),message}}__name(refusalOf,"refusalOf");function withRefusals(command){const name=String(command.command).split(" ")[0];return{...command,handler:__name(async argv=>{try{await command.handler(argv)}catch(error){if(!(error instanceof AutofixPrRefusal)&&error instanceof Error){const frames=(error.stack??"").split("\n").filter(line=>/^\s+at /.test(line));if(frames.length>0)writeStderrLine(frames.join("\n"))}writeStderrLine(JSON.stringify(refusalOf(name,error)));process.exitCode=1}},"handler")}}__name(withRefusals,"withRefusals");init_esbuild_shims();import{lstatSync as lstatSync2,readFileSync as readFileSync2,renameSync as renameSync2,rmSync as rmSync2}from"node:fs";import{dirname as dirname2,join as join2}from"node:path";init_esbuild_shims();import{createHash,randomUUID}from"node:crypto";import{homedir}from"node:os";import{closeSync,constants,existsSync,fstatSync,linkSync,lstatSync,mkdirSync,openSync,readFileSync,readlinkSync,realpathSync,renameSync,rmSync,statSync,unlinkSync,writeFileSync}from"node:fs";import{basename,dirname,isAbsolute,join,resolve}from"node:path";var REPLY_MARKER="<!-- qwen-autofix-pr:v1 -->";var WATCH_INTERVALS=[1,2,5,10,15,30,60];var MAX_NEEDS_HUMAN=20;var MAX_INSTRUCTIONS_CHARS=2e3;function rerunFloors(state){return[...state.rerunChecks??[],...(state.heldChecks??[]).map(entry=>entry.replace(/^\d+:/,""))]}__name(rerunFloors,"rerunFloors");var MAX_PUSHES=10;var MAX_CHECK_FIX_PUSHES=3;var MAX_FAILING_CHECKS=100;function withKnownHead(state,head){if(state.pushedShas.includes(head)||!state.failingChecks?.length){return{...state,lastKnownHeadSha:head}}const lastPush=state.pushedShas.at(-1);return{...state,lastKnownHeadSha:head,failingChecks:state.failingChecks.map(record=>({identity:record.identity,check:record.check,head:record.head,pushes:0,...lastPush===void 0?{}:{lastPush}}))}}__name(withKnownHead,"withKnownHead");function checkAttemptKey(check,headSha,attempt){return`${check}@${headSha}@${attempt}`}__name(checkAttemptKey,"checkAttemptKey");function watchRoot(){if(process.env["QWEN_CODE_SERVE"]==="1"){return git("rev-parse","--show-toplevel")}return repoRoot()}__name(watchRoot,"watchRoot");function parseWorktreePaths(nulOutput){const paths=[];for(const field of nulOutput.split("\0")){if(field.startsWith("worktree ")){paths.push(field.slice("worktree ".length))}}return paths}__name(parseWorktreePaths,"parseWorktreePaths");function cloneWorktreeRoots(){const z=gitOpt("worktree","list","--porcelain","-z");if(z!==null)return parseWorktreePaths(z);return[repoRoot()]}__name(cloneWorktreeRoots,"cloneWorktreeRoots");function findWatchRoot(prNumber){assertPositiveInteger(prNumber,"PR number");let found=null;for(const root of vouchedScanRoots(cloneWorktreeRoots())){const paths=autofixPrPaths(root,prNumber);let hasState;try{hasState=isRegularFile(paths.statePath)}catch{continue}if(!hasState)continue;if(found===null||!existsSync(autofixPrPaths(found,prNumber).worktreePath)&&existsSync(paths.worktreePath)){found=root}}return found}__name(findWatchRoot,"findWatchRoot");function resolveWatchRoot(prNumber){return findWatchRoot(prNumber)??watchRoot()}__name(resolveWatchRoot,"resolveWatchRoot");function anchorStoreRoot(){return process.env["QWEN_AUTOFIX_ANCHOR_DIR"]??join(homedir(),".qwen","autofix-anchors")}__name(anchorStoreRoot,"anchorStoreRoot");function anchorPath(repository,prNumber,cloneRoot){assertPositiveInteger(prNumber,"PR number");const slug=[normalizeGhHostForUrl(repository.host).replace(/:/g,"@"),normalizeSegment(repository.owner),normalizeSegment(repository.repo)].join("+").replace(/[^a-z0-9._@+-]/g,"_");const cloneKey=createHash("sha256").update(resolve(cloneRoot)).digest("hex").slice(0,16);return join(anchorStoreRoot(),slug,`${cloneKey}-pr-${prNumber}.json`)}__name(anchorPath,"anchorPath");function writeAnchor(repository,prNumber,trustRoot){const path=anchorPath(repository,prNumber,trustRoot);mkdirSync(dirname(path),{recursive:true});const anchor={trustRoot,...repository};atomicWriteFileSync(path,`${JSON.stringify(anchor,null,2)}
4
4
  `,NO_FOLLOW)}__name(writeAnchor,"writeAnchor");function readAnchor(repository,prNumber){const path=anchorPath(repository,prNumber,repoRoot());if(!isRegularFile(path))return null;try{const parsed=JSON.parse(readRegularFile(path)??"null");if(parsed&&typeof parsed.trustRoot==="string"&&typeof parsed.host==="string"&&typeof parsed.owner==="string"&&typeof parsed.repo==="string"){return parsed}return null}catch{return null}}__name(readAnchor,"readAnchor");function trustAnchor(state){const anchor=readAnchor(state,state.prNumber);if(!anchor){throw new Error(`PR #${state.prNumber} has no confirmed trust anchor; re-run \`qwen autofix-pr prepare ${state.prNumber}\` (or resume it) to confirm the clone before its worktree can be validated`)}return anchor.trustRoot}__name(trustAnchor,"trustAnchor");function vouchedScanRoots(roots){if(roots.length===0)return[];const main=roots[0];const notNested=roots.filter(r=>!roots.some(other=>other!==r&&isWithinRoot(r,join(other,".qwen","tmp"))));let genuineCommon;let genuineWorktrees;try{const dotGit=join(main,".git");genuineCommon=realpathSync(existsSync(dotGit)?dotGit:main);genuineWorktrees=realpathSync(join(genuineCommon,"worktrees"))}catch{return notNested.slice(0,1)}return notNested.filter(r=>r===main||vouchesForClone(r,genuineCommon,genuineWorktrees))}__name(vouchedScanRoots,"vouchedScanRoots");function vouchesForClone(root,genuineCommon,genuineWorktrees){const dotGit=join(root,".git");let st;try{st=lstatSync(dotGit)}catch{return false}if(st.isDirectory()){try{return realpathSync(dotGit)===genuineCommon}catch{return false}}if(!st.isFile())return false;let text;try{text=readFileSync(dotGit,"utf8")}catch{return false}if(!text.startsWith("gitdir: "))return false;const pointer=text.slice("gitdir: ".length).replace(/[\r\n]+$/,"");let entry;try{entry=realpathSync(isAbsolute(pointer)?pointer:join(root,pointer))}catch{return false}if(dirname(entry)!==genuineWorktrees)return false;let back;try{back=readFileSync(join(entry,"gitdir"),"utf8").replace(/[\r\n]+$/,"")}catch{return false}try{return realpathSync(isAbsolute(back)?back:join(entry,back))===realpathSync(dotGit)}catch{return false}}__name(vouchesForClone,"vouchesForClone");function assertPositiveInteger(value,what){if(!Number.isInteger(value)||value<1){throw new TypeError(`${what} must be a positive integer, got ${value}`)}}__name(assertPositiveInteger,"assertPositiveInteger");function statePaths(root,state){const paths=autofixPrPaths(root,state.prNumber);return state.inPlace?{...paths,worktreePath:state.worktreePath,branch:state.branch}:paths}__name(statePaths,"statePaths");function autofixPrPaths(root,prNumber){assertPositiveInteger(prNumber,"PR number");const tmp=join(root,".qwen","tmp");return{worktreePath:join(tmp,`autofix-pr-${prNumber}`),statePath:join(tmp,`autofix-pr-${prNumber}-state.json`),gatePath:join(tmp,`autofix-pr-${prNumber}-gate.json`),checkedPath:join(tmp,`autofix-pr-${prNumber}-gate.checked`),snapshotPath:join(tmp,`autofix-pr-${prNumber}-snapshot.json`),repliesPath:join(tmp,`autofix-pr-${prNumber}-replies.json`),lockPath:join(tmp,`autofix-pr-${prNumber}.lock`),instructionsPath:join(tmp,`autofix-pr-${prNumber}-instructions.txt`),fixPath:join(tmp,`autofix-pr-${prNumber}-fix.json`),branch:`qwen-autofix/pr-${prNumber}`,headRef:`refs/qwen-autofix/pr-${prNumber}/head`}}__name(autofixPrPaths,"autofixPrPaths");function isRegularFile(path){return lstatSync(path,{throwIfNoEntry:false})?.isFile()===true}__name(isRegularFile,"isRegularFile");function readRegularFile(path){let fd;try{fd=openSync(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0))}catch(err){if(err.code==="ENOENT")return null;throw err}try{if(!fstatSync(fd).isFile()){throw new Error(`${path} is not a regular file`)}return readFileSync(fd,"utf8")}finally{closeSync(fd)}}__name(readRegularFile,"readRegularFile");function readGateCursor(gatePath){if(lstatSync(gatePath,{throwIfNoEntry:false})===void 0){return null}if(!isRegularFile(gatePath)){throw new Error(`${gatePath} is not a regular file`)}const text=readRegularFile(gatePath);if(text===null)return null;const parsed=JSON.parse(text);if(parsed.version!==1){throw new Error(`unsupported autofix-pr gate cursor version in ${gatePath}: ${String(parsed.version)}`)}return{...parsed,reportedTruncated:parsed.reportedTruncated??[]}}__name(readGateCursor,"readGateCursor");function writeGateCursor(gatePath,cursor){atomicWriteFileSync(gatePath,`${JSON.stringify(cursor,null,2)}
5
5
  `,{noFollow:true})}__name(writeGateCursor,"writeGateCursor");function sameRepository(a,b){return normalizeGhHostForUrl(a.host)===normalizeGhHostForUrl(b.host)&&normalizeSegment(a.owner)===normalizeSegment(b.owner)&&normalizeSegment(a.repo)===normalizeSegment(b.repo)}__name(sameRepository,"sameRepository");var SHA_RE=/^[0-9a-f]{40,64}$/;function isBranchName(name){return!(name===""||name==="@"||name.startsWith("-")||name.endsWith("/")||name.endsWith(".")||[...name].some(char=>char.charCodeAt(0)<=32||char==="\x7F")||/[~^:?*[\\]/.test(name)||name.includes("..")||name.includes("@{")||name.includes("//")||name.split("/").some(part=>part.startsWith(".")||part.endsWith(".lock")))}__name(isBranchName,"isBranchName");var SHELL_SPECIAL=/[;&|$`<>()'"{}!#]/;function isCommandSafeName(name){return!SHELL_SPECIAL.test(name)}__name(isCommandSafeName,"isCommandSafeName");function stringList(value){return Array.isArray(value)?value.filter(item=>typeof item==="string"):[]}__name(stringList,"stringList");var isStringList=__name(value=>Array.isArray(value)&&value.every(item=>typeof item==="string"),"isStringList");var isRunList=__name(value=>Array.isArray(value)&&value.every(item=>Number.isInteger(item)),"isRunList");function isPendingPost(value){const post=value;return typeof post==="object"&&post!==null&&(post.where==="summary"||Number.isInteger(post.where))&&isStringList(post.handled)&&typeof post.bodyHash==="string"&&typeof post.sha==="string"&&(post.needsHuman===void 0||isStringList(post.needsHuman))}__name(isPendingPost,"isPendingPost");function stateDefect(state){const word=__name(value=>typeof value==="string"&&value!==""&&!value.startsWith("-"),"word");if(!word(state.remote)||!isBranchName(state.remote)||!isCommandSafeName(state.remote)){return"remote"}if(!word(state.pushTarget))return"pushTarget";if(!word(state.headRefName)||!isBranchName(state.headRefName)){return"headRefName"}if(!word(state.baseRefName)||!isBranchName(state.baseRefName)||!isCommandSafeName(state.baseRefName)){return"baseRefName"}if(!isOwnerRepo(`${state.owner}/${state.repo}`))return"owner/repo";if(typeof state.host!=="string"||!HOSTNAME_RE.test(state.host)){return"host"}if(!Number.isInteger(state.prNumber)||state.prNumber<1){return"prNumber"}if(typeof state.lastKnownHeadSha!=="string"||!SHA_RE.test(state.lastKnownHeadSha)){return"lastKnownHeadSha"}if(!Array.isArray(state.pushedShas)||!state.pushedShas.every(sha=>typeof sha==="string"&&SHA_RE.test(sha))){return"pushedShas"}if(!isStringList(state.handledCommentIds))return"handledCommentIds";if(!isStringList(state.postedCommentIds))return"postedCommentIds";if(state.handledChecks!==void 0&&!isStringList(state.handledChecks)){return"handledChecks"}if(state.rerunChecks!==void 0&&!isStringList(state.rerunChecks)){return"rerunChecks"}if(state.deferredRuns!==void 0&&!isRunList(state.deferredRuns)){return"deferredRuns"}if(state.heldChecks!==void 0&&!isStringList(state.heldChecks)){return"heldChecks"}if(state.pendingPosts!==void 0&&!(Array.isArray(state.pendingPosts)&&state.pendingPosts.every(isPendingPost))){return"pendingPosts"}if(state.pushCount!==void 0&&!(Number.isInteger(state.pushCount)&&state.pushCount>=0)){return"pushCount"}if(state.watch!==void 0&&!isWatchOptions(state.watch)){return"watch"}if(state.needsHuman!==void 0&&!(Array.isArray(state.needsHuman)&&state.needsHuman.every(isNeedsHumanItem))){return"needsHuman"}if(state.reportedNeedsHuman!==void 0&&!(typeof state.reportedNeedsHuman==="object"&&state.reportedNeedsHuman!==null&&typeof state.reportedNeedsHuman.sha==="string"&&SHA_RE.test(state.reportedNeedsHuman.sha)&&isStringList(state.reportedNeedsHuman.texts))){return"reportedNeedsHuman"}if(state.preparedAt!==void 0&&typeof state.preparedAt!=="string"){return"preparedAt"}if(state.ended!==void 0&&!(typeof state.ended==="object"&&state.ended!==null&&typeof state.ended.at==="string"&&typeof state.ended.reason==="string")){return"ended"}if(state.failingChecks!==void 0&&!(Array.isArray(state.failingChecks)&&state.failingChecks.every(isFailingCheck))){return"failingChecks"}return null}__name(stateDefect,"stateDefect");function isFailingCheck(value){const check=value;return typeof check==="object"&&check!==null&&typeof check.identity==="string"&&typeof check.check==="string"&&typeof check.head==="string"&&Number.isInteger(check.pushes)&&check.pushes>=0&&SHA_RE.test(check.head)&&(check.lastPush===void 0||SHA_RE.test(check.lastPush))&&(check.unanswered===void 0||Array.isArray(check.unanswered)&&check.unanswered.every(entry=>typeof entry==="object"&&entry!==null&&typeof entry.sha==="string"&&SHA_RE.test(entry.sha)&&Number.isInteger(entry.pushes)&&entry.pushes>=0))}__name(isFailingCheck,"isFailingCheck");function isWatchOptions(value){const watch=value;return typeof watch==="object"&&watch!==null&&WATCH_INTERVALS.includes(watch.every)&&typeof watch.reply==="boolean"&&typeof watch.instructions==="string"&&watch.instructions.length<=MAX_INSTRUCTIONS_CHARS&&!/[\p{Cc}\p{Cf}\u2028\u2029]/u.test(watch.instructions)&&(watch.task===void 0||/^[0-9a-f]{12}$/.test(watch.task))}__name(isWatchOptions,"isWatchOptions");function isNeedsHumanItem(value){const item=value;return typeof item==="object"&&item!==null&&typeof item.sha==="string"&&typeof item.at==="string"&&typeof item.text==="string"}__name(isNeedsHumanItem,"isNeedsHumanItem");function readState(statePath){const entry=lstatSync(statePath,{throwIfNoEntry:false});if(entry===void 0)return null;if(!entry.isFile()){throw new Error(`${statePath} is not a regular file; \`qwen autofix-pr cleanup <pr> --force\` discards it.`)}let text;try{text=readRegularFile(statePath)}catch{throw new Error(`${statePath} is not a regular file; \`qwen autofix-pr cleanup <pr> --force\` discards it.`)}if(text===null)return null;const parsed=JSON.parse(text);if(parsed.version!==1){throw new Error(`unsupported autofix-pr state version in ${statePath}: ${String(parsed.version)}`)}const defect=stateDefect(parsed);if(defect){throw new Error(`${statePath} has an invalid ${defect}; run \`qwen autofix-pr cleanup ${String(parsed.prNumber)} --force\` and prepare the watch again.`)}const{watch,ended,needsHuman,reportedNeedsHuman,failingChecks}=parsed;return{...parsed,...watch?{watch:{every:watch.every,reply:watch.reply,instructions:watch.instructions,...watch.task!==void 0?{task:watch.task}:{}}}:{},...ended?{ended:{at:ended.at,reason:ended.reason}}:{},...needsHuman?{needsHuman:needsHuman.map(({sha,at,text:text2})=>({sha,at,text:text2}))}:{},...reportedNeedsHuman?{reportedNeedsHuman:{sha:reportedNeedsHuman.sha,texts:[...reportedNeedsHuman.texts]}}:{},...failingChecks?{failingChecks:failingChecks.map(({identity,check,head,pushes,lastPush,unanswered})=>({identity,check,head,pushes,...lastPush===void 0?{}:{lastPush},...unanswered===void 0?{}:{unanswered:unanswered.map(({sha,pushes:pushes2})=>({sha,pushes:pushes2}))}}))}:{}}}__name(readState,"readState");var NO_FOLLOW={noFollow:true};function writeState(statePath,state){atomicWriteFileSync(statePath,`${JSON.stringify(state,null,2)}
6
6
  `,NO_FOLLOW)}__name(writeState,"writeState");function historyPath(paths,repository){const slug=[normalizeGhHostForUrl(repository.host).replace(/:/g,"@"),normalizeSegment(repository.owner),normalizeSegment(repository.repo)].join("+").replace(/[^a-z0-9._@+-]/g,"_");return join(dirname(paths.statePath),`${historyPrefix(paths)}${slug}.history.json`)}__name(historyPath,"historyPath");function historyPrefix(paths){return basename(paths.statePath).replace(/-state\.json$/,"-history-")}__name(historyPrefix,"historyPrefix");function readHistory(path){if(lstatSync(path,{throwIfNoEntry:false})===void 0)return null;if(!isRegularFile(path))throw new Error(`${path} is not a regular file`);const parsed=JSON.parse(readFileSync(path,"utf8"));if(parsed.version!==1){throw new Error(`unsupported autofix-pr history version in ${path}: ${String(parsed.version)}`)}return{...parsed,handledCommentIds:stringList(parsed.handledCommentIds),postedCommentIds:stringList(parsed.postedCommentIds),handledChecks:stringList(parsed.handledChecks),rerunChecks:stringList(parsed.rerunChecks),handledConflictSha:typeof parsed.handledConflictSha==="string"&&SHA_RE.test(parsed.handledConflictSha)?parsed.handledConflictSha:null,pendingPosts:Array.isArray(parsed.pendingPosts)?parsed.pendingPosts.filter(isPendingPost):[],deferredRuns:Array.isArray(parsed.deferredRuns)?parsed.deferredRuns.filter(run=>Number.isInteger(run)):[],heldChecks:stringList(parsed.heldChecks)}}__name(readHistory,"readHistory");function keepHistory(paths,state){const path=historyPath(paths,state);let earlier=null;try{earlier=readHistory(path)}catch{}if(earlier&&!sameRepository(earlier,state))earlier=null;const union=__name((a,b)=>[...new Set([...stringList(a),...stringList(b)])],"union");const history={version:1,host:state.host,owner:state.owner,repo:state.repo,prNumber:state.prNumber,handledCommentIds:union(earlier?.handledCommentIds,state.handledCommentIds),postedCommentIds:union(earlier?.postedCommentIds,state.postedCommentIds),handledChecks:union(earlier?.handledChecks,state.handledChecks),rerunChecks:union(earlier?.rerunChecks,state.rerunChecks),handledConflictSha:state.handledConflictSha??earlier?.handledConflictSha??null,pendingPosts:state.pendingPosts??earlier?.pendingPosts??[],deferredRuns:state.deferredRuns??earlier?.deferredRuns??[],heldChecks:state.heldChecks??earlier?.heldChecks??[]};const entry=lstatSync(path,{throwIfNoEntry:false});if(entry&&!entry.isFile()&&!entry.isSymbolicLink()){rmSync(path,{recursive:true,force:true})}atomicWriteFileSync(path,`${JSON.stringify(history,null,2)}
@@ -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-24PHAWM3.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,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{DashScopeOpenAICompatibleProvider}from"./chunk-W2ZVZ6LS.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var QWEN_OAUTH_PLACEHOLDER_API_KEY="QWEN_OAUTH_DYNAMIC_TOKEN";var ENV_VAR_NAME_PATTERN=/^[A-Za-z_][A-Za-z0-9_]*$/;var OmniUploadConfigError=class extends Error{static{__name(this,"OmniUploadConfigError")}constructor(message){super(message);this.name="OmniUploadConfigError"}};function normalizeDedicatedOmniUploadConfig(raw,env=process.env){const configured=raw.baseUrl!==void 0||raw.apiKeyEnv!==void 0||raw.model!==void 0;if(!configured)return void 0;const baseUrl=raw.baseUrl?.trim();const apiKeyEnv=raw.apiKeyEnv?.trim();const model=raw.model?.trim();if(!baseUrl||!apiKeyEnv||!model){throw new OmniUploadConfigError("omni.delivery.upload.baseUrl, apiKeyEnv, and model must all be set when a dedicated upload channel is configured.")}if(!ENV_VAR_NAME_PATTERN.test(apiKeyEnv)){throw new OmniUploadConfigError("omni.delivery.upload.apiKeyEnv must be a valid environment variable name.")}if(!DashScopeOpenAICompatibleProvider.isDashScopeProvider({authType:"openai",baseUrl})){throw new OmniUploadConfigError("omni.delivery.upload.baseUrl must be a DashScope-compatible endpoint.")}const apiKey=env[apiKeyEnv]?.trim();if(!apiKey){throw new OmniUploadConfigError(`omni.delivery.upload.apiKeyEnv names ${apiKeyEnv}, but that environment variable is not set or is empty.`)}return{baseUrl,apiKey,model}}__name(normalizeDedicatedOmniUploadConfig,"normalizeDedicatedOmniUploadConfig");function resolveLegacyOmniUploadConfig(contentGeneratorConfig,model){if(!contentGeneratorConfig||contentGeneratorConfig.authType==="qwen-oauth"||!contentGeneratorConfig.apiKey||contentGeneratorConfig.apiKey===QWEN_OAUTH_PLACEHOLDER_API_KEY||!contentGeneratorConfig.baseUrl||!model||!DashScopeOpenAICompatibleProvider.isDashScopeProvider(contentGeneratorConfig)){return void 0}return{baseUrl:contentGeneratorConfig.baseUrl,apiKey:contentGeneratorConfig.apiKey,model}}__name(resolveLegacyOmniUploadConfig,"resolveLegacyOmniUploadConfig");function getEffectiveOmniUploadConfig(config){const dedicated=config.getOmniUploadConfig?.();if(dedicated)return dedicated;return resolveLegacyOmniUploadConfig(config.getContentGeneratorConfig?.(),config.getModel?.())}__name(getEffectiveOmniUploadConfig,"getEffectiveOmniUploadConfig");function requireEffectiveOmniUploadConfig(config){const upload=getEffectiveOmniUploadConfig(config);if(!upload){throw new OmniUploadConfigError("Omni upload is not configured. Set all of omni.delivery.upload.baseUrl, apiKeyEnv, and model, or use a static DashScope inference configuration.")}return upload}__name(requireEffectiveOmniUploadConfig,"requireEffectiveOmniUploadConfig");export{OmniUploadConfigError,normalizeDedicatedOmniUploadConfig,getEffectiveOmniUploadConfig,requireEffectiveOmniUploadConfig};
3
+ import{DashScopeOpenAICompatibleProvider}from"./chunk-FSLDNLNU.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var QWEN_OAUTH_PLACEHOLDER_API_KEY="QWEN_OAUTH_DYNAMIC_TOKEN";var ENV_VAR_NAME_PATTERN=/^[A-Za-z_][A-Za-z0-9_]*$/;var OmniUploadConfigError=class extends Error{static{__name(this,"OmniUploadConfigError")}constructor(message){super(message);this.name="OmniUploadConfigError"}};function normalizeDedicatedOmniUploadConfig(raw,env=process.env){const configured=raw.baseUrl!==void 0||raw.apiKeyEnv!==void 0||raw.model!==void 0;if(!configured)return void 0;const baseUrl=raw.baseUrl?.trim();const apiKeyEnv=raw.apiKeyEnv?.trim();const model=raw.model?.trim();if(!baseUrl||!apiKeyEnv||!model){throw new OmniUploadConfigError("omni.delivery.upload.baseUrl, apiKeyEnv, and model must all be set when a dedicated upload channel is configured.")}if(!ENV_VAR_NAME_PATTERN.test(apiKeyEnv)){throw new OmniUploadConfigError("omni.delivery.upload.apiKeyEnv must be a valid environment variable name.")}if(!DashScopeOpenAICompatibleProvider.isDashScopeProvider({authType:"openai",baseUrl})){throw new OmniUploadConfigError("omni.delivery.upload.baseUrl must be a DashScope-compatible endpoint.")}const apiKey=env[apiKeyEnv]?.trim();if(!apiKey){throw new OmniUploadConfigError(`omni.delivery.upload.apiKeyEnv names ${apiKeyEnv}, but that environment variable is not set or is empty.`)}return{baseUrl,apiKey,model}}__name(normalizeDedicatedOmniUploadConfig,"normalizeDedicatedOmniUploadConfig");function resolveLegacyOmniUploadConfig(contentGeneratorConfig,model){if(!contentGeneratorConfig||contentGeneratorConfig.authType==="qwen-oauth"||!contentGeneratorConfig.apiKey||contentGeneratorConfig.apiKey===QWEN_OAUTH_PLACEHOLDER_API_KEY||!contentGeneratorConfig.baseUrl||!model||!DashScopeOpenAICompatibleProvider.isDashScopeProvider(contentGeneratorConfig)){return void 0}return{baseUrl:contentGeneratorConfig.baseUrl,apiKey:contentGeneratorConfig.apiKey,model}}__name(resolveLegacyOmniUploadConfig,"resolveLegacyOmniUploadConfig");function getEffectiveOmniUploadConfig(config){const dedicated=config.getOmniUploadConfig?.();if(dedicated)return dedicated;return resolveLegacyOmniUploadConfig(config.getContentGeneratorConfig?.(),config.getModel?.())}__name(getEffectiveOmniUploadConfig,"getEffectiveOmniUploadConfig");function requireEffectiveOmniUploadConfig(config){const upload=getEffectiveOmniUploadConfig(config);if(!upload){throw new OmniUploadConfigError("Omni upload is not configured. Set all of omni.delivery.upload.baseUrl, apiKeyEnv, and model, or use a static DashScope inference configuration.")}return upload}__name(requireEffectiveOmniUploadConfig,"requireEffectiveOmniUploadConfig");export{OmniUploadConfigError,normalizeDedicatedOmniUploadConfig,getEffectiveOmniUploadConfig,requireEffectiveOmniUploadConfig};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{appEvents}from"./chunk-MMGNOY3U.js";import{assembleMcpServers,getPendingGatedMcpServers,getPromptableMcpServers}from"./chunk-SHKSVOTG.js";import{getMCPServerStatus}from"./chunk-MJEL7DIE.js";import{require_fast_deep_equal}from"./chunk-7LLG2W7I.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_fast_deep_equal=__toESM(require_fast_deep_equal(),1);var debugLogger=createDebugLogger("MCP_HOT_RELOAD");var modelProvidersDebugLogger=createDebugLogger("MODEL_PROVIDERS_HOT_RELOAD");function mcpServersEqual(a,b){return(0,import_fast_deep_equal.default)(a??{},b??{})}__name(mcpServersEqual,"mcpServersEqual");function mcpGatingEqual(a,b){const norm=__name(xs=>[...xs??[]].sort(),"norm");const allowedEqual=a.allowed===void 0===(b.allowed===void 0)&&(0,import_fast_deep_equal.default)(norm(a.allowed),norm(b.allowed));return(0,import_fast_deep_equal.default)(norm(a.excluded),norm(b.excluded))&&allowedEqual&&(0,import_fast_deep_equal.default)(norm(a.pending),norm(b.pending))}__name(mcpGatingEqual,"mcpGatingEqual");function recomputeMcpGating(settings,assembled,cwd,bootAllowed,isYolo){const settingsAllowed=settings.merged.mcp?.allowed?.filter(Boolean);const excluded=settings.merged.mcp?.excluded?.filter(Boolean);let allowed=settingsAllowed;if(bootAllowed){allowed=settingsAllowed?settingsAllowed.filter(n=>bootAllowed.includes(n)):[...bootAllowed]}return{allowed,excluded:excluded&&excluded.length>0?excluded:void 0,pending:isYolo?void 0:getPendingGatedMcpServers(assembled,cwd)}}__name(recomputeMcpGating,"recomputeMcpGating");function registerMcpHotReload(watcher,settings,config,topTierMcpServers){debugLogger.debug("registered MCP hot-reload listener on SettingsWatcher");return watcher.addChangeListener(async events=>{debugLogger.debug(`settings change fired (${events.length} event(s)): ${events.map(e=>`${e.scope}:${e.changeType}`).join(", ")}`);const cwd=config.getTargetDir();const next=config.getBareMode()||config.isSafeMode()?{...topTierMcpServers}:assembleMcpServers(settings.merged.mcpServers,cwd,topTierMcpServers);const isYolo=config.getApprovalMode()==="yolo";const bootAllowed=config.getCliAllowedMcpServerNames();const nextGating=config.getBareMode()||config.isSafeMode()?{allowed:bootAllowed?[...bootAllowed]:void 0}:recomputeMcpGating(settings,next,cwd,bootAllowed,isYolo);const prevServers=config.getSettingsMcpServers();const prevGating=config.getMcpGating();debugLogger.debug(`assembled servers: prev=[${Object.keys(prevServers??{}).join(", ")}] next=[${Object.keys(next).join(", ")}]`);debugLogger.debug(`gating next: excluded=[${(nextGating.excluded??[]).join(", ")}] allowed=[${(nextGating.allowed??[]).join(", ")}] pending=[${(nextGating.pending??[]).join(", ")}]`);const serversChanged=!mcpServersEqual(prevServers,next);const gatingChanged=!mcpGatingEqual(prevGating,nextGating);if(!serversChanged&&!gatingChanged){debugLogger.debug("no MCP-relevant change (servers + gating unchanged) \u2014 skipping reconcile");return}debugLogger.debug(`MCP-relevant change detected (serversChanged=${serversChanged} gatingChanged=${gatingChanged}) \u2014 reconciling`);const promptable=getPromptableMcpServers(next,cwd);config.setExcludedMcpServers(nextGating.excluded??[]);config.setAllowedMcpServers(nextGating.allowed);config.setPendingMcpServers(nextGating.pending);try{await config.reinitializeMcpServers(next);const finalStatuses=Object.keys(next).map(name=>`${name}=${getMCPServerStatus(name)}`).join(", ");debugLogger.debug(`reinitializeMcpServers resolved; final statuses=[${finalStatuses}]`)}catch(err){debugLogger.error(`reinitializeMcpServers threw: ${err instanceof Error?err.stack??err.message:String(err)}`);appEvents.emit("log-error","Failed to reload MCP server settings; existing MCP state may be unchanged. Run with --debug for details.")}if(!isYolo&&promptable.length>0){debugLogger.debug(`gated servers awaiting approval \u2192 emitting ${"mcp-pending-approval-changed"}: [${promptable.join(", ")}]`);appEvents.emit("mcp-pending-approval-changed")}})}__name(registerMcpHotReload,"registerMcpHotReload");function registerModelProvidersHotReload(watcher,settings,config){modelProvidersDebugLogger.debug("registered modelProviders hot-reload listener on SettingsWatcher");let refreshAuthRetryPending=false;const reconcile=__name(async()=>{const next=settings.merged.modelProviders;const providersUnchanged=(0,import_fast_deep_equal.default)(config.getModelProvidersConfig()??{},next??{});if(providersUnchanged&&!refreshAuthRetryPending){return}if(!providersUnchanged){modelProvidersDebugLogger.debug("modelProviders changed \u2014 reloading model registry");try{config.reloadModelProvidersConfig(next)}catch(err){modelProvidersDebugLogger.error(`reloadModelProvidersConfig threw: ${err instanceof Error?err.stack??err.message:String(err)}`);return}}const authType=config.getAuthType();if(!authType){return}try{await config.refreshAuth(authType,true);refreshAuthRetryPending=false}catch(err){const alreadyPending=refreshAuthRetryPending;refreshAuthRetryPending=true;modelProvidersDebugLogger.error(`refreshAuth after modelProviders reload threw: ${err instanceof Error?err.stack??err.message:String(err)}`);if(!alreadyPending){appEvents.emit("log-error",`Model provider settings reloaded, but re-authenticating the active model failed: ${err instanceof Error?err.message:String(err)}. Select a model with /model or restart to apply the change.`)}}},"reconcile");void reconcile();return watcher.addChangeListener(reconcile)}__name(registerModelProvidersHotReload,"registerModelProvidersHotReload");export{recomputeMcpGating,registerMcpHotReload,registerModelProvidersHotReload};
3
+ import{appEvents}from"./chunk-DP7LJTG2.js";import{assembleMcpServers,getPendingGatedMcpServers,getPromptableMcpServers}from"./chunk-VO6SPDH4.js";import{getMCPServerStatus}from"./chunk-MJEL7DIE.js";import{require_fast_deep_equal}from"./chunk-7LLG2W7I.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_fast_deep_equal=__toESM(require_fast_deep_equal(),1);var debugLogger=createDebugLogger("MCP_HOT_RELOAD");var modelProvidersDebugLogger=createDebugLogger("MODEL_PROVIDERS_HOT_RELOAD");function mcpServersEqual(a,b){return(0,import_fast_deep_equal.default)(a??{},b??{})}__name(mcpServersEqual,"mcpServersEqual");function mcpGatingEqual(a,b){const norm=__name(xs=>[...xs??[]].sort(),"norm");const allowedEqual=a.allowed===void 0===(b.allowed===void 0)&&(0,import_fast_deep_equal.default)(norm(a.allowed),norm(b.allowed));return(0,import_fast_deep_equal.default)(norm(a.excluded),norm(b.excluded))&&allowedEqual&&(0,import_fast_deep_equal.default)(norm(a.pending),norm(b.pending))}__name(mcpGatingEqual,"mcpGatingEqual");function recomputeMcpGating(settings,assembled,cwd,bootAllowed,isYolo){const settingsAllowed=settings.merged.mcp?.allowed?.filter(Boolean);const excluded=settings.merged.mcp?.excluded?.filter(Boolean);let allowed=settingsAllowed;if(bootAllowed){allowed=settingsAllowed?settingsAllowed.filter(n=>bootAllowed.includes(n)):[...bootAllowed]}return{allowed,excluded:excluded&&excluded.length>0?excluded:void 0,pending:isYolo?void 0:getPendingGatedMcpServers(assembled,cwd)}}__name(recomputeMcpGating,"recomputeMcpGating");function registerMcpHotReload(watcher,settings,config,topTierMcpServers){debugLogger.debug("registered MCP hot-reload listener on SettingsWatcher");return watcher.addChangeListener(async events=>{debugLogger.debug(`settings change fired (${events.length} event(s)): ${events.map(e=>`${e.scope}:${e.changeType}`).join(", ")}`);const cwd=config.getTargetDir();const next=config.getBareMode()||config.isSafeMode()?{...topTierMcpServers}:assembleMcpServers(settings.merged.mcpServers,cwd,topTierMcpServers);const isYolo=config.getApprovalMode()==="yolo";const bootAllowed=config.getCliAllowedMcpServerNames();const nextGating=config.getBareMode()||config.isSafeMode()?{allowed:bootAllowed?[...bootAllowed]:void 0}:recomputeMcpGating(settings,next,cwd,bootAllowed,isYolo);const prevServers=config.getSettingsMcpServers();const prevGating=config.getMcpGating();debugLogger.debug(`assembled servers: prev=[${Object.keys(prevServers??{}).join(", ")}] next=[${Object.keys(next).join(", ")}]`);debugLogger.debug(`gating next: excluded=[${(nextGating.excluded??[]).join(", ")}] allowed=[${(nextGating.allowed??[]).join(", ")}] pending=[${(nextGating.pending??[]).join(", ")}]`);const serversChanged=!mcpServersEqual(prevServers,next);const gatingChanged=!mcpGatingEqual(prevGating,nextGating);if(!serversChanged&&!gatingChanged){debugLogger.debug("no MCP-relevant change (servers + gating unchanged) \u2014 skipping reconcile");return}debugLogger.debug(`MCP-relevant change detected (serversChanged=${serversChanged} gatingChanged=${gatingChanged}) \u2014 reconciling`);const promptable=getPromptableMcpServers(next,cwd);config.setExcludedMcpServers(nextGating.excluded??[]);config.setAllowedMcpServers(nextGating.allowed);config.setPendingMcpServers(nextGating.pending);try{await config.reinitializeMcpServers(next);const finalStatuses=Object.keys(next).map(name=>`${name}=${getMCPServerStatus(name)}`).join(", ");debugLogger.debug(`reinitializeMcpServers resolved; final statuses=[${finalStatuses}]`)}catch(err){debugLogger.error(`reinitializeMcpServers threw: ${err instanceof Error?err.stack??err.message:String(err)}`);appEvents.emit("log-error","Failed to reload MCP server settings; existing MCP state may be unchanged. Run with --debug for details.")}if(!isYolo&&promptable.length>0){debugLogger.debug(`gated servers awaiting approval \u2192 emitting ${"mcp-pending-approval-changed"}: [${promptable.join(", ")}]`);appEvents.emit("mcp-pending-approval-changed")}})}__name(registerMcpHotReload,"registerMcpHotReload");function registerModelProvidersHotReload(watcher,settings,config){modelProvidersDebugLogger.debug("registered modelProviders hot-reload listener on SettingsWatcher");let refreshAuthRetryPending=false;const reconcile=__name(async()=>{const next=settings.merged.modelProviders;const providersUnchanged=(0,import_fast_deep_equal.default)(config.getModelProvidersConfig()??{},next??{});if(providersUnchanged&&!refreshAuthRetryPending){return}if(!providersUnchanged){modelProvidersDebugLogger.debug("modelProviders changed \u2014 reloading model registry");try{config.reloadModelProvidersConfig(next)}catch(err){modelProvidersDebugLogger.error(`reloadModelProvidersConfig threw: ${err instanceof Error?err.stack??err.message:String(err)}`);return}}const authType=config.getAuthType();if(!authType){return}try{await config.refreshAuth(authType,true);refreshAuthRetryPending=false}catch(err){const alreadyPending=refreshAuthRetryPending;refreshAuthRetryPending=true;modelProvidersDebugLogger.error(`refreshAuth after modelProviders reload threw: ${err instanceof Error?err.stack??err.message:String(err)}`);if(!alreadyPending){appEvents.emit("log-error",`Model provider settings reloaded, but re-authenticating the active model failed: ${err instanceof Error?err.message:String(err)}. Select a model with /model or restart to apply the change.`)}}},"reconcile");void reconcile();return watcher.addChangeListener(reconcile)}__name(registerModelProvidersHotReload,"registerModelProvidersHotReload");export{recomputeMcpGating,registerMcpHotReload,registerModelProvidersHotReload};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen