@qwen-code/qwen-code 0.25.2-preview.1 → 0.25.2

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 (274) hide show
  1. package/chunks/{MaxSizedBox-CF4NN4Y7.js → MaxSizedBox-CGJP7S5S.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-Q23KTB6U.js → StandaloneSessionPicker-H6NONKPP.js} +1 -1
  3. package/chunks/{acp-subagent-executor-LXOLDTFY.js → acp-subagent-executor-7OCKCTA5.js} +1 -1
  4. package/chunks/{acpAgent-QRKZVQAG.js → acpAgent-VCKTBLFO.js} +3 -3
  5. package/chunks/{advisor-VZZJU7BR.js → advisor-UQJ45FLG.js} +1 -1
  6. package/chunks/{agent-LP66VBC4.js → agent-KMSCVRSG.js} +1 -1
  7. package/chunks/{agent-headless-W5P4KPX4.js → agent-headless-3FWQ5QNO.js} +1 -1
  8. package/chunks/{agent-host-client-OW4HBXRL.js → agent-host-client-PXIIFCCS.js} +1 -1
  9. package/chunks/{agent-host-connections-D7IC6WWL.js → agent-host-connections-QUYGQNJX.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-6I25Q3Y6.js → anthropicContentGenerator-MDETV5LU.js} +1 -1
  11. package/chunks/{batch-7E5KJ625.js → batch-RQO2HWFV.js} +1 -1
  12. package/chunks/{bridge-BITC2AVN.js → bridge-OA3GEU2I.js} +1 -1
  13. package/chunks/{channel-settings-store-VAVG6ONF.js → channel-settings-store-YN23NP2H.js} +1 -1
  14. package/chunks/{chunk-4NCTKE4Z.js → chunk-2PQ5ZRTI.js} +1 -1
  15. package/chunks/{chunk-OJHTHXBC.js → chunk-32UFT5HU.js} +1 -1
  16. package/chunks/{chunk-2HJZ3OYW.js → chunk-3C34EMBZ.js} +1 -1
  17. package/chunks/{chunk-UXFLNZNB.js → chunk-3FPPMGVC.js} +1 -1
  18. package/chunks/{chunk-74YXI5IJ.js → chunk-445NIH5T.js} +1 -1
  19. package/chunks/{chunk-MXXYBMBZ.js → chunk-45EKBDFD.js} +1 -1
  20. package/chunks/{chunk-JV5FCFG4.js → chunk-4WFWZWR3.js} +1 -1
  21. package/chunks/{chunk-AAOAX46J.js → chunk-56NX3ASC.js} +1 -1
  22. package/chunks/{chunk-IBS4PHD2.js → chunk-5FY6TL3Z.js} +1 -1
  23. package/chunks/{chunk-UGI3XPRM.js → chunk-5GJPVNHI.js} +1 -1
  24. package/chunks/{chunk-7BZGY7AH.js → chunk-5XAVUYY6.js} +6 -6
  25. package/chunks/{chunk-V3WNU4F5.js → chunk-655XEN5H.js} +1 -1
  26. package/chunks/{chunk-APX7ODYT.js → chunk-6PHAGUA6.js} +1 -1
  27. package/chunks/{chunk-CD6C4OHZ.js → chunk-7YX6LW5H.js} +1 -1
  28. package/chunks/{chunk-C2NFZSGI.js → chunk-AAVRYR5T.js} +1 -1
  29. package/chunks/{chunk-EO35BRIG.js → chunk-ANUAITTH.js} +1 -1
  30. package/chunks/{chunk-CNQ6AOFN.js → chunk-AZ5GFEKG.js} +1 -1
  31. package/chunks/{chunk-KAEW65QP.js → chunk-B5XDGUAK.js} +1 -1
  32. package/chunks/{chunk-X6QHNKUW.js → chunk-BCNBZOGV.js} +1 -1
  33. package/chunks/{chunk-W5DIWPQB.js → chunk-BDXWLZJD.js} +1 -1
  34. package/chunks/{chunk-ZASVUARY.js → chunk-BPX4A433.js} +1 -1
  35. package/chunks/{chunk-CDSI44GJ.js → chunk-BUI6W6CU.js} +1 -1
  36. package/chunks/{chunk-ZEYCGUHI.js → chunk-BVARURDD.js} +1 -1
  37. package/chunks/{chunk-PZ5UPKIG.js → chunk-BW5CHWEJ.js} +2 -2
  38. package/chunks/{chunk-7TUP75C2.js → chunk-C4DSH4A3.js} +1 -1
  39. package/chunks/{chunk-R4KMBENY.js → chunk-CCBWBPJL.js} +1 -1
  40. package/chunks/{chunk-TU6DWKVI.js → chunk-CKJ3OUIV.js} +2 -2
  41. package/chunks/{chunk-SG5P4CK4.js → chunk-CRZ7QRFB.js} +1 -1
  42. package/chunks/{chunk-UYFL7K4Z.js → chunk-CTEBIP2S.js} +1 -1
  43. package/chunks/{chunk-WSIDVWGO.js → chunk-DBOWUORN.js} +1 -1
  44. package/chunks/{chunk-NAHKSVYI.js → chunk-DPBXGGQX.js} +1 -1
  45. package/chunks/{chunk-BMOJDKDZ.js → chunk-DSSSLNXD.js} +3 -3
  46. package/chunks/{chunk-FP2RLPWJ.js → chunk-EKGFFEH4.js} +1 -1
  47. package/chunks/{chunk-L7W3J427.js → chunk-EMEQR2LX.js} +1 -1
  48. package/chunks/{chunk-YRYMLJAC.js → chunk-ENUYA7BO.js} +1 -1
  49. package/chunks/{chunk-4CWBH6LP.js → chunk-EORORGZC.js} +1 -1
  50. package/chunks/{chunk-RBH3BOVF.js → chunk-EUK64V6Z.js} +1 -1
  51. package/chunks/{chunk-AII4DN7M.js → chunk-FBV4LUUL.js} +1 -1
  52. package/chunks/{chunk-YVEPPENZ.js → chunk-FFLFTXO7.js} +1 -1
  53. package/chunks/{chunk-2HSFO66N.js → chunk-FHXH3GSI.js} +1 -1
  54. package/chunks/{chunk-RH6PMH32.js → chunk-FVBDVZD7.js} +1 -1
  55. package/chunks/{chunk-Y2HLDUZG.js → chunk-I2D2ZUKF.js} +1 -1
  56. package/chunks/{chunk-6PUZWUMQ.js → chunk-I3FZ733S.js} +1 -1
  57. package/chunks/{chunk-GG7RNHZW.js → chunk-IFAUFERF.js} +5 -5
  58. package/chunks/{chunk-JQ7BCB3L.js → chunk-IYFUH3JB.js} +1 -1
  59. package/chunks/{chunk-VAMQAYF3.js → chunk-JB5I5QAD.js} +1 -1
  60. package/chunks/{chunk-Z3UZTCKY.js → chunk-JD3QDS7D.js} +1 -1
  61. package/chunks/{chunk-TFVPY43T.js → chunk-JG2UNQOW.js} +1 -1
  62. package/chunks/{chunk-E4MRBL4O.js → chunk-JSXHTTFE.js} +1 -1
  63. package/chunks/{chunk-QTYA6TES.js → chunk-LJLS3MDJ.js} +1 -1
  64. package/chunks/{chunk-RZISIEQL.js → chunk-MEIW5WVJ.js} +1 -1
  65. package/chunks/{chunk-ZD4U3GR4.js → chunk-MGL36H3B.js} +1 -1
  66. package/chunks/{chunk-HXA3X4PB.js → chunk-MJUFVFH3.js} +1 -1
  67. package/chunks/{chunk-SYIDPXVT.js → chunk-MSR6LYHS.js} +1 -1
  68. package/chunks/{chunk-4MJ67O5W.js → chunk-MTXJRB7G.js} +2 -2
  69. package/chunks/{chunk-F5P3BWS7.js → chunk-MXFBSMIM.js} +1 -1
  70. package/chunks/{chunk-W6TNBCKX.js → chunk-MYHJ4WUH.js} +1 -1
  71. package/chunks/{chunk-CWU5NJOB.js → chunk-NHXKNS7F.js} +1 -1
  72. package/chunks/{chunk-6OIJIF6G.js → chunk-NT74NPQT.js} +1 -1
  73. package/chunks/{chunk-O47FCWNF.js → chunk-NWXW4UNC.js} +1 -1
  74. package/chunks/{chunk-JASL4RZR.js → chunk-O77LM4EW.js} +1 -1
  75. package/chunks/{chunk-ZDNTENP2.js → chunk-OB7T2MDO.js} +1 -1
  76. package/chunks/{chunk-L7WFW57T.js → chunk-PODFLAH7.js} +1 -1
  77. package/chunks/{chunk-R3ZMQ7WR.js → chunk-Q2G675WT.js} +1 -1
  78. package/chunks/{chunk-H3QROVUO.js → chunk-QT27SK62.js} +1 -1
  79. package/chunks/{chunk-UELAXFT7.js → chunk-QZPNBV4F.js} +1 -1
  80. package/chunks/{chunk-B3L4LODR.js → chunk-RV54BGL2.js} +1 -1
  81. package/chunks/{chunk-KLXL3FSI.js → chunk-SFETIBPP.js} +1 -1
  82. package/chunks/{chunk-F3YGAXZ5.js → chunk-SGKINIQB.js} +1 -1
  83. package/chunks/{chunk-MBPT3YYO.js → chunk-SHJNP7OV.js} +1 -1
  84. package/chunks/{chunk-U3YSYIQE.js → chunk-SPFRORFN.js} +1 -1
  85. package/chunks/{chunk-S3B4TZVJ.js → chunk-SPLINFM7.js} +1 -1
  86. package/chunks/{chunk-ORIS5AVH.js → chunk-SYO5FPHL.js} +1 -1
  87. package/chunks/{chunk-AGHGPOH6.js → chunk-TEE4MM5S.js} +1 -1
  88. package/chunks/{chunk-WHF3HYZI.js → chunk-TPZTO4K3.js} +1 -1
  89. package/chunks/{chunk-KJO757RN.js → chunk-UY2CSL5W.js} +1 -1
  90. package/chunks/{chunk-VCTZRPKP.js → chunk-W7QYXFWW.js} +1 -1
  91. package/chunks/{chunk-T3ECMT6I.js → chunk-WQOZJ6V7.js} +2 -2
  92. package/chunks/{chunk-INEI2ZW2.js → chunk-WZK7RC36.js} +1 -1
  93. package/chunks/{chunk-Y5JLH3SN.js → chunk-X22435IN.js} +4 -4
  94. package/chunks/{chunk-WHNAY3QQ.js → chunk-X2KF6AUQ.js} +1 -1
  95. package/chunks/{chunk-MUEIZGTI.js → chunk-YHPHQX6M.js} +1 -1
  96. package/chunks/{chunk-5OOO3YIH.js → chunk-YL7QMYOX.js} +1 -1
  97. package/chunks/{chunk-43E3XC2W.js → chunk-YQEOEO5V.js} +1 -1
  98. package/chunks/{chunk-624P32LD.js → chunk-YZ374XTK.js} +1 -1
  99. package/chunks/{codex-subagent-executor-2MPLWNLD.js → codex-subagent-executor-MC3QB2AN.js} +1 -1
  100. package/chunks/{config-utils-MJEEBLQW.js → config-utils-FYT7PUIC.js} +1 -1
  101. package/chunks/{contextCommand-BP566QVE.js → contextCommand-DXMSMSR7.js} +1 -1
  102. package/chunks/{core-runtime-BOAIFYAZ.js → core-runtime-ZLB6QZ3Z.js} +1 -1
  103. package/chunks/{create-sub-session-HJVK7AXV.js → create-sub-session-YUI3G5AF.js} +1 -1
  104. package/chunks/{daemon-git-worktree-guard-KA2Y6FHL.js → daemon-git-worktree-guard-5PYZMC6T.js} +1 -1
  105. package/chunks/{daemon-status-provider-JGR5JT2T.js → daemon-status-provider-GC567FVE.js} +1 -1
  106. package/chunks/{daemon-trust-policy-EP4DHXOW.js → daemon-trust-policy-LLD2UMPF.js} +1 -1
  107. package/chunks/{daemon-trust-policy-monitor-W3VZRKOK.js → daemon-trust-policy-monitor-MRMB2CRJ.js} +1 -1
  108. package/chunks/{deferred-core-runtime-Q3JH7XDL.js → deferred-core-runtime-4HLTINJ6.js} +1 -1
  109. package/chunks/{edit-S7DCBMAL.js → edit-CZ6FEXDU.js} +1 -1
  110. package/chunks/{enterPlanMode-UX7B6KWX.js → enterPlanMode-O3CJ3I2J.js} +1 -1
  111. package/chunks/{environment-ZBW6HDG3.js → environment-OJWH4FYL.js} +1 -1
  112. package/chunks/{errors-7ZRLUHEB.js → errors-NWKSQVL3.js} +1 -1
  113. package/chunks/{execution-tool-R244Q3GW.js → execution-tool-7UCADALN.js} +1 -1
  114. package/chunks/{execution-worker-JR44JTC4.js → execution-worker-LWHQMPBV.js} +1 -1
  115. package/chunks/{exitPlanMode-2PTTZXGO.js → exitPlanMode-JDM6ZZWI.js} +1 -1
  116. package/chunks/{fast-path-NQQ42XUR.js → fast-path-4WHPMNMD.js} +1 -1
  117. package/chunks/{glob-4JP6RQNK.js → glob-LAU4YJ6J.js} +1 -1
  118. package/chunks/{goal-tools-MO7NIH7B.js → goal-tools-AF2FQO3H.js} +1 -1
  119. package/chunks/{handleAutoUpdate-STUVMCIU.js → handleAutoUpdate-WBWK4775.js} +1 -1
  120. package/chunks/{i18n-UTIILRKE.js → i18n-O4Q2KHOA.js} +1 -1
  121. package/chunks/{initializer-YI2WT6LZ.js → initializer-2AH3EKBL.js} +1 -1
  122. package/chunks/{installationInfo-PW2JHHJV.js → installationInfo-77WYXG4W.js} +1 -1
  123. package/chunks/{list-SAOL2OZI.js → list-RAU3ZJQS.js} +1 -1
  124. package/chunks/{llm-LMY62H6Z.js → llm-MJMQ34KB.js} +4 -4
  125. package/chunks/{llm-content-generator-6RPOZ2YR.js → llm-content-generator-MJPR2TWC.js} +1 -1
  126. package/chunks/{loadedSettingsAdapter-RNXWDDE2.js → loadedSettingsAdapter-WRWWNGHZ.js} +1 -1
  127. package/chunks/{local-execution-environment-GIWY2LO6.js → local-execution-environment-VVJ7OYBT.js} +1 -1
  128. package/chunks/{loggingContentGenerator-AOKEDXK6.js → loggingContentGenerator-722BJL7T.js} +1 -1
  129. package/chunks/{manage-memory-WKPWLYDD.js → manage-memory-GN56UQHG.js} +1 -1
  130. package/chunks/{managed-npm-update-LFFWFATA.js → managed-npm-update-5VE662JS.js} +1 -1
  131. package/chunks/{managed-runtime-attestation-worker-IV6ZNIAK.js → managed-runtime-attestation-worker-ASGGZMFM.js} +1 -1
  132. package/chunks/{managed-runtime-session-worker-3NU4FOXD.js → managed-runtime-session-worker-YUSO7WFB.js} +1 -1
  133. package/chunks/{mcp-RDDGN4JK.js → mcp-6D236MEH.js} +1 -1
  134. package/chunks/{model-call-collection-JARTJD6S.js → model-call-collection-UAE2W6VV.js} +1 -1
  135. package/chunks/{model-configuration-7H6PEOLY.js → model-configuration-VHPSBCQI.js} +1 -1
  136. package/chunks/{modelConfigUtils-Q63ZZTXY.js → modelConfigUtils-XKDXYQRJ.js} +1 -1
  137. package/chunks/{monitor-HLO366TQ.js → monitor-JIKXBXDK.js} +1 -1
  138. package/chunks/{nonInteractiveCli-JO5EG6OK.js → nonInteractiveCli-IXTK5V4Q.js} +1 -1
  139. package/chunks/{nonInteractiveToolExecutor-T7AKBX25.js → nonInteractiveToolExecutor-3MSROJV5.js} +1 -1
  140. package/chunks/{notebook-edit-XKULPMG7.js → notebook-edit-VDWBIBMG.js} +1 -1
  141. package/chunks/{omni-H3GFC6KR.js → omni-MEUE65XC.js} +1 -1
  142. package/chunks/{openaiContentGenerator-RT4S6OYR.js → openaiContentGenerator-KNZTYVNK.js} +1 -1
  143. package/chunks/{openaiResponsesContentGenerator-JD4ZBCAL.js → openaiResponsesContentGenerator-G7GRJXES.js} +1 -1
  144. package/chunks/{pidfile-JXCPPGC6.js → pidfile-HMEKKPWO.js} +1 -1
  145. package/chunks/{processUtils-FF7LHGHW.js → processUtils-KHWNT3KU.js} +1 -1
  146. package/chunks/{prompt-terminal-ledger-VLIEJ5BB.js → prompt-terminal-ledger-EY72RU3D.js} +1 -1
  147. package/chunks/{qwenContentGenerator-6SGQI4ES.js → qwenContentGenerator-A7WREYLV.js} +1 -1
  148. package/chunks/{reactive-degrade-2UJPX4AU.js → reactive-degrade-O6WBGQ5X.js} +1 -1
  149. package/chunks/{read-file-27DWTM5N.js → read-file-A4MQWC6T.js} +1 -1
  150. package/chunks/{resumeHistoryUtils-KRF2LD7T.js → resumeHistoryUtils-KNUVMH5J.js} +1 -1
  151. package/chunks/{review-IPFFTVGV.js → review-OC76PLQ4.js} +1 -1
  152. package/chunks/{ripGrep-75QL35XD.js → ripGrep-JR6DHTIW.js} +1 -1
  153. package/chunks/{run-qwen-serve-WW74NSUL.js → run-qwen-serve-NFPGPJJ2.js} +2 -2
  154. package/chunks/{runtime-Z2NIOF6Y.js → runtime-BPHFAZOP.js} +1 -1
  155. package/chunks/{sandboxConfig-WMQAKX7Q.js → sandboxConfig-KXTV3QBG.js} +1 -1
  156. package/chunks/{scheduled-tasks-LMJJ5ZM7.js → scheduled-tasks-2GNFZH4N.js} +1 -1
  157. package/chunks/{scheduler-KHWWXW6H.js → scheduler-CKLZCETX.js} +1 -1
  158. package/chunks/{search-memory-WEO3M674.js → search-memory-ICNU2EJA.js} +1 -1
  159. package/chunks/{send-message-E2EVXDU4.js → send-message-T32PFXX5.js} +1 -1
  160. package/chunks/{serve-E7ZGE7PD.js → serve-O7XBFM36.js} +1 -1
  161. package/chunks/{server-SSHP5IO4.js → server-7H2EGX7C.js} +3 -3
  162. package/chunks/{session-UWUQU3NV.js → session-SO4TKKO3.js} +1 -1
  163. package/chunks/{session-attachments-root-I35OUD7P.js → session-attachments-root-QPBJB3Y2.js} +1 -1
  164. package/chunks/{session-execution-engine-selector-S7HXLYKG.js → session-execution-engine-selector-73JQ7AG6.js} +1 -1
  165. package/chunks/{session-pr-refresh-34FLQB2Z.js → session-pr-refresh-XPDBRBQV.js} +1 -1
  166. package/chunks/{sessionService-BBC2563F.js → sessionService-DDLWVLNC.js} +1 -1
  167. package/chunks/{settings-BXCTAYMU.js → settings-TUEKBNAX.js} +1 -1
  168. package/chunks/{shell-ORZNRZKX.js → shell-SXSN7UYK.js} +1 -1
  169. package/chunks/{skill-3MJ6V2VQ.js → skill-XAYT7HGV.js} +1 -1
  170. package/chunks/{skill-settings-A7TTYJGH.js → skill-settings-X3O75XUN.js} +1 -1
  171. package/chunks/{spawnChannel-UPHPUPIJ.js → spawnChannel-3523LPUW.js} +1 -1
  172. package/chunks/{standalone-update-GGHQ54QB.js → standalone-update-T7AUODLV.js} +1 -1
  173. package/chunks/{start-opentui-ui-O6WMWLGS.js → start-opentui-ui-IKBADQQS.js} +1 -1
  174. package/chunks/{startInteractiveUI-N3ZPR2FK.js → startInteractiveUI-PV2JETB4.js} +1 -1
  175. package/chunks/{team-create-EYLFAQVU.js → team-create-ZKTBFE7Z.js} +1 -1
  176. package/chunks/{team-plan-approval-2WFSX4XE.js → team-plan-approval-SCTAN2HM.js} +1 -1
  177. package/chunks/{terminal-image-renderer-A5HEJZTW.js → terminal-image-renderer-EDBYTK3B.js} +1 -1
  178. package/chunks/{theme-manager-TQHNJSKQ.js → theme-manager-ZLXHLO2Y.js} +1 -1
  179. package/chunks/{tool-call-UBLAA45C.js → tool-call-ULUE3W3P.js} +1 -1
  180. package/chunks/{tool-result-media-53AD3EHK.js → tool-result-media-VXS7QTX7.js} +1 -1
  181. package/chunks/{tool-search-D6PSBDDZ.js → tool-search-VWM6VCVU.js} +1 -1
  182. package/chunks/{total-session-admission-CUMMWSM2.js → total-session-admission-FZDBG232.js} +1 -1
  183. package/chunks/{trustedFolders-TERXKVJ6.js → trustedFolders-VIPEDZNB.js} +1 -1
  184. package/chunks/{update-relaunch-PXCI66U2.js → update-relaunch-N6TNUHQE.js} +1 -1
  185. package/chunks/{updateCheck-2P4ANPL7.js → updateCheck-367IR3FW.js} +1 -1
  186. package/chunks/{upload-config-G2WZG4DM.js → upload-config-5W4WTLML.js} +1 -1
  187. package/chunks/{useAutoAcceptIndicator-H7I7JP34.js → useAutoAcceptIndicator-SGT7EBCJ.js} +1 -1
  188. package/chunks/{validateNonInterActiveAuth-VLRV5LCK.js → validateNonInterActiveAuth-7WEBPZ4S.js} +1 -1
  189. package/chunks/{version-AOKDKXXZ.js → version-3OKRQ6LC.js} +1 -1
  190. package/chunks/{web-fetch-OUJS56AV.js → web-fetch-BV7BK5NT.js} +1 -1
  191. package/chunks/{web-search-3S4ZIGLP.js → web-search-DFQ74G7V.js} +1 -1
  192. package/chunks/{workflow-6W4WB4L5.js → workflow-EXSCHLQK.js} +1 -1
  193. package/chunks/{workspace-agents-7GB2RLY5.js → workspace-agents-HPOPFXKJ.js} +1 -1
  194. package/chunks/{workspace-providers-status-OMD57CUW.js → workspace-providers-status-UQCSR2PB.js} +1 -1
  195. package/chunks/{workspace-registration-store-WKLFVMQ2.js → workspace-registration-store-Q5U4WD5M.js} +1 -1
  196. package/chunks/{workspace-registry-6WJOPYIS.js → workspace-registry-I2O2LXTZ.js} +1 -1
  197. package/chunks/{workspace-runtime-coordinator-XG7G7DG3.js → workspace-runtime-coordinator-MVVDZYYX.js} +1 -1
  198. package/chunks/{workspace-service-YLX46RJM.js → workspace-service-CFJ2EUB7.js} +1 -1
  199. package/chunks/{workspace-skills-status-JZZR7QHN.js → workspace-skills-status-LLNIK3NS.js} +1 -1
  200. package/chunks/{workspace-trust-reconciler-AO3I5KYO.js → workspace-trust-reconciler-VLGJXLCZ.js} +1 -1
  201. package/chunks/{write-file-MGYLC32T.js → write-file-RG7HHIYP.js} +1 -1
  202. package/chunks/{zoom-image-TZ527ASZ.js → zoom-image-AKW6CA4K.js} +1 -1
  203. package/cli.js +2 -2
  204. package/execution-worker.js +1 -1
  205. package/export-transcript-document.js +1 -1
  206. package/package.json +3 -3
  207. package/web-shell/assets/{PierreFilePreview-Cq9imG0c.js → PierreFilePreview-Cij36lF-.js} +1 -1
  208. package/web-shell/assets/{SpreadsheetPreview-Blho0kkO.js → SpreadsheetPreview-kDlHrK21.js} +1 -1
  209. package/web-shell/assets/{WorkspaceFileBrowser-DjeX-ArR.js → WorkspaceFileBrowser-DBXW9l-s.js} +1 -1
  210. package/web-shell/assets/{abnfDiagram-VCTEODGH-mEfLgGao.js → abnfDiagram-VCTEODGH-DBrfOx4O.js} +1 -1
  211. package/web-shell/assets/{agents-route-Bg4_tLdL.js → agents-route-6E_3XRjk.js} +1 -1
  212. package/web-shell/assets/{arc-DEVpMJqB.js → arc-RwrvKU6y.js} +1 -1
  213. package/web-shell/assets/{architectureDiagram-5GKGNRK7-CGhqKvd1.js → architectureDiagram-5GKGNRK7-B2_hfNn6.js} +1 -1
  214. package/web-shell/assets/{blockDiagram-NRAW4CY4-DxpWdCdl.js → blockDiagram-NRAW4CY4-C755qTFO.js} +1 -1
  215. package/web-shell/assets/{c4Diagram-UCG6FXSJ-CE1W0_yu.js → c4Diagram-UCG6FXSJ-CARC2uHQ.js} +1 -1
  216. package/web-shell/assets/channel-U9JRrjem.js +1 -0
  217. package/web-shell/assets/{chunk-2Q5K7J3B-ibHTXjoH.js → chunk-2Q5K7J3B-BS1ldEp9.js} +1 -1
  218. package/web-shell/assets/{chunk-5VM5RSS4-BEZ2-gCE.js → chunk-5VM5RSS4-DckOEd3N.js} +1 -1
  219. package/web-shell/assets/{chunk-F27PBJKO-CKyPZ7Jh.js → chunk-F27PBJKO-fZstOLLL.js} +1 -1
  220. package/web-shell/assets/{chunk-G27WJ6UU-WHNRb7iQ.js → chunk-G27WJ6UU-Bf4QkrJ7.js} +1 -1
  221. package/web-shell/assets/{chunk-JWPE2WC7-Dm4G-fLP.js → chunk-JWPE2WC7-uBW51XO_.js} +1 -1
  222. package/web-shell/assets/{chunk-LCL6LL3I-BvTm39E-.js → chunk-LCL6LL3I-D2MYZdE_.js} +1 -1
  223. package/web-shell/assets/{chunk-POPQ4Y6H-C0zAbzIo.js → chunk-POPQ4Y6H-CzTHTST7.js} +1 -1
  224. package/web-shell/assets/{chunk-SVP7TREG-B36K-VPq.js → chunk-SVP7TREG-fL48tjL5.js} +1 -1
  225. package/web-shell/assets/{chunk-XXDRQBXY-D1opdtZ1.js → chunk-XXDRQBXY-R1jjDz-e.js} +1 -1
  226. package/web-shell/assets/classDiagram-DTDB5LWJ-r255RW6f.js +1 -0
  227. package/web-shell/assets/classDiagram-v2-JRS7N3AN-r255RW6f.js +1 -0
  228. package/web-shell/assets/{cose-bilkent-JH36ORCC-S_IO4ZW5.js → cose-bilkent-JH36ORCC-DTK6Alrt.js} +1 -1
  229. package/web-shell/assets/{cynefin-OW5HDTMX-CGUKfurr.js → cynefin-OW5HDTMX-C1JYDjN4.js} +1 -1
  230. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-BqUpO_VD.js → cynefinDiagram-5FMLGOSQ-C3bR18IM.js} +1 -1
  231. package/web-shell/assets/{dagre-3AP2YEHR-CiKqZpUi.js → dagre-3AP2YEHR-D4oUlW7g.js} +1 -1
  232. package/web-shell/assets/{diagram-S7CK7UJ4-B3CQED4o.js → diagram-S7CK7UJ4-m-a-vk_2.js} +1 -1
  233. package/web-shell/assets/{diagram-UQ7AKVKN-BewunX5H.js → diagram-UQ7AKVKN-CVGSVvpJ.js} +1 -1
  234. package/web-shell/assets/{diagram-VSXAHHWV-C5j1hiVn.js → diagram-VSXAHHWV-DcLovKfd.js} +1 -1
  235. package/web-shell/assets/{diagram-VX7I27RA-CWDIIA61.js → diagram-VX7I27RA-DAwY09qQ.js} +1 -1
  236. package/web-shell/assets/{diagram-Z3DM3KII-COa1V8UD.js → diagram-Z3DM3KII-D4BWV8Yb.js} +1 -1
  237. package/web-shell/assets/{ebnfDiagram-PWID7BFC-CP33EIO8.js → ebnfDiagram-PWID7BFC-AhqQLlAR.js} +1 -1
  238. package/web-shell/assets/{erDiagram-SSCWMZ5O-V2pL2JAp.js → erDiagram-SSCWMZ5O-DcIpsPuK.js} +1 -1
  239. package/web-shell/assets/{flowDiagram-A5DVABFB-CF-YQlR_.js → flowDiagram-A5DVABFB-Cdu3v56D.js} +1 -1
  240. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-TXUid-Q2.js → ganttDiagram-EL5Y4UJY-D8o98Muo.js} +1 -1
  241. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-QNcIYsgn.js → gitGraphDiagram-WWUBYQGX-fIAd56jC.js} +1 -1
  242. package/web-shell/assets/{index-CKa6aZMZ.js → index-CJmvuO8Q.js} +1 -1
  243. package/web-shell/assets/{index-N9F4X44H.js → index-DSh5Yfsf.js} +5 -5
  244. package/web-shell/assets/{infoDiagram-RXCK75RN-Dn1biwuc.js → infoDiagram-RXCK75RN-dPnP0Koe.js} +1 -1
  245. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-iBYO7WCt.js → ishikawaDiagram-5VMMS53U-f9Oq8YH7.js} +1 -1
  246. package/web-shell/assets/{journeyDiagram-EYS64GPL-D98LzO4k.js → journeyDiagram-EYS64GPL-CqwSlUQ1.js} +1 -1
  247. package/web-shell/assets/{kanban-definition-3QL26DDD-lQMIgDSM.js → kanban-definition-3QL26DDD-Bh_KTp2S.js} +1 -1
  248. package/web-shell/assets/{layout-BgOy6tFo.js → layout-0e-hGnuM.js} +1 -1
  249. package/web-shell/assets/{linear-En8RXsBs.js → linear-BtxWFISv.js} +1 -1
  250. package/web-shell/assets/{mermaid.core-BneKXyZr.js → mermaid.core-Dik4l-jM.js} +6 -6
  251. package/web-shell/assets/{mindmap-definition-FBJOCRG2-NkP_9BC4.js → mindmap-definition-FBJOCRG2-B7gext3e.js} +1 -1
  252. package/web-shell/assets/{pegDiagram-XKGWAZYB-B0ie-nkt.js → pegDiagram-XKGWAZYB-BfyKzGY0.js} +1 -1
  253. package/web-shell/assets/{pieDiagram-E7YTZNPT-Qa86cFZc.js → pieDiagram-E7YTZNPT-vfeVyHgh.js} +1 -1
  254. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-CkjUzR0e.js → quadrantDiagram-AXDQQJYC-DGAZmngq.js} +1 -1
  255. package/web-shell/assets/{railroadDiagram-O6MQD6OU-mN7KpgJG.js → railroadDiagram-O6MQD6OU-Dgxiy8W5.js} +1 -1
  256. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-Bmn2z6x2.js → requirementDiagram-EFPCY7ZU-D7TFokdR.js} +1 -1
  257. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CYWnwpoW.js → sankeyDiagram-P5KCCOFB-BZU_UYd-.js} +1 -1
  258. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-BFyWlR1P.js → sequenceDiagram-WJ2MYXX4-Bz94qtvq.js} +1 -1
  259. package/web-shell/assets/{sizeCapture-X5ZJPWSS-BwCPrn2w.js → sizeCapture-X5ZJPWSS-DVlzIShY.js} +1 -1
  260. package/web-shell/assets/{stateDiagram-HBIQ2CUA-oqL3E0Ws.js → stateDiagram-HBIQ2CUA-CE9Il33j.js} +1 -1
  261. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BVL1rIGD.js +1 -0
  262. package/web-shell/assets/{swimlanes-XN3QIQJK-C3FAVL8g.js → swimlanes-XN3QIQJK-Cr2CyF9L.js} +1 -1
  263. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-BeWJAUmf.js +8 -0
  264. package/web-shell/assets/{timeline-definition-24CTP7MA-BdwxFsPJ.js → timeline-definition-24CTP7MA-DWbRlUDe.js} +1 -1
  265. package/web-shell/assets/{vennDiagram-4TSXK5OY-j_G2AbSj.js → vennDiagram-4TSXK5OY-Bp5BiaRL.js} +1 -1
  266. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-Dy_fHHBq.js → wardleyDiagram-VM6X3IG4-DoQIUrT8.js} +1 -1
  267. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-CnLgG50x.js → xychartDiagram-S5SC5T6Z-BTO308Vv.js} +1 -1
  268. package/web-shell/index.html +1 -1
  269. package/web-shell/sw.js +1 -1
  270. package/web-shell/assets/channel-CHCXOu89.js +0 -1
  271. package/web-shell/assets/classDiagram-DTDB5LWJ-DXIqcod_.js +0 -1
  272. package/web-shell/assets/classDiagram-v2-JRS7N3AN-DXIqcod_.js +0 -1
  273. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-Cmho6gw2.js +0 -1
  274. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-D9Sfkn7b.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{ARTIFACT_TITLE_MAX_LENGTH,ARTIFACT_WORKSPACE_PATH_MAX_LENGTH,OFFICE_DOCUMENT_EXTENSIONS,hasControlCharacter,hasUnsafeDisplayPayload,pathHasSkippedDirectoryComponent,toCanonicalWorkspaceArtifactPath}from"./chunk-NZFR5IY7.js";import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-UELAXFT7.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-6GLM4FUL.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-GG7RNHZW.js";import{FileOperationEvent,getLanguageFromFilePath,logFileOperation}from"./chunk-KBPIYGHG.js";import{fileExists,getSpecificMimeType}from"./chunk-JU2HHQR5.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-37KFLBKZ.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-O5EKX7LG.js";import{ToolDisplayNames,ToolNames}from"./chunk-2UNFJQ2D.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import fs from"node:fs";import path from"node:path";var debugLogger=createDebugLogger("WRITE_FILE");var ARTIFACT_KIND_BY_EXTENSION=new Map([[".csv","file"],[".htm","html"],[".html","html"],[".ipynb","notebook"],[".jpeg","image"],[".jpg","image"],[".pdf","pdf"],[".png","image"],[".svg","image"],[".webp","image"]]);for(const ext of OFFICE_DOCUMENT_EXTENSIONS){ARTIFACT_KIND_BY_EXTENSION.set(ext,"document")}var WriteFileToolInvocation=class extends BaseToolInvocation{constructor(config,params){super(params);this.config=config}static{__name(this,"WriteFileToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());return`Writing to ${shortenPath(relativePath)}`}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(_abortSignal){let originalContent="";let observation;try{observation=await this.config.getFileSystemService().textFileIo?.inspect(this.params.file_path,_abortSignal)}catch(error){if(isNodeError(error)&&error.code==="EISDIR")throw new StructuredToolError(`Path is a directory, not a file: ${this.params.file_path}`,"target_is_directory");throw error}let fileExists2=observation?observation.kind==="file":await fileExists(this.params.file_path);if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting");if(!decision.ok){throw new StructuredToolError(decision.rawMessage,decision.type)}}if(fileExists2){try{const{content}=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:this.params.file_path});originalContent=content}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{throw new Error(`Error reading existing file for confirmation: ${getErrorMessage(err)}`)}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (confirmation)",{path:this.params.file_path,reason:postDecision.type});throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}}const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,originalContent,this.params.content,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Write: ${shortenPath(relativePath)}`,fileName,filePath:this.params.file_path,fileDiff,originalContent,newContent:this.params.content,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async execute(abortSignal){const io=this.config.getFileSystemService().textFileIo;if(!io)return this.executeObserved(abortSignal);try{return await io.withMutation(this.params.file_path,abortSignal,mutation=>this.executeObserved(abortSignal,mutation))}catch(error){if(abortSignal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(abortSignal,mutation){const{file_path,content,ai_proposed_content,modified_by_user}=this.params;let sandboxFileVersion;try{sandboxFileVersion=captureRuntimeFileVersion(this.config,file_path)}catch(error){const message=`${file_path}: ${getErrorMessage(error)}`;return{llmContent:message,returnDisplay:message,error:{message,type:isNodeError(error)&&error.code==="EISDIR"?"target_is_directory":"file_write_failure"}}}let fileExists2=mutation?mutation.original.kind==="file":await fileExists(file_path);let originalContent="";let useBOM=false;let detectedEncoding;let detectedLineEnding;const dirName=path.dirname(file_path);const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(file_path,content,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting");if(!decision.ok){return{llmContent:decision.rawMessage,returnDisplay:`Error: ${decision.displayMessage}`,error:{message:decision.rawMessage,type:decision.type}}}}if(fileExists2){try{const fileInfo=mutation?.original.kind==="file"?mutation.original.response:await this.config.getFileSystemService().readTextFile({path:file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);originalContent=fileInfo.content;fileExists2=true}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{const error={message:getErrorMessage(err),code:isNodeError(err)?err.code:void 0};const errorMsg=error.code?`Error checking existing file '${file_path}': ${error.message} (${error.code})`:`Error checking existing file: ${error.message}`;return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:"file_write_failure"}}}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (execute)",{path:file_path,reason:postDecision.type});return{llmContent:postDecision.rawMessage,returnDisplay:`Error: ${postDecision.displayMessage}`,error:{message:postDecision.rawMessage,type:postDecision.type}}}}if(!fileExists2){const userEncoding=this.config.getDefaultFileEncoding();if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(file_path)}detectedEncoding=void 0}try{await this.config.getFileHistoryService().trackEdit(file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:fileExists2});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!fileExists2&&!this.config.getShellExecutionSandbox?.()){fs.mkdirSync(dirName,{recursive:true})}try{const writeParams={path:file_path,content,toolWriteOrigin:"write_file",_meta:{bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}};const committedStats=mutation?await mutation.write(writeParams):(await writeRuntimeFile(this.config,writeParams,sandboxFileVersion,abortSignal),void 0);if(!mutation&&!modified_by_user){CommitAttributionService.getInstance().recordEdit(file_path,fileExists2?originalContent:null,content)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(file_path);const currentContentForDiff=originalContent;const fileDiff=createPatchSmart(fileName,currentContentForDiff,content,"Original","Written");const originallyProposedContent=ai_proposed_content||content;const diffStat=getDiffStat(fileName,currentContentForDiff,originallyProposedContent,content);const llmSuccessMessageParts=[!fileExists2?`Successfully created and wrote to new file: ${file_path}.`:`Successfully overwrote file: ${file_path}.`];if(modified_by_user){llmSuccessMessageParts.push(`User modified the \`content\` to be: ${content}`)}const artifact=this.params.record_as_artifact===false?null:buildWorkspaceArtifactMetadata(this.config,file_path,postWriteSizeBytes);if(artifact){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const mimetype=getSpecificMimeType(file_path);const programmingLanguage=getLanguageFromFilePath(file_path);const extension=path.extname(file_path);const operation=!fileExists2?"create":"update";const lineCount=content.split("\n").length;logFileOperation(this.config,new FileOperationEvent(WriteFileTool.Name,operation,lineCount,mimetype,extension,programmingLanguage));const displayResult={fileDiff,fileName,filePath:file_path,originalContent,newContent:content,diffStat};return{llmContent:llmSuccessMessageParts.join(" "),returnDisplay:displayResult,...artifact?{artifacts:[artifact]}:{}}}catch(error){return this.writeFailure(error)}}writeFailure(error){const file_path=this.params.file_path;let errorMsg;let errorType="file_write_failure";if(isNodeError(error)){errorMsg=`Error writing to file '${file_path}': ${error.message} (${error.code})`;if(error.code==="ESTALE"&&this.config.getShellExecutionSandbox?.()){errorType="file_changed_since_read"}else if(error.code==="EACCES"){errorMsg=`Permission denied writing to file: ${file_path} (${error.code})`;errorType="permission_denied"}else if(error.code==="ENOSPC"){errorMsg=`No space left on device: ${file_path} (${error.code})`;errorType="no_space_left"}else if(error.code==="EISDIR"){errorMsg=`Target is a directory, not a file: ${file_path} (${error.code})`;errorType="target_is_directory"}if(this.config.getDebugMode()&&error.stack){debugLogger.debug("Write file error stack:",error.stack)}}else{errorMsg=`Error writing to file: ${getErrorMessage(error)}`}return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:errorType}}}};function buildRecordArtifactReminder(config,filePath){const artifact=buildWorkspaceArtifactMetadata(config,filePath);return artifact?formatRecordArtifactReminder(artifact.workspacePath):null}__name(buildRecordArtifactReminder,"buildRecordArtifactReminder");function formatRecordArtifactReminder(workspacePath){return`This file was automatically recorded as a workspace artifact with workspacePath "${workspacePath}". No extra artifact registration step is needed.`}__name(formatRecordArtifactReminder,"formatRecordArtifactReminder");function buildWorkspaceArtifactMetadata(config,filePath,sizeBytes){const recorded=resolveRecordedWorkspaceFile(config,filePath);if(!recorded){return null}const title=path.basename(recorded.filePath);if(title.length>ARTIFACT_TITLE_MAX_LENGTH||hasControlCharacter(title)||hasUnsafeDisplayPayload(title)||recorded.workspacePath.length>ARTIFACT_WORKSPACE_PATH_MAX_LENGTH||hasControlCharacter(recorded.workspacePath)||hasUnsafeDisplayPayload(recorded.workspacePath)){debugLogger.debug("workspace artifact skipped (safety checks)",{path:filePath});return null}return{title,kind:inferWorkspaceArtifactKind(recorded.filePath),storage:"workspace",workspacePath:recorded.workspacePath,mimeType:getSpecificMimeType(recorded.filePath)??(recorded.filePath.toLowerCase().endsWith(".ipynb")?"application/x-ipynb+json":void 0),sizeBytes}}__name(buildWorkspaceArtifactMetadata,"buildWorkspaceArtifactMetadata");function resolveRecordedWorkspaceFile(config,filePath){if(!config.isRecordArtifactEnabled()){return null}let resolvedFile=filePath;let resolvedRoot=config.getTargetDir();try{if(!config.getFileSystemService().textFileIo){resolvedFile=fs.realpathSync(filePath);resolvedRoot=fs.realpathSync(resolvedRoot)}}catch{}if(!ARTIFACT_KIND_BY_EXTENSION.has(path.extname(resolvedFile).toLowerCase())){return null}const workspacePath=toCanonicalWorkspaceArtifactPath(resolvedFile,resolvedRoot);if(!workspacePath){return null}if(pathHasSkippedDirectoryComponent(workspacePath)){return null}return{filePath:resolvedFile,workspacePath}}__name(resolveRecordedWorkspaceFile,"resolveRecordedWorkspaceFile");function inferWorkspaceArtifactKind(filePath){return ARTIFACT_KIND_BY_EXTENSION.get(path.extname(filePath).toLowerCase())??"file"}__name(inferWorkspaceArtifactKind,"inferWorkspaceArtifactKind");var WRITE_FILE_ARTIFACT_DESCRIPTION="Artifact-like files such as HTML, PDF, images, notebooks, and office documents are automatically registered as session artifacts. Intermediate files that exist only to produce another artifact \u2014 for example HTML written solely to print a PDF \u2014 must set record_as_artifact=false, or be written under .qwen/tmp/ so they are not registered. Delete those intermediates when done.";var WriteFileTool=class _WriteFileTool extends BaseDeclarativeTool{constructor(config){super(_WriteFileTool.Name,ToolDisplayNames.WRITE_FILE,`Writes content to a specified file in the local filesystem. A request to create or generate a file does not establish that the target path is new. Unless the target's absence or current text contents have already been established in this session, you MUST use the ${ToolNames.READ_FILE} tool first; if the file does not exist, then create it. With prior-read enforcement enabled, blind overwrites are rejected. The file_path argument MUST be an absolute path. Always construct it by combining the project root with the file's relative path (e.g. project root '/path/to/project/' + relative 'foo/bar.txt' = '/path/to/project/foo/bar.txt'). If the user provides a relative path, resolve it against the project root first.
3
+ import{ARTIFACT_TITLE_MAX_LENGTH,ARTIFACT_WORKSPACE_PATH_MAX_LENGTH,OFFICE_DOCUMENT_EXTENSIONS,hasControlCharacter,hasUnsafeDisplayPayload,pathHasSkippedDirectoryComponent,toCanonicalWorkspaceArtifactPath}from"./chunk-NZFR5IY7.js";import{captureRuntimeFileVersion,writeRuntimeFile}from"./chunk-QZPNBV4F.js";import{checkTeamMemorySecrets,checkWorkspaceTeamMemorySecrets}from"./chunk-6GLM4FUL.js";import{CommitAttributionService,FileEncoding,checkPriorRead,createPatchSmart,detectLineEnding,getDiffStat,needsUtf8Bom}from"./chunk-IFAUFERF.js";import{FileOperationEvent,getLanguageFromFilePath,logFileOperation}from"./chunk-KBPIYGHG.js";import{fileExists,getSpecificMimeType}from"./chunk-JU2HHQR5.js";import{isAnyAutoMemPath,isTeamAutoMemPath}from"./chunk-37KFLBKZ.js";import{BaseDeclarativeTool,BaseToolInvocation,StructuredToolError}from"./chunk-O5EKX7LG.js";import{ToolDisplayNames,ToolNames}from"./chunk-2UNFJQ2D.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{makeRelative,shortenPath,unescapePath}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import fs from"node:fs";import path from"node:path";var debugLogger=createDebugLogger("WRITE_FILE");var ARTIFACT_KIND_BY_EXTENSION=new Map([[".csv","file"],[".htm","html"],[".html","html"],[".ipynb","notebook"],[".jpeg","image"],[".jpg","image"],[".pdf","pdf"],[".png","image"],[".svg","image"],[".webp","image"]]);for(const ext of OFFICE_DOCUMENT_EXTENSIONS){ARTIFACT_KIND_BY_EXTENSION.set(ext,"document")}var WriteFileToolInvocation=class extends BaseToolInvocation{constructor(config,params){super(params);this.config=config}static{__name(this,"WriteFileToolInvocation")}toolLocations(){return[{path:this.params.file_path}]}getDescription(){const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());return`Writing to ${shortenPath(relativePath)}`}async getDefaultPermission(){if(this.config.getFileSystemService().textFileIo)return"ask";const projectRoot=this.config.getProjectRoot();const filePath=path.resolve(this.params.file_path);if(isTeamAutoMemPath(filePath,projectRoot)){return"ask"}if(isAnyAutoMemPath(filePath,projectRoot)){return"allow"}return"ask"}async getConfirmationDetails(_abortSignal){let originalContent="";let observation;try{observation=await this.config.getFileSystemService().textFileIo?.inspect(this.params.file_path,_abortSignal)}catch(error){if(isNodeError(error)&&error.code==="EISDIR")throw new StructuredToolError(`Path is a directory, not a file: ${this.params.file_path}`,"target_is_directory");throw error}let fileExists2=observation?observation.kind==="file":await fileExists(this.params.file_path);if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting");if(!decision.ok){throw new StructuredToolError(decision.rawMessage,decision.type)}}if(fileExists2){try{const{content}=observation?.kind==="file"?observation.response:await this.config.getFileSystemService().readTextFile({path:this.params.file_path});originalContent=content}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{throw new Error(`Error reading existing file for confirmation: ${getErrorMessage(err)}`)}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),this.params.file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (confirmation)",{path:this.params.file_path,reason:postDecision.type});throw new StructuredToolError(postDecision.rawMessage,postDecision.type)}}const relativePath=makeRelative(this.params.file_path,this.config.getTargetDir());const fileName=path.basename(this.params.file_path);const fileDiff=createPatchSmart(fileName,originalContent,this.params.content,"Current","Proposed");const confirmationDetails={type:"edit",title:`Confirm Write: ${shortenPath(relativePath)}`,fileName,filePath:this.params.file_path,fileDiff,originalContent,newContent:this.params.content,onConfirm:__name(async outcome=>{if(outcome==="proceed_always"){this.config.setApprovalMode("auto-edit")}},"onConfirm")};return confirmationDetails}async execute(abortSignal){const io=this.config.getFileSystemService().textFileIo;if(!io)return this.executeObserved(abortSignal);try{return await io.withMutation(this.params.file_path,abortSignal,mutation=>this.executeObserved(abortSignal,mutation))}catch(error){if(abortSignal.aborted)throw error;return this.writeFailure(error)}}async executeObserved(abortSignal,mutation){const{file_path,content,ai_proposed_content,modified_by_user}=this.params;let sandboxFileVersion;try{sandboxFileVersion=captureRuntimeFileVersion(this.config,file_path)}catch(error){const message=`${file_path}: ${getErrorMessage(error)}`;return{llmContent:message,returnDisplay:message,error:{message,type:isNodeError(error)&&error.code==="EISDIR"?"target_is_directory":"file_write_failure"}}}let fileExists2=mutation?mutation.original.kind==="file":await fileExists(file_path);let originalContent="";let useBOM=false;let detectedEncoding;let detectedLineEnding;const dirName=path.dirname(file_path);const teamMemoryError=(this.config.getFileSystemService().textFileIo?checkWorkspaceTeamMemorySecrets:checkTeamMemorySecrets)(file_path,content,this.config.getProjectRoot());if(teamMemoryError){return{llmContent:`[ERROR: ${teamMemoryError}]`,returnDisplay:teamMemoryError,error:{message:teamMemoryError,type:"invalid_tool_params"}}}if(!this.config.getFileReadCacheDisabled()){const decision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting");if(!decision.ok){return{llmContent:decision.rawMessage,returnDisplay:`Error: ${decision.displayMessage}`,error:{message:decision.rawMessage,type:decision.type}}}}if(fileExists2){try{const fileInfo=mutation?.original.kind==="file"?mutation.original.response:await this.config.getFileSystemService().readTextFile({path:file_path});if(fileInfo._meta?.bom!==void 0){useBOM=fileInfo._meta.bom}else{useBOM=fileInfo.content.length>0&&fileInfo.content.codePointAt(0)===65279}detectedEncoding=fileInfo._meta?.encoding||"utf-8";detectedLineEnding=detectLineEnding(fileInfo.content);originalContent=fileInfo.content;fileExists2=true}catch(err){if(isNodeError(err)&&err.code==="ENOENT"){fileExists2=false}else{const error={message:getErrorMessage(err),code:isNodeError(err)?err.code:void 0};const errorMsg=error.code?`Error checking existing file '${file_path}': ${error.message} (${error.code})`:`Error checking existing file: ${error.message}`;return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:"file_write_failure"}}}}}if(fileExists2&&!this.config.getFileReadCacheDisabled()){const postDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:true});if(!postDecision.ok){debugLogger.warn("post-read TOCTOU rejection (execute)",{path:file_path,reason:postDecision.type});return{llmContent:postDecision.rawMessage,returnDisplay:`Error: ${postDecision.displayMessage}`,error:{message:postDecision.rawMessage,type:postDecision.type}}}}if(!fileExists2){const userEncoding=this.config.getDefaultFileEncoding();if(userEncoding===FileEncoding.UTF8_BOM){useBOM=true}else if(userEncoding===void 0){useBOM=needsUtf8Bom(file_path)}detectedEncoding=void 0}try{await this.config.getFileHistoryService().trackEdit(file_path)}catch{}if(!this.config.getFileReadCacheDisabled()){const writeDecision=await checkPriorRead(this.config.getFileReadCache(),file_path,"overwriting",{expectExisting:fileExists2});if(!writeDecision.ok){debugLogger.warn("pre-write TOCTOU rejection",{path:file_path,reason:writeDecision.type});return{llmContent:writeDecision.rawMessage,returnDisplay:`Error: ${writeDecision.displayMessage}`,error:{message:writeDecision.rawMessage,type:writeDecision.type}}}}if(!mutation&&!fileExists2&&!this.config.getShellExecutionSandbox?.()){fs.mkdirSync(dirName,{recursive:true})}try{const writeParams={path:file_path,content,toolWriteOrigin:"write_file",_meta:{bom:useBOM,encoding:detectedEncoding,lineEnding:detectedLineEnding}};const committedStats=mutation?await mutation.write(writeParams):(await writeRuntimeFile(this.config,writeParams,sandboxFileVersion,abortSignal),void 0);if(!mutation&&!modified_by_user){CommitAttributionService.getInstance().recordEdit(file_path,fileExists2?originalContent:null,content)}let postWriteSizeBytes;try{if(mutation&&!committedStats)throw new Error("Scoped file write returned no committed stats.");const postWriteStats=mutation?committedStats:fs.statSync(file_path);postWriteSizeBytes=postWriteStats.size;this.config.getFileReadCache().recordWrite(file_path,postWriteStats)}catch(error){if(mutation)throw error}const fileName=path.basename(file_path);const currentContentForDiff=originalContent;const fileDiff=createPatchSmart(fileName,currentContentForDiff,content,"Original","Written");const originallyProposedContent=ai_proposed_content||content;const diffStat=getDiffStat(fileName,currentContentForDiff,originallyProposedContent,content);const llmSuccessMessageParts=[!fileExists2?`Successfully created and wrote to new file: ${file_path}.`:`Successfully overwrote file: ${file_path}.`];if(modified_by_user){llmSuccessMessageParts.push(`User modified the \`content\` to be: ${content}`)}const artifact=this.params.record_as_artifact===false?null:buildWorkspaceArtifactMetadata(this.config,file_path,postWriteSizeBytes);if(artifact){llmSuccessMessageParts.push(formatRecordArtifactReminder(artifact.workspacePath))}const mimetype=getSpecificMimeType(file_path);const programmingLanguage=getLanguageFromFilePath(file_path);const extension=path.extname(file_path);const operation=!fileExists2?"create":"update";const lineCount=content.split("\n").length;logFileOperation(this.config,new FileOperationEvent(WriteFileTool.Name,operation,lineCount,mimetype,extension,programmingLanguage));const displayResult={fileDiff,fileName,filePath:file_path,originalContent,newContent:content,diffStat};return{llmContent:llmSuccessMessageParts.join(" "),returnDisplay:displayResult,...artifact?{artifacts:[artifact]}:{}}}catch(error){return this.writeFailure(error)}}writeFailure(error){const file_path=this.params.file_path;let errorMsg;let errorType="file_write_failure";if(isNodeError(error)){errorMsg=`Error writing to file '${file_path}': ${error.message} (${error.code})`;if(error.code==="ESTALE"&&this.config.getShellExecutionSandbox?.()){errorType="file_changed_since_read"}else if(error.code==="EACCES"){errorMsg=`Permission denied writing to file: ${file_path} (${error.code})`;errorType="permission_denied"}else if(error.code==="ENOSPC"){errorMsg=`No space left on device: ${file_path} (${error.code})`;errorType="no_space_left"}else if(error.code==="EISDIR"){errorMsg=`Target is a directory, not a file: ${file_path} (${error.code})`;errorType="target_is_directory"}if(this.config.getDebugMode()&&error.stack){debugLogger.debug("Write file error stack:",error.stack)}}else{errorMsg=`Error writing to file: ${getErrorMessage(error)}`}return{llmContent:errorMsg,returnDisplay:errorMsg,error:{message:errorMsg,type:errorType}}}};function buildRecordArtifactReminder(config,filePath){const artifact=buildWorkspaceArtifactMetadata(config,filePath);return artifact?formatRecordArtifactReminder(artifact.workspacePath):null}__name(buildRecordArtifactReminder,"buildRecordArtifactReminder");function formatRecordArtifactReminder(workspacePath){return`This file was automatically recorded as a workspace artifact with workspacePath "${workspacePath}". No extra artifact registration step is needed.`}__name(formatRecordArtifactReminder,"formatRecordArtifactReminder");function buildWorkspaceArtifactMetadata(config,filePath,sizeBytes){const recorded=resolveRecordedWorkspaceFile(config,filePath);if(!recorded){return null}const title=path.basename(recorded.filePath);if(title.length>ARTIFACT_TITLE_MAX_LENGTH||hasControlCharacter(title)||hasUnsafeDisplayPayload(title)||recorded.workspacePath.length>ARTIFACT_WORKSPACE_PATH_MAX_LENGTH||hasControlCharacter(recorded.workspacePath)||hasUnsafeDisplayPayload(recorded.workspacePath)){debugLogger.debug("workspace artifact skipped (safety checks)",{path:filePath});return null}return{title,kind:inferWorkspaceArtifactKind(recorded.filePath),storage:"workspace",workspacePath:recorded.workspacePath,mimeType:getSpecificMimeType(recorded.filePath)??(recorded.filePath.toLowerCase().endsWith(".ipynb")?"application/x-ipynb+json":void 0),sizeBytes}}__name(buildWorkspaceArtifactMetadata,"buildWorkspaceArtifactMetadata");function resolveRecordedWorkspaceFile(config,filePath){if(!config.isRecordArtifactEnabled()){return null}let resolvedFile=filePath;let resolvedRoot=config.getTargetDir();try{if(!config.getFileSystemService().textFileIo){resolvedFile=fs.realpathSync(filePath);resolvedRoot=fs.realpathSync(resolvedRoot)}}catch{}if(!ARTIFACT_KIND_BY_EXTENSION.has(path.extname(resolvedFile).toLowerCase())){return null}const workspacePath=toCanonicalWorkspaceArtifactPath(resolvedFile,resolvedRoot);if(!workspacePath){return null}if(pathHasSkippedDirectoryComponent(workspacePath)){return null}return{filePath:resolvedFile,workspacePath}}__name(resolveRecordedWorkspaceFile,"resolveRecordedWorkspaceFile");function inferWorkspaceArtifactKind(filePath){return ARTIFACT_KIND_BY_EXTENSION.get(path.extname(filePath).toLowerCase())??"file"}__name(inferWorkspaceArtifactKind,"inferWorkspaceArtifactKind");var WRITE_FILE_ARTIFACT_DESCRIPTION="Artifact-like files such as HTML, PDF, images, notebooks, and office documents are automatically registered as session artifacts. Intermediate files that exist only to produce another artifact \u2014 for example HTML written solely to print a PDF \u2014 must set record_as_artifact=false, or be written under .qwen/tmp/ so they are not registered. Delete those intermediates when done.";var WriteFileTool=class _WriteFileTool extends BaseDeclarativeTool{constructor(config){super(_WriteFileTool.Name,ToolDisplayNames.WRITE_FILE,`Writes content to a specified file in the local filesystem. A request to create or generate a file does not establish that the target path is new. Unless the target's absence or current text contents have already been established in this session, you MUST use the ${ToolNames.READ_FILE} tool first; if the file does not exist, then create it. With prior-read enforcement enabled, blind overwrites are rejected. The file_path argument MUST be an absolute path. Always construct it by combining the project root with the file's relative path (e.g. project root '/path/to/project/' + relative 'foo/bar.txt' = '/path/to/project/foo/bar.txt'). If the user provides a relative path, resolve it against the project root first.
4
4
 
5
5
  ${WRITE_FILE_ARTIFACT_DESCRIPTION}
6
6
 
@@ -1,7 +1,7 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{HEADLESS_YOLO_NO_SANDBOX_WARNING}from"./chunk-Z57KDB5F.js";import{DEFAULT_RING_SIZE}from"./chunk-EDCAX2GY.js";import{DEFAULT_COMPACTED_REPLAY_MAX_BYTES,DEFAULT_MAX_JOURNAL_BYTES,DEFAULT_MAX_JOURNAL_EVENTS,JOURNAL_GROWTH_HARD_CAP_BYTES}from"./chunk-WDR5XP3Y.js";import{JOURNAL_GROWTH_POOL_FRACTION,MAX_JOURNAL_GROWTH_POOL_MB,MIN_MEMORY_BUDGET_MB,isValidMemoryBudgetMb,memoryBudgetRangeError}from"./chunk-2QYDBHYZ.js";import{normalizeServeChannelSelection}from"./chunk-KOJ7WZ63.js";import{EXTERNAL_TOOL_GUARD_TOKEN_ENV}from"./chunk-NIEO2TBE.js";import{loadSettings}from"./chunk-JV5FCFG4.js";import{MCP_BUDGET_WARN_FRACTION}from"./chunk-GG7RNHZW.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{openBrowserSecurely,shouldLaunchBrowser}from"./chunk-3YWXKSOI.js";import{MEMORY_PROJECT_SCOPES}from"./chunk-PWOQASXT.js";import{writeStderrLine,writeStdoutLine}from"./chunk-SLPJ4OII.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var SEGMENT=/^[A-Za-z0-9_-]{1,256}$/;function parseJoinLink(link){let url;try{url=new URL(link.trim())}catch{throw new Error("--join expects the link shown by the coordinator.")}const marker=url.pathname.lastIndexOf("/join/");const[workspaceId,...rest]=marker>=0?url.pathname.slice(marker+"/join/".length).split("/"):[];if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.search||url.hash||!workspaceId||rest.some(Boolean)||!SEGMENT.test(workspaceId)){throw new Error("--join expects a link like https://host:4170/join/<workspace>.")}const base=url.pathname.slice(0,marker).replace(/\/+$/,"");return{serverUrl:`${url.origin}${base}`,workspaceId}}__name(parseJoinLink,"parseJoinLink");function blockForever(){return new Promise(()=>{})}__name(blockForever,"blockForever");var DEFAULT_SERVE_HOSTNAME="127.0.0.1";async function startLocalControl(handle,address){await handle.runtimeReady;if(!handle.webShellMounted){throw new Error("Local Control requires the Web Shell.")}const service=handle.getLocalControl();if(!service){throw new Error("Local Control is unavailable on this daemon.")}let status;try{status=await service.enable(address?{address}:{})}catch(err){if(err instanceof Error&&err.code==="ambiguous_lan_interface"){throw new Error(`${err.message}. Pass --local-control-address <ip>.`)}throw err}if(!status.url){throw new Error("Local Control did not return a pairing URL.")}const{default:qrcode}=await import("./main-5IVKRF6Q.js");qrcode.setErrorLevel("Q");writeStdoutLine("\nLocal Control is on. Scan this QR code from the same network:");writeStdoutLine(`
4
- ${status.interfaceName}: ${status.url}`);qrcode.generate(status.url,{small:true},code=>{writeStdoutLine(code.trimEnd())});writeStdoutLine("\nKeep this terminal open. "+(status.sleepInhibited?"Sleep is inhibited while this session is active. ":"Sleep inhibition is unavailable here, so the host may sleep. ")+(status.encrypted?"Traffic is encrypted.":"Traffic is unencrypted \u2014 use it only on a network you trust.")+" Turn Local Control off from the Web Shell Settings card, or press Ctrl+C to exit the daemon.")}__name(startLocalControl,"startLocalControl");async function maybeOpenWebShellBrowser(handle,open,manualFallbackWhenIneligible=false){if(!open||!handle.webShellMounted)return;const shouldLaunch=shouldLaunchBrowser();if(!shouldLaunch&&!manualFallbackWhenIneligible)return;try{await handle.runtimeReady}catch(runtimeErr){writeStderrLine(`qwen serve: Web Shell runtime not ready; skipping --open: ${runtimeErr instanceof Error?runtimeErr.message:String(runtimeErr)}`);return}let target;try{target=new URL(handle.url);if(target.hostname==="0.0.0.0"||target.hostname==="[::]"){target.hostname="127.0.0.1"}if(handle.resolvedToken){target.hash=`token=${encodeURIComponent(handle.resolvedToken)}`}if(!shouldLaunch){writeStderrLine(`Browser launch is not available in this environment. Please open this URL manually: ${target.toString()}`);return}if(handle.resolvedToken){writeStderrLine("qwen serve: --open passes the token in the browser launch command (visible via `ps` / /proc); on a multi-user host open the URL manually instead.")}await openBrowserSecurely(target.toString())}catch(browserErr){const manualUrl=manualFallbackWhenIneligible&&target?`. Please open this URL manually: ${target.toString()}`:"";writeStderrLine(`qwen serve: failed to open browser: ${browserErr instanceof Error?browserErr.message:String(browserErr)}${manualUrl}`)}}__name(maybeOpenWebShellBrowser,"maybeOpenWebShellBrowser");function primaryWorkspaceArg(workspace){return Array.isArray(workspace)?workspace[0]:workspace}__name(primaryWorkspaceArg,"primaryWorkspaceArg");var serveCommand={command:"serve",describe:"Run Qwen Code as a local HTTP daemon (Stage 1 experimental: --http-bridge)",builder:__name(yargs=>yargs.option("port",{type:"number",default:4170,description:"TCP port to bind (use 0 for an OS-assigned ephemeral port)"}).option("hostname",{type:"string",default:DEFAULT_SERVE_HOSTNAME,description:"Interface to bind. Loopback (127.0.0.0/8, localhost, ::1, [::1]) is auth-free; anything else requires a token (one is generated and printed when neither --token nor QWEN_SERVER_TOKEN supplies one). A localhost bind that resolves off-loopback never generates, and still refuses when no token source resolved; an empty value is rejected as operator error."}).option("profile",{choices:["default","hosted-harness"],default:"default",description:"Deployment profile. hosted-harness enables the private no-tool Managed Session API on loopback."}).option("hosted-harness-capability-digest",{type:"string",description:"SHA-256 capability digest for the private Hosted Harness profile. Falls back to QWEN_HOSTED_HARNESS_CAPABILITY_DIGEST."}).option("token",{type:"string",description:"Bearer token required on every request. Falls back to the QWEN_SERVER_TOKEN env var; a non-loopback bind with neither generates an ephemeral token at startup, while loopback keeps the trusted tokenless mode unless --require-auth is set."}).option("max-sessions",{type:"number",default:32,description:"Cap on concurrent live sessions. New spawn requests beyond this return 503; attach to existing sessions still works. Set to 0 to disable."}).option("max-total-sessions",{type:"number",description:"Non-negative integer cap on concurrent live sessions across all workspace runtimes. Set to 0 to disable."}).option("max-pending-prompts-per-session",{type:"number",default:5,description:"Per-session cap on accepted prompts waiting or running. New prompts beyond this return 503. Set to 0 to disable."}).option("workspace",{type:"string",array:true,requiresArg:true,description:"Absolute workspace path to register with this daemon. POST /session requests with a mismatched cwd return 400 workspace_mismatch. Defaults to process.cwd() when omitted. Repeat to register isolated workspace runtimes; the first is primary."}).option("memory-project-scope",{type:"string",choices:MEMORY_PROJECT_SCOPES,description:'Choose how project memory is partitioned. Defaults to "workspace" so each daemon workspace stays isolated; "git-root" preserves the legacy shared scope. Overrides QWEN_CODE_MEMORY_PROJECT_SCOPE when provided.'}).option("max-connections",{type:"number",default:256,description:"Listener-level TCP connection cap (server.maxConnections). Bounds raw sockets \u2014 slow/phantom SSE clients get rejected at accept time once full. Set to 0 to disable."}).option("require-auth",{type:"boolean",default:false,description:"Refuse to start without a bearer token, even on loopback. Hardens the loopback developer default for shared dev hosts / CI runners / multi-tenant workstations where any local user can hit 127.0.0.1. Requires --token, QWEN_SERVER_TOKEN, or --open-with-auth (which installs its own generated loopback token); on non-loopback binds the generated ephemeral token also satisfies it, so the no-configured-secret fail-fast is loopback-only. /health also requires Authorization when enabled (no loopback exemption \u2014 k8s/Compose probes must pass the bearer too)."}).option("enable-session-shell",{type:"boolean",default:false,description:"Enable direct POST /session/:id/shell execution. Available with bearer auth or trusted loopback; each call still requires a session-bound client id."}).option("tls-cert",{type:"string",description:"Path to a PEM certificate file. Serve over HTTPS instead of HTTP. Required for secure-context browser APIs (voice input/getUserMedia, WebRTC) when accessed over a LAN IP. Must be used together with --tls-key. Generate a local cert with mkcert."}).option("tls-key",{type:"string",description:"Path to a PEM private key file. Must be used together with --tls-cert."}).option("experimental-lsp",{type:"boolean",default:false,description:"Forward the experimental LSP opt-in to spawned agent sessions."}).option("restore-ask-user-question",{type:"boolean",default:false,description:"On session load/resume, re-hang a trailing unanswered ask_user_question instead of synthesizing a failed tool result."}).option("channel",{type:"string",array:true,description:"Experimental: start a daemon-managed channel worker for the named channel. Repeat to select multiple channels, or use --channel all."}).option("web",{type:"boolean",default:true,description:"Serve the Web Shell UI at the daemon root path. Use --no-web for an API-only daemon."}).option("open",{type:"boolean",default:false,description:"Open the Web Shell in a browser once the daemon is listening. With a token configured, the launch URL (token included) is handed to the browser launcher and is visible in the process list, so prefer opening the URL manually on multi-user hosts. No-op with --no-web, when the UI assets are absent, or in headless/CI/SSH environments."}).option("open-with-auth",{type:"boolean",default:false,description:"Open the Web Shell with bearer authentication on loopback. Reuse --token or QWEN_SERVER_TOKEN, or generate a temporary 256-bit token and deliver it in the URL fragment. In headless environments, print the fragment URL for manual opening."}).option("token-qr",{type:"boolean",description:"Print the token-bearing QR even when stdout is captured (not an interactive terminal) and the bearer is an operator-supplied (stable) token, which is withheld by default to keep stable credentials out of collected logs. Enable only when the log pipeline is as trusted as the daemon host. Can also be set via the serve.tokenQr setting (user, system, and system-defaults scopes only); the flag wins when passed. --no-token-qr suppresses the startup quickstart token QR for that run on every quickstart path \u2014 interactive terminal and generated token included. It does not govern the Local Control pairing QR, which --local-control prints by design."}).option("local-control",{type:"boolean",default:false,description:"Share the Web Shell on the local IPv4 network with its own revocable pairing token, terminal QR code, and best-effort sleep inhibition. Ctrl+C turns it off by ending the whole daemon; the Web Shell Settings card turns it off while the daemon keeps running."}).option("local-control-address",{type:"string",description:"Which local IPv4 address to share when the host is on more than one network. Only needed if --local-control reports an ambiguous choice."}).option("join",{type:"string",description:"Join another Qwen Code as a runtime, with the one-line link it shows under Agent \u2192 Runtime \u2192 Add runtime."}).option("agent-host-server",{type:"string",description:"Register this daemon as an Agent Host with a primary Qwen daemon."}).option("agent-host-workspace-id",{type:"string",description:"Control-plane workspace id printed by the primary daemon."}).option("agent-host-name",{type:"string",description:"Display name advertised for this Agent Host."}).option("agent-host-allow-http",{type:"boolean",default:false,description:"Allow unencrypted Agent Host HTTP connections outside loopback (trusted demo networks only)."}).check(argv=>{if(argv["local-control"]===true&&argv["web"]===false){throw new Error("Local Control requires the Web Shell.")}if(argv["local-control"]===true&&argv.hostname!==DEFAULT_SERVE_HOSTNAME){throw new Error(`Local Control requires --hostname ${DEFAULT_SERVE_HOSTNAME}.`)}if(argv["local-control"]!==true&&argv["local-control-address"]!==void 0){throw new Error("--local-control-address requires --local-control.")}if(argv["local-control-address"]===""){throw new Error("--local-control-address must not be empty.")}if(Boolean(argv["agent-host-server"])!==Boolean(argv["agent-host-workspace-id"])){throw new Error("--agent-host-server and --agent-host-workspace-id must be used together.")}if(argv["agent-host-name"]===""){throw new Error("--agent-host-name must not be empty.")}if(argv["join"]!==void 0){if(argv["agent-host-server"]||argv["agent-host-workspace-id"]){throw new Error("--join already names the coordinator and workspace; drop --agent-host-server and --agent-host-workspace-id.")}parseJoinLink(argv["join"])}return true}).option("event-ring-size",{type:"number",default:DEFAULT_RING_SIZE,description:"Per-session SSE replay ring depth. Sets the replay backlog available to `GET /session/:id/events` reconnects that send a `Last-Event-ID: N` header. Larger = more reconnect headroom at the cost of a few hundred KB extra RAM per session. Must be a positive finite integer."}).option("compacted-replay-max-bytes",{type:"number",default:DEFAULT_COMPACTED_REPLAY_MAX_BYTES,description:"Per-session in-memory compacted replay snapshot byte cap for `POST /session/:id/load` late attaches. Larger = more recent history in load snapshots at higher heap cost. Must be a positive safe integer no larger than 256 MiB."}).option("max-journal-events",{type:"number",nargs:1,description:"Per-session baseline cap on replay entries retained in the in-flight live journal (current unfinished turn). Compatible text/thought chunks share bounded entries. When exceeded, the daemon first tries adaptive growth (see --max-journal-bytes); without granted headroom the oldest entries are dropped. Pinning this flag (or --max-journal-bytes) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_EVENTS+" when unset. Must be a positive safe integer."}).option("max-journal-bytes",{type:"number",nargs:1,description:"Per-session baseline source-event byte cap on the in-flight live journal. When a turn outgrows it, adaptive growth raises the session's caps (per-session hard cap "+JOURNAL_GROWTH_HARD_CAP_BYTES/(1024*1024)+" MiB) within a growth pool derived from the daemon memory budget (see --memory-budget-mb); without granted headroom the oldest entries are dropped whole (at least one is always kept), so the retained tail can be much smaller than the cap. Pinning this flag (or --max-journal-events) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_BYTES+" bytes when unset. Must be a positive safe integer."}).option("http-bridge",{type:"boolean",default:true,description:"HTTP bridge mode: attempt to preheat the primary `qwen --acp` child; trusted secondaries start one on demand. Stage 2 native in-process mode is not yet implemented; this flag will become opt-in then."}).option("memory-budget-mb",{type:"number",description:"Total memory budget in MB for the daemon process tree. When unset, derived as 50% of cgroup-constrained or host memory, and capped at the resolved available memory either way. In `admit` and `enforce` modes it determines managed ACP child capacity; `enforce` also applies the modeled per-child old-space ceiling. It also sizes one daemon-wide pool of "+JOURNAL_GROWTH_POOL_FRACTION*100+"% of the effective budget (capped at "+MAX_JOURNAL_GROWTH_POOL_MB+" MB; 0, growth disabled, when the effective budget falls below the "+MIN_MEMORY_BUDGET_MB+" MB minimum; see --max-journal-bytes). Reported under `limits.memory` in daemon status, alongside a modeled per-child partition under `limits.memory.childHeap`. Must be an integer in [1024, 1048576]."}).option("memory-pressure-mode",{choices:["off","observe"],default:"observe",description:"Whether the daemon derives a memory-pressure level from its own RSS and V8 heap. `observe` (default) reports the level in daemon status and raises a status issue when it leaves normal. `off` still reports the underlying figures but raises no issue, so the overall status rollup is unchanged \u2014 use it while calibrating, or if you alert on the top-level status. Nothing remediates in either mode."}).option("child-heap-mode",{choices:["off","observe","admit","enforce"],default:"observe",description:"Whether the daemon models a per-child heap partition of the memory budget. `observe` (default) reports the partition it would apply \u2014 `limits.memory.childHeap.perChildCeilingMb` and `maxConcurrentChildren` \u2014 and counts spawns that would have exceeded it. Nothing is applied: no child is sized from the budget and no spawn is refused. `off` models nothing. Note a refusal count of 0 does NOT mean the partition would be safe to apply; children still run on the much larger host-derived ceiling, so a workload needing more old space than the modeled ceiling looks healthy here. `admit` rejects starts past the modeled process limit but keeps the existing child heap arguments. Experimental `enforce` also applies the fixed modeled old-space ceiling to each managed child; it does not cap total process RSS."}).option("mcp-client-budget",{type:"number",description:"Cap on live MCP clients spawned inside the ACP child for the bound workspace. Positive integer. Combine with --mcp-budget-mode to control behavior at the cap. When unset, mode defaults to off (no accounting-driven enforcement, but GET /workspace/mcp still reports `clientCount`). Distinct from claude-code MCP_SERVER_CONNECTION_BATCH_SIZE which gates startup concurrency, not the total client count."}).option("mcp-budget-mode",{choices:["enforce","warn","off"],description:'How --mcp-client-budget is enforced. `warn` (default when budget set): no refusal, snapshot surfaces warning at >=75% of budget. `enforce`: connects past the cap are refused (`disabledReason: "budget"`, deterministic by mcpServers declaration order). `off`: pure observability. Boot rejects `enforce` without a budget.'}).option("allow-origin",{type:"string",array:true,description:"Cross-origin allowlist for browser clients."}).option("allow-private-auth-base-url",{type:"boolean",default:false,description:"Allow /workspace/auth/provider to install localhost/private-network baseUrl values. Use only for local development with trusted clients."}).option("prompt-deadline-ms",{type:"number",description:"Server-side wallclock cap on POST /session/:id/prompt (ms). Falls back to QWEN_SERVE_PROMPT_DEADLINE_MS. Positive integer."}).option("experimental-paired-engines",{type:"boolean",default:false,description:"Experimental: build workspace runtimes, other than the private Conversations one, with paired Legacy and Managed engines. No Managed engine is available yet, so sessions run on Legacy with a durable owner."}).option("experimental-managed-agents",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-worker",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-auto-local",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-url",{type:"string",requiresArg:true,description:"Reserved experimental Runtime URL; not implemented and rejects startup."}).option("experimental-managed-runtime-token",{type:"string",requiresArg:true,description:"Reserved experimental Runtime credential; not implemented and rejects startup."}).option("managed-runtime-broker-url",{type:"string",requiresArg:true,description:"Private Broker URL for --profile hosted-harness; required together with token for Workspace tool turns."}).option("managed-runtime-broker-token",{type:"string",requiresArg:true,description:"Private Broker credential for --profile hosted-harness; required together with URL for Workspace tool turns."}).option("writer-idle-timeout-ms",{type:"number",description:"Per-SSE-connection idle deadline (ms). Falls back to QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS. Positive integer."}).option("channel-idle-timeout-ms",{type:"number",description:"Compatibility auto-reap delay for an idle workspace ACP child. 0 or unset = reap after work drains; keepalive windows may extend it (default)."}).option("initialize-timeout-ms",{type:"number",description:"ACP child request timeout, including the initialize handshake (ms). Default: 10000 (10 s)."}).option("session-restore-timeout-ms",{type:"number",description:"ACP session load/resume timeout (ms). Default: 60000. An explicit --initialize-timeout-ms can raise (but never lower) this default."}).option("session-reap-interval-ms",{type:"number",description:"Session reaper scan interval (ms). 0 = disabled. Default: 60000."}).option("session-idle-timeout-ms",{type:"number",description:"Idle timeout before a disconnected session is reaped (ms). 0 = disabled. Default: 1800000 (30 min)."}).option("session-prompt-settled-close-grace-ms",{type:"number",description:"Grace period after a prompt settles before an otherwise-idle session may be auto-closed (ms). Poll-based SSE clients use this window to reconnect without triggering a session rebuild. 0 = disabled (immediate close). Default: 0."}).option("permission-response-timeout-ms",{type:"number",description:"Wall-clock timeout for a human permission / ask_user_question response in daemon (ACP) mode (ms). 0 or unset = disabled (wait indefinitely). Default: 0."}).option("external-tool-guard-mode",{choices:["off","required"],default:"off",description:"Managed ACP pre-execution policy mode. Default off preserves current CLI and daemon behavior. Required fails startup unless a compatible loopback provider is available."}).option("external-tool-guard-endpoint",{type:"string",description:"Origin-only loopback HTTP(S) endpoint for required external tool guarding, for example http://127.0.0.1:8787."}).option("external-tool-guard-timeout-ms",{type:"number",description:"Per-handshake/prepare external tool guard timeout in milliseconds. Default: 3000."}).option("rate-limit",{type:"boolean",description:"Enable per-tier HTTP rate limiting. Tiers: prompt (10/min), mutation (30/min), read (120/min). Health, heartbeat, SSE, and /acp are exempt."}).option("rate-limit-prompt",{type:"number",description:"Max prompt requests per window per client (default 10). Requires --rate-limit."}).option("rate-limit-mutation",{type:"number",description:"Max mutation requests per window per client (default 30). Requires --rate-limit."}).option("rate-limit-read",{type:"number",description:"Max read requests per window per client (default 120). Requires --rate-limit."}).option("rate-limit-window-ms",{type:"number",description:"Rate limit window duration in ms (default 60000). Requires --rate-limit."}),"builder"),handler:__name(async argv=>{const agentHostEnrollmentToken=process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"]?.trim();delete process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"];if(!argv["http-bridge"]){writeStderrLine("qwen serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge.")}if(argv.token){writeStderrLine("qwen serve: --token is visible in the process command line; prefer the QWEN_SERVER_TOKEN env var for any non-trivial deployment.")}let channelSelection;try{channelSelection=normalizeServeChannelSelection(argv.channel)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}const mcpClientBudget=argv["mcp-client-budget"];const mcpBudgetMode=argv["mcp-budget-mode"];if(mcpClientBudget!==void 0){if(!Number.isFinite(mcpClientBudget)||!Number.isInteger(mcpClientBudget)||mcpClientBudget<=0){writeStderrLine("qwen serve: --mcp-client-budget must be a positive integer.");process.exit(1)}}if(mcpBudgetMode==="enforce"&&mcpClientBudget===void 0){writeStderrLine("qwen serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N.");process.exit(1)}const resolvedMcpMode=mcpBudgetMode??(mcpClientBudget!==void 0?"warn":"off");const memoryBudgetMb=argv["memory-budget-mb"];if(memoryBudgetMb!==void 0&&!isValidMemoryBudgetMb(memoryBudgetMb)){writeStderrLine(memoryBudgetRangeError());process.exit(1)}const maxPendingPromptsPerSession=argv["max-pending-prompts-per-session"];if(maxPendingPromptsPerSession!==Number.POSITIVE_INFINITY&&(!Number.isFinite(maxPendingPromptsPerSession)||!Number.isInteger(maxPendingPromptsPerSession)||maxPendingPromptsPerSession<0)){writeStderrLine("qwen serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited).");process.exit(1)}if(mcpClientBudget!==void 0){writeStderrLine(`qwen serve: --mcp-client-budget=${mcpClientBudget} mode=${resolvedMcpMode}`+(resolvedMcpMode==="enforce"?" (servers past the cap will be refused at discovery)":resolvedMcpMode==="warn"?` (warnings at >=${Math.ceil(mcpClientBudget*MCP_BUDGET_WARN_FRACTION)}, no refusal)`:""))}try{const loaded=loadSettings(primaryWorkspaceArg(argv.workspace)??process.cwd());const merged=loaded.merged;const approvalMode=merged.tools?.approvalMode;const sandbox=merged.tools?.sandbox;const sandboxEnv=process.env["SANDBOX"];const suppress=process.env["QWEN_CODE_SUPPRESS_YOLO_WARNING"];const suppressed=suppress==="1"||suppress==="true";if(approvalMode==="yolo"&&!sandbox&&!sandboxEnv&&!suppressed){writeStderrLine(HEADLESS_YOLO_NO_SANDBOX_WARNING)}}catch{}const rateLimit=argv["rate-limit"]??(process.env["QWEN_SERVE_RATE_LIMIT"]==="1"||process.env["QWEN_SERVE_RATE_LIMIT"]==="true");let rateLimitPrompt;let rateLimitMutation;let rateLimitRead;let rateLimitWindowMs;if(rateLimit){const envInt=__name(key=>{const raw=process.env[key];if(raw===void 0||raw==="")return void 0;return parsePositiveIntegerEnv(raw,Number.NaN)},"envInt");rateLimitPrompt=argv["rate-limit-prompt"]??envInt("QWEN_SERVE_RATE_LIMIT_PROMPT");rateLimitMutation=argv["rate-limit-mutation"]??envInt("QWEN_SERVE_RATE_LIMIT_MUTATION");rateLimitRead=argv["rate-limit-read"]??envInt("QWEN_SERVE_RATE_LIMIT_READ");rateLimitWindowMs=argv["rate-limit-window-ms"]??envInt("QWEN_SERVE_RATE_LIMIT_WINDOW_MS");for(const[name,value]of[["--rate-limit-prompt",rateLimitPrompt],["--rate-limit-mutation",rateLimitMutation],["--rate-limit-read",rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){writeStderrLine(`qwen serve: ${name} must be a positive integer.`);process.exit(1)}}if(rateLimitWindowMs!==void 0&&(!Number.isFinite(rateLimitWindowMs)||!Number.isInteger(rateLimitWindowMs)||rateLimitWindowMs<1e3)){writeStderrLine("qwen serve: --rate-limit-window-ms must be an integer >= 1000.");process.exit(1)}}const externalToolGuardToken=process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV]??"";delete process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV];const openWithAuth=argv["open-with-auth"];const open=argv.open||openWithAuth;const{runQwenServe}=await import("./run-qwen-serve-WW74NSUL.js");try{const serveOptions={port:argv.port,hostname:argv.hostname,profile:argv.profile,token:argv.token,mode:"http-bridge",maxSessions:argv["max-sessions"],...argv["max-total-sessions"]!==void 0?{maxTotalSessions:argv["max-total-sessions"]}:{},maxPendingPromptsPerSession,maxConnections:argv["max-connections"],eventRingSize:argv["event-ring-size"],compactedReplayMaxBytes:argv["compacted-replay-max-bytes"],...argv["max-journal-events"]!==void 0?{maxJournalEvents:argv["max-journal-events"]}:{},...argv["max-journal-bytes"]!==void 0?{maxJournalBytes:argv["max-journal-bytes"]}:{},workspace:argv.workspace,...argv["memory-project-scope"]!==void 0?{memoryProjectScope:argv["memory-project-scope"]}:{},requireAuth:argv["require-auth"],enableSessionShell:argv["enable-session-shell"],serveWebShell:argv.web,...argv["token-qr"]!==void 0?{tokenQr:argv["token-qr"]}:{},...argv["tls-cert"]!==void 0?{tlsCert:argv["tls-cert"]}:{},...argv["tls-key"]!==void 0?{tlsKey:argv["tls-key"]}:{},allowPrivateAuthBaseUrl:argv["allow-private-auth-base-url"],mcpClientBudget,mcpBudgetMode:resolvedMcpMode,...memoryBudgetMb!==void 0?{memoryBudgetMb}:{},memoryPressureMode:argv["memory-pressure-mode"],childHeapMode:argv["child-heap-mode"],...argv["allow-origin"]&&argv["allow-origin"].length>0?{allowOrigins:argv["allow-origin"]}:{},...argv["prompt-deadline-ms"]!==void 0?{promptDeadlineMs:argv["prompt-deadline-ms"]}:{},...argv["experimental-paired-engines"]?{experimentalPairedEngines:true}:{},...argv["experimental-managed-agents"]?{experimentalManagedAgents:true}:{},...argv["experimental-managed-runtime-auto-local"]?{experimentalManagedRuntimeAutoLocal:true}:{},...argv["experimental-managed-runtime-worker"]?{experimentalManagedRuntimeWorker:true}:{},...argv["experimental-managed-runtime-url"]!==void 0?{experimentalManagedRuntimeUrl:argv["experimental-managed-runtime-url"]}:{},...argv["experimental-managed-runtime-token"]!==void 0?{experimentalManagedRuntimeToken:argv["experimental-managed-runtime-token"]}:{},...argv["managed-runtime-broker-url"]!==void 0?{managedRuntimeBrokerUrl:argv["managed-runtime-broker-url"]}:{},...argv["managed-runtime-broker-token"]!==void 0?{managedRuntimeBrokerToken:argv["managed-runtime-broker-token"]}:{},...argv["hosted-harness-capability-digest"]!==void 0?{hostedHarnessCapabilityDigest:argv["hosted-harness-capability-digest"]}:{},...argv["writer-idle-timeout-ms"]!==void 0?{writerIdleTimeoutMs:argv["writer-idle-timeout-ms"]}:{},...argv["channel-idle-timeout-ms"]!==void 0?{channelIdleTimeoutMs:argv["channel-idle-timeout-ms"]}:{},...argv["initialize-timeout-ms"]!==void 0?{initializeTimeoutMs:argv["initialize-timeout-ms"]}:{},...argv["session-restore-timeout-ms"]!==void 0?{sessionRestoreTimeoutMs:argv["session-restore-timeout-ms"]}:{},...argv["session-reap-interval-ms"]!==void 0?{sessionReapIntervalMs:argv["session-reap-interval-ms"]}:{},...argv["session-idle-timeout-ms"]!==void 0?{sessionIdleTimeoutMs:argv["session-idle-timeout-ms"]}:{},...argv["session-prompt-settled-close-grace-ms"]!==void 0?{sessionPromptSettledCloseGraceMs:argv["session-prompt-settled-close-grace-ms"]}:{},...argv["permission-response-timeout-ms"]!==void 0?{permissionResponseTimeoutMs:argv["permission-response-timeout-ms"]}:{},...argv["external-tool-guard-mode"]==="required"?{externalToolGuard:{mode:"required",endpoint:argv["external-tool-guard-endpoint"]??"",token:externalToolGuardToken,...argv["external-tool-guard-timeout-ms"]!==void 0?{timeoutMs:argv["external-tool-guard-timeout-ms"]}:{}}}:{},...rateLimit?{rateLimit:true}:{},...rateLimitPrompt!==void 0?{rateLimitPrompt}:{},...rateLimitMutation!==void 0?{rateLimitMutation}:{},...rateLimitRead!==void 0?{rateLimitRead}:{},...rateLimitWindowMs!==void 0?{rateLimitWindowMs}:{},...argv.experimentalLsp===true?{experimentalLsp:true}:{},...argv.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},...channelSelection!==void 0?{channelSelection}:{}};if(openWithAuth){const{applyOpenWithAuth}=await import("./open-with-auth-KXZ7DU2D.js");applyOpenWithAuth(serveOptions)}const handle=await runQwenServe(serveOptions,{updateRestartArgv:process.argv.slice(2)});const joined=argv["join"]?parseJoinLink(argv["join"]):void 0;const hostTarget=joined?{...joined,token:agentHostEnrollmentToken}:argv["agent-host-server"]&&argv["agent-host-workspace-id"]?{serverUrl:argv["agent-host-server"],workspaceId:argv["agent-host-workspace-id"],token:agentHostEnrollmentToken}:void 0;if(hostTarget){try{await handle.runtimeReady;const runtime=handle.getPrimaryWorkspaceRuntime();if(!runtime?.trusted||!runtime.generationGuard||runtime.generationGuard.closed){throw new Error("Agent Host join requires a trusted active workspace.")}const{startAgentHostConnection}=await import("./agent-host-client-OW4HBXRL.js");await startAgentHostConnection({bridge:runtime.bridge,serverUrl:hostTarget.serverUrl,workspaceId:hostTarget.workspaceId,workspaceCwd:runtime.workspaceCwd,allowHttp:argv["agent-host-allow-http"]===true,generationGuard:runtime.generationGuard,...hostTarget.token?{enrollmentToken:hostTarget.token}:{},...argv["agent-host-name"]?{name:argv["agent-host-name"]}:{}})}catch(error){await handle.close().catch(()=>void 0);throw error}}if(argv["local-control"]){try{await startLocalControl(handle,argv["local-control-address"])}catch(err){await handle.close().catch(()=>void 0);throw err}}await maybeOpenWebShellBrowser(handle,open,openWithAuth)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}await blockForever()},"handler")};export{parseJoinLink,maybeOpenWebShellBrowser,serveCommand};
3
+ import{HEADLESS_YOLO_NO_SANDBOX_WARNING}from"./chunk-Z57KDB5F.js";import{DEFAULT_RING_SIZE}from"./chunk-EDCAX2GY.js";import{DEFAULT_COMPACTED_REPLAY_MAX_BYTES,DEFAULT_MAX_JOURNAL_BYTES,DEFAULT_MAX_JOURNAL_EVENTS,JOURNAL_GROWTH_HARD_CAP_BYTES}from"./chunk-WDR5XP3Y.js";import{JOURNAL_GROWTH_POOL_FRACTION,MAX_JOURNAL_GROWTH_POOL_MB,MIN_MEMORY_BUDGET_MB,isValidMemoryBudgetMb,memoryBudgetRangeError}from"./chunk-2QYDBHYZ.js";import{normalizeServeChannelSelection}from"./chunk-KOJ7WZ63.js";import{EXTERNAL_TOOL_GUARD_TOKEN_ENV}from"./chunk-NIEO2TBE.js";import{loadSettings}from"./chunk-4WFWZWR3.js";import{MCP_BUDGET_WARN_FRACTION}from"./chunk-IFAUFERF.js";import{parsePositiveIntegerEnv}from"./chunk-BG67XABA.js";import{openBrowserSecurely,shouldLaunchBrowser}from"./chunk-3YWXKSOI.js";import{MEMORY_PROJECT_SCOPES}from"./chunk-PWOQASXT.js";import{writeStderrLine,writeStdoutLine}from"./chunk-SLPJ4OII.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();var SEGMENT=/^[A-Za-z0-9_-]{1,256}$/;function parseJoinLink(link){let url;try{url=new URL(link.trim())}catch{throw new Error("--join expects the link shown by the coordinator.")}const marker=url.pathname.lastIndexOf("/join/");const[workspaceId,...rest]=marker>=0?url.pathname.slice(marker+"/join/".length).split("/"):[];if(url.protocol!=="http:"&&url.protocol!=="https:"||url.username||url.password||url.search||url.hash||!workspaceId||rest.some(Boolean)||!SEGMENT.test(workspaceId)){throw new Error("--join expects a link like https://host:4170/join/<workspace>.")}const base=url.pathname.slice(0,marker).replace(/\/+$/,"");return{serverUrl:`${url.origin}${base}`,workspaceId}}__name(parseJoinLink,"parseJoinLink");function blockForever(){return new Promise(()=>{})}__name(blockForever,"blockForever");var DEFAULT_SERVE_HOSTNAME="127.0.0.1";async function startLocalControl(handle,address){await handle.runtimeReady;if(!handle.webShellMounted){throw new Error("Local Control requires the Web Shell.")}const service=handle.getLocalControl();if(!service){throw new Error("Local Control is unavailable on this daemon.")}let status;try{status=await service.enable(address?{address}:{})}catch(err){if(err instanceof Error&&err.code==="ambiguous_lan_interface"){throw new Error(`${err.message}. Pass --local-control-address <ip>.`)}throw err}if(!status.url){throw new Error("Local Control did not return a pairing URL.")}const{default:qrcode}=await import("./main-5IVKRF6Q.js");qrcode.setErrorLevel("Q");writeStdoutLine("\nLocal Control is on. Scan this QR code from the same network:");writeStdoutLine(`
4
+ ${status.interfaceName}: ${status.url}`);qrcode.generate(status.url,{small:true},code=>{writeStdoutLine(code.trimEnd())});writeStdoutLine("\nKeep this terminal open. "+(status.sleepInhibited?"Sleep is inhibited while this session is active. ":"Sleep inhibition is unavailable here, so the host may sleep. ")+(status.encrypted?"Traffic is encrypted.":"Traffic is unencrypted \u2014 use it only on a network you trust.")+" Turn Local Control off from the Web Shell Settings card, or press Ctrl+C to exit the daemon.")}__name(startLocalControl,"startLocalControl");async function maybeOpenWebShellBrowser(handle,open,manualFallbackWhenIneligible=false){if(!open||!handle.webShellMounted)return;const shouldLaunch=shouldLaunchBrowser();if(!shouldLaunch&&!manualFallbackWhenIneligible)return;try{await handle.runtimeReady}catch(runtimeErr){writeStderrLine(`qwen serve: Web Shell runtime not ready; skipping --open: ${runtimeErr instanceof Error?runtimeErr.message:String(runtimeErr)}`);return}let target;try{target=new URL(handle.url);if(target.hostname==="0.0.0.0"||target.hostname==="[::]"){target.hostname="127.0.0.1"}if(handle.resolvedToken){target.hash=`token=${encodeURIComponent(handle.resolvedToken)}`}if(!shouldLaunch){writeStderrLine(`Browser launch is not available in this environment. Please open this URL manually: ${target.toString()}`);return}if(handle.resolvedToken){writeStderrLine("qwen serve: --open passes the token in the browser launch command (visible via `ps` / /proc); on a multi-user host open the URL manually instead.")}await openBrowserSecurely(target.toString())}catch(browserErr){const manualUrl=manualFallbackWhenIneligible&&target?`. Please open this URL manually: ${target.toString()}`:"";writeStderrLine(`qwen serve: failed to open browser: ${browserErr instanceof Error?browserErr.message:String(browserErr)}${manualUrl}`)}}__name(maybeOpenWebShellBrowser,"maybeOpenWebShellBrowser");function primaryWorkspaceArg(workspace){return Array.isArray(workspace)?workspace[0]:workspace}__name(primaryWorkspaceArg,"primaryWorkspaceArg");var serveCommand={command:"serve",describe:"Run Qwen Code as a local HTTP daemon (Stage 1 experimental: --http-bridge)",builder:__name(yargs=>yargs.option("port",{type:"number",default:4170,description:"TCP port to bind (use 0 for an OS-assigned ephemeral port)"}).option("hostname",{type:"string",default:DEFAULT_SERVE_HOSTNAME,description:"Interface to bind. Loopback (127.0.0.0/8, localhost, ::1, [::1]) is auth-free; anything else requires a token (one is generated and printed when neither --token nor QWEN_SERVER_TOKEN supplies one). A localhost bind that resolves off-loopback never generates, and still refuses when no token source resolved; an empty value is rejected as operator error."}).option("profile",{choices:["default","hosted-harness"],default:"default",description:"Deployment profile. hosted-harness enables the private no-tool Managed Session API on loopback."}).option("hosted-harness-capability-digest",{type:"string",description:"SHA-256 capability digest for the private Hosted Harness profile. Falls back to QWEN_HOSTED_HARNESS_CAPABILITY_DIGEST."}).option("token",{type:"string",description:"Bearer token required on every request. Falls back to the QWEN_SERVER_TOKEN env var; a non-loopback bind with neither generates an ephemeral token at startup, while loopback keeps the trusted tokenless mode unless --require-auth is set."}).option("max-sessions",{type:"number",default:32,description:"Cap on concurrent live sessions. New spawn requests beyond this return 503; attach to existing sessions still works. Set to 0 to disable."}).option("max-total-sessions",{type:"number",description:"Non-negative integer cap on concurrent live sessions across all workspace runtimes. Set to 0 to disable."}).option("max-pending-prompts-per-session",{type:"number",default:5,description:"Per-session cap on accepted prompts waiting or running. New prompts beyond this return 503. Set to 0 to disable."}).option("workspace",{type:"string",array:true,requiresArg:true,description:"Absolute workspace path to register with this daemon. POST /session requests with a mismatched cwd return 400 workspace_mismatch. Defaults to process.cwd() when omitted. Repeat to register isolated workspace runtimes; the first is primary."}).option("memory-project-scope",{type:"string",choices:MEMORY_PROJECT_SCOPES,description:'Choose how project memory is partitioned. Defaults to "workspace" so each daemon workspace stays isolated; "git-root" preserves the legacy shared scope. Overrides QWEN_CODE_MEMORY_PROJECT_SCOPE when provided.'}).option("max-connections",{type:"number",default:256,description:"Listener-level TCP connection cap (server.maxConnections). Bounds raw sockets \u2014 slow/phantom SSE clients get rejected at accept time once full. Set to 0 to disable."}).option("require-auth",{type:"boolean",default:false,description:"Refuse to start without a bearer token, even on loopback. Hardens the loopback developer default for shared dev hosts / CI runners / multi-tenant workstations where any local user can hit 127.0.0.1. Requires --token, QWEN_SERVER_TOKEN, or --open-with-auth (which installs its own generated loopback token); on non-loopback binds the generated ephemeral token also satisfies it, so the no-configured-secret fail-fast is loopback-only. /health also requires Authorization when enabled (no loopback exemption \u2014 k8s/Compose probes must pass the bearer too)."}).option("enable-session-shell",{type:"boolean",default:false,description:"Enable direct POST /session/:id/shell execution. Available with bearer auth or trusted loopback; each call still requires a session-bound client id."}).option("tls-cert",{type:"string",description:"Path to a PEM certificate file. Serve over HTTPS instead of HTTP. Required for secure-context browser APIs (voice input/getUserMedia, WebRTC) when accessed over a LAN IP. Must be used together with --tls-key. Generate a local cert with mkcert."}).option("tls-key",{type:"string",description:"Path to a PEM private key file. Must be used together with --tls-cert."}).option("experimental-lsp",{type:"boolean",default:false,description:"Forward the experimental LSP opt-in to spawned agent sessions."}).option("restore-ask-user-question",{type:"boolean",default:false,description:"On session load/resume, re-hang a trailing unanswered ask_user_question instead of synthesizing a failed tool result."}).option("channel",{type:"string",array:true,description:"Experimental: start a daemon-managed channel worker for the named channel. Repeat to select multiple channels, or use --channel all."}).option("web",{type:"boolean",default:true,description:"Serve the Web Shell UI at the daemon root path. Use --no-web for an API-only daemon."}).option("open",{type:"boolean",default:false,description:"Open the Web Shell in a browser once the daemon is listening. With a token configured, the launch URL (token included) is handed to the browser launcher and is visible in the process list, so prefer opening the URL manually on multi-user hosts. No-op with --no-web, when the UI assets are absent, or in headless/CI/SSH environments."}).option("open-with-auth",{type:"boolean",default:false,description:"Open the Web Shell with bearer authentication on loopback. Reuse --token or QWEN_SERVER_TOKEN, or generate a temporary 256-bit token and deliver it in the URL fragment. In headless environments, print the fragment URL for manual opening."}).option("token-qr",{type:"boolean",description:"Print the token-bearing QR even when stdout is captured (not an interactive terminal) and the bearer is an operator-supplied (stable) token, which is withheld by default to keep stable credentials out of collected logs. Enable only when the log pipeline is as trusted as the daemon host. Can also be set via the serve.tokenQr setting (user, system, and system-defaults scopes only); the flag wins when passed. --no-token-qr suppresses the startup quickstart token QR for that run on every quickstart path \u2014 interactive terminal and generated token included. It does not govern the Local Control pairing QR, which --local-control prints by design."}).option("local-control",{type:"boolean",default:false,description:"Share the Web Shell on the local IPv4 network with its own revocable pairing token, terminal QR code, and best-effort sleep inhibition. Ctrl+C turns it off by ending the whole daemon; the Web Shell Settings card turns it off while the daemon keeps running."}).option("local-control-address",{type:"string",description:"Which local IPv4 address to share when the host is on more than one network. Only needed if --local-control reports an ambiguous choice."}).option("join",{type:"string",description:"Join another Qwen Code as a runtime, with the one-line link it shows under Agent \u2192 Runtime \u2192 Add runtime."}).option("agent-host-server",{type:"string",description:"Register this daemon as an Agent Host with a primary Qwen daemon."}).option("agent-host-workspace-id",{type:"string",description:"Control-plane workspace id printed by the primary daemon."}).option("agent-host-name",{type:"string",description:"Display name advertised for this Agent Host."}).option("agent-host-allow-http",{type:"boolean",default:false,description:"Allow unencrypted Agent Host HTTP connections outside loopback (trusted demo networks only)."}).check(argv=>{if(argv["local-control"]===true&&argv["web"]===false){throw new Error("Local Control requires the Web Shell.")}if(argv["local-control"]===true&&argv.hostname!==DEFAULT_SERVE_HOSTNAME){throw new Error(`Local Control requires --hostname ${DEFAULT_SERVE_HOSTNAME}.`)}if(argv["local-control"]!==true&&argv["local-control-address"]!==void 0){throw new Error("--local-control-address requires --local-control.")}if(argv["local-control-address"]===""){throw new Error("--local-control-address must not be empty.")}if(Boolean(argv["agent-host-server"])!==Boolean(argv["agent-host-workspace-id"])){throw new Error("--agent-host-server and --agent-host-workspace-id must be used together.")}if(argv["agent-host-name"]===""){throw new Error("--agent-host-name must not be empty.")}if(argv["join"]!==void 0){if(argv["agent-host-server"]||argv["agent-host-workspace-id"]){throw new Error("--join already names the coordinator and workspace; drop --agent-host-server and --agent-host-workspace-id.")}parseJoinLink(argv["join"])}return true}).option("event-ring-size",{type:"number",default:DEFAULT_RING_SIZE,description:"Per-session SSE replay ring depth. Sets the replay backlog available to `GET /session/:id/events` reconnects that send a `Last-Event-ID: N` header. Larger = more reconnect headroom at the cost of a few hundred KB extra RAM per session. Must be a positive finite integer."}).option("compacted-replay-max-bytes",{type:"number",default:DEFAULT_COMPACTED_REPLAY_MAX_BYTES,description:"Per-session in-memory compacted replay snapshot byte cap for `POST /session/:id/load` late attaches. Larger = more recent history in load snapshots at higher heap cost. Must be a positive safe integer no larger than 256 MiB."}).option("max-journal-events",{type:"number",nargs:1,description:"Per-session baseline cap on replay entries retained in the in-flight live journal (current unfinished turn). Compatible text/thought chunks share bounded entries. When exceeded, the daemon first tries adaptive growth (see --max-journal-bytes); without granted headroom the oldest entries are dropped. Pinning this flag (or --max-journal-bytes) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_EVENTS+" when unset. Must be a positive safe integer."}).option("max-journal-bytes",{type:"number",nargs:1,description:"Per-session baseline source-event byte cap on the in-flight live journal. When a turn outgrows it, adaptive growth raises the session's caps (per-session hard cap "+JOURNAL_GROWTH_HARD_CAP_BYTES/(1024*1024)+" MiB) within a growth pool derived from the daemon memory budget (see --memory-budget-mb); without granted headroom the oldest entries are dropped whole (at least one is always kept), so the retained tail can be much smaller than the cap. Pinning this flag (or --max-journal-events) disables adaptive growth. Defaults to "+DEFAULT_MAX_JOURNAL_BYTES+" bytes when unset. Must be a positive safe integer."}).option("http-bridge",{type:"boolean",default:true,description:"HTTP bridge mode: attempt to preheat the primary `qwen --acp` child; trusted secondaries start one on demand. Stage 2 native in-process mode is not yet implemented; this flag will become opt-in then."}).option("memory-budget-mb",{type:"number",description:"Total memory budget in MB for the daemon process tree. When unset, derived as 50% of cgroup-constrained or host memory, and capped at the resolved available memory either way. In `admit` and `enforce` modes it determines managed ACP child capacity; `enforce` also applies the modeled per-child old-space ceiling. It also sizes one daemon-wide pool of "+JOURNAL_GROWTH_POOL_FRACTION*100+"% of the effective budget (capped at "+MAX_JOURNAL_GROWTH_POOL_MB+" MB; 0, growth disabled, when the effective budget falls below the "+MIN_MEMORY_BUDGET_MB+" MB minimum; see --max-journal-bytes). Reported under `limits.memory` in daemon status, alongside a modeled per-child partition under `limits.memory.childHeap`. Must be an integer in [1024, 1048576]."}).option("memory-pressure-mode",{choices:["off","observe"],default:"observe",description:"Whether the daemon derives a memory-pressure level from its own RSS and V8 heap. `observe` (default) reports the level in daemon status and raises a status issue when it leaves normal. `off` still reports the underlying figures but raises no issue, so the overall status rollup is unchanged \u2014 use it while calibrating, or if you alert on the top-level status. Nothing remediates in either mode."}).option("child-heap-mode",{choices:["off","observe","admit","enforce"],default:"observe",description:"Whether the daemon models a per-child heap partition of the memory budget. `observe` (default) reports the partition it would apply \u2014 `limits.memory.childHeap.perChildCeilingMb` and `maxConcurrentChildren` \u2014 and counts spawns that would have exceeded it. Nothing is applied: no child is sized from the budget and no spawn is refused. `off` models nothing. Note a refusal count of 0 does NOT mean the partition would be safe to apply; children still run on the much larger host-derived ceiling, so a workload needing more old space than the modeled ceiling looks healthy here. `admit` rejects starts past the modeled process limit but keeps the existing child heap arguments. Experimental `enforce` also applies the fixed modeled old-space ceiling to each managed child; it does not cap total process RSS."}).option("mcp-client-budget",{type:"number",description:"Cap on live MCP clients spawned inside the ACP child for the bound workspace. Positive integer. Combine with --mcp-budget-mode to control behavior at the cap. When unset, mode defaults to off (no accounting-driven enforcement, but GET /workspace/mcp still reports `clientCount`). Distinct from claude-code MCP_SERVER_CONNECTION_BATCH_SIZE which gates startup concurrency, not the total client count."}).option("mcp-budget-mode",{choices:["enforce","warn","off"],description:'How --mcp-client-budget is enforced. `warn` (default when budget set): no refusal, snapshot surfaces warning at >=75% of budget. `enforce`: connects past the cap are refused (`disabledReason: "budget"`, deterministic by mcpServers declaration order). `off`: pure observability. Boot rejects `enforce` without a budget.'}).option("allow-origin",{type:"string",array:true,description:"Cross-origin allowlist for browser clients."}).option("allow-private-auth-base-url",{type:"boolean",default:false,description:"Allow /workspace/auth/provider to install localhost/private-network baseUrl values. Use only for local development with trusted clients."}).option("prompt-deadline-ms",{type:"number",description:"Server-side wallclock cap on POST /session/:id/prompt (ms). Falls back to QWEN_SERVE_PROMPT_DEADLINE_MS. Positive integer."}).option("experimental-paired-engines",{type:"boolean",default:false,description:"Experimental: build workspace runtimes, other than the private Conversations one, with paired Legacy and Managed engines. No Managed engine is available yet, so sessions run on Legacy with a durable owner."}).option("experimental-managed-agents",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-worker",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-auto-local",{type:"boolean",default:false,description:"Reserved experimental mode; not implemented and rejects startup."}).option("experimental-managed-runtime-url",{type:"string",requiresArg:true,description:"Reserved experimental Runtime URL; not implemented and rejects startup."}).option("experimental-managed-runtime-token",{type:"string",requiresArg:true,description:"Reserved experimental Runtime credential; not implemented and rejects startup."}).option("managed-runtime-broker-url",{type:"string",requiresArg:true,description:"Private Broker URL for --profile hosted-harness; required together with token for Workspace tool turns."}).option("managed-runtime-broker-token",{type:"string",requiresArg:true,description:"Private Broker credential for --profile hosted-harness; required together with URL for Workspace tool turns."}).option("writer-idle-timeout-ms",{type:"number",description:"Per-SSE-connection idle deadline (ms). Falls back to QWEN_SERVE_WRITER_IDLE_TIMEOUT_MS. Positive integer."}).option("channel-idle-timeout-ms",{type:"number",description:"Compatibility auto-reap delay for an idle workspace ACP child. 0 or unset = reap after work drains; keepalive windows may extend it (default)."}).option("initialize-timeout-ms",{type:"number",description:"ACP child request timeout, including the initialize handshake (ms). Default: 10000 (10 s)."}).option("session-restore-timeout-ms",{type:"number",description:"ACP session load/resume timeout (ms). Default: 60000. An explicit --initialize-timeout-ms can raise (but never lower) this default."}).option("session-reap-interval-ms",{type:"number",description:"Session reaper scan interval (ms). 0 = disabled. Default: 60000."}).option("session-idle-timeout-ms",{type:"number",description:"Idle timeout before a disconnected session is reaped (ms). 0 = disabled. Default: 1800000 (30 min)."}).option("session-prompt-settled-close-grace-ms",{type:"number",description:"Grace period after a prompt settles before an otherwise-idle session may be auto-closed (ms). Poll-based SSE clients use this window to reconnect without triggering a session rebuild. 0 = disabled (immediate close). Default: 0."}).option("permission-response-timeout-ms",{type:"number",description:"Wall-clock timeout for a human permission / ask_user_question response in daemon (ACP) mode (ms). 0 or unset = disabled (wait indefinitely). Default: 0."}).option("external-tool-guard-mode",{choices:["off","required"],default:"off",description:"Managed ACP pre-execution policy mode. Default off preserves current CLI and daemon behavior. Required fails startup unless a compatible loopback provider is available."}).option("external-tool-guard-endpoint",{type:"string",description:"Origin-only loopback HTTP(S) endpoint for required external tool guarding, for example http://127.0.0.1:8787."}).option("external-tool-guard-timeout-ms",{type:"number",description:"Per-handshake/prepare external tool guard timeout in milliseconds. Default: 3000."}).option("rate-limit",{type:"boolean",description:"Enable per-tier HTTP rate limiting. Tiers: prompt (10/min), mutation (30/min), read (120/min). Health, heartbeat, SSE, and /acp are exempt."}).option("rate-limit-prompt",{type:"number",description:"Max prompt requests per window per client (default 10). Requires --rate-limit."}).option("rate-limit-mutation",{type:"number",description:"Max mutation requests per window per client (default 30). Requires --rate-limit."}).option("rate-limit-read",{type:"number",description:"Max read requests per window per client (default 120). Requires --rate-limit."}).option("rate-limit-window-ms",{type:"number",description:"Rate limit window duration in ms (default 60000). Requires --rate-limit."}),"builder"),handler:__name(async argv=>{const agentHostEnrollmentToken=process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"]?.trim();delete process.env["QWEN_AGENT_HOST_ENROLLMENT_TOKEN"];if(!argv["http-bridge"]){writeStderrLine("qwen serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge.")}if(argv.token){writeStderrLine("qwen serve: --token is visible in the process command line; prefer the QWEN_SERVER_TOKEN env var for any non-trivial deployment.")}let channelSelection;try{channelSelection=normalizeServeChannelSelection(argv.channel)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}const mcpClientBudget=argv["mcp-client-budget"];const mcpBudgetMode=argv["mcp-budget-mode"];if(mcpClientBudget!==void 0){if(!Number.isFinite(mcpClientBudget)||!Number.isInteger(mcpClientBudget)||mcpClientBudget<=0){writeStderrLine("qwen serve: --mcp-client-budget must be a positive integer.");process.exit(1)}}if(mcpBudgetMode==="enforce"&&mcpClientBudget===void 0){writeStderrLine("qwen serve: --mcp-budget-mode=enforce requires --mcp-client-budget=N.");process.exit(1)}const resolvedMcpMode=mcpBudgetMode??(mcpClientBudget!==void 0?"warn":"off");const memoryBudgetMb=argv["memory-budget-mb"];if(memoryBudgetMb!==void 0&&!isValidMemoryBudgetMb(memoryBudgetMb)){writeStderrLine(memoryBudgetRangeError());process.exit(1)}const maxPendingPromptsPerSession=argv["max-pending-prompts-per-session"];if(maxPendingPromptsPerSession!==Number.POSITIVE_INFINITY&&(!Number.isFinite(maxPendingPromptsPerSession)||!Number.isInteger(maxPendingPromptsPerSession)||maxPendingPromptsPerSession<0)){writeStderrLine("qwen serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited).");process.exit(1)}if(mcpClientBudget!==void 0){writeStderrLine(`qwen serve: --mcp-client-budget=${mcpClientBudget} mode=${resolvedMcpMode}`+(resolvedMcpMode==="enforce"?" (servers past the cap will be refused at discovery)":resolvedMcpMode==="warn"?` (warnings at >=${Math.ceil(mcpClientBudget*MCP_BUDGET_WARN_FRACTION)}, no refusal)`:""))}try{const loaded=loadSettings(primaryWorkspaceArg(argv.workspace)??process.cwd());const merged=loaded.merged;const approvalMode=merged.tools?.approvalMode;const sandbox=merged.tools?.sandbox;const sandboxEnv=process.env["SANDBOX"];const suppress=process.env["QWEN_CODE_SUPPRESS_YOLO_WARNING"];const suppressed=suppress==="1"||suppress==="true";if(approvalMode==="yolo"&&!sandbox&&!sandboxEnv&&!suppressed){writeStderrLine(HEADLESS_YOLO_NO_SANDBOX_WARNING)}}catch{}const rateLimit=argv["rate-limit"]??(process.env["QWEN_SERVE_RATE_LIMIT"]==="1"||process.env["QWEN_SERVE_RATE_LIMIT"]==="true");let rateLimitPrompt;let rateLimitMutation;let rateLimitRead;let rateLimitWindowMs;if(rateLimit){const envInt=__name(key=>{const raw=process.env[key];if(raw===void 0||raw==="")return void 0;return parsePositiveIntegerEnv(raw,Number.NaN)},"envInt");rateLimitPrompt=argv["rate-limit-prompt"]??envInt("QWEN_SERVE_RATE_LIMIT_PROMPT");rateLimitMutation=argv["rate-limit-mutation"]??envInt("QWEN_SERVE_RATE_LIMIT_MUTATION");rateLimitRead=argv["rate-limit-read"]??envInt("QWEN_SERVE_RATE_LIMIT_READ");rateLimitWindowMs=argv["rate-limit-window-ms"]??envInt("QWEN_SERVE_RATE_LIMIT_WINDOW_MS");for(const[name,value]of[["--rate-limit-prompt",rateLimitPrompt],["--rate-limit-mutation",rateLimitMutation],["--rate-limit-read",rateLimitRead]]){if(value!==void 0&&(!Number.isFinite(value)||!Number.isInteger(value)||value<=0)){writeStderrLine(`qwen serve: ${name} must be a positive integer.`);process.exit(1)}}if(rateLimitWindowMs!==void 0&&(!Number.isFinite(rateLimitWindowMs)||!Number.isInteger(rateLimitWindowMs)||rateLimitWindowMs<1e3)){writeStderrLine("qwen serve: --rate-limit-window-ms must be an integer >= 1000.");process.exit(1)}}const externalToolGuardToken=process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV]??"";delete process.env[EXTERNAL_TOOL_GUARD_TOKEN_ENV];const openWithAuth=argv["open-with-auth"];const open=argv.open||openWithAuth;const{runQwenServe}=await import("./run-qwen-serve-NFPGPJJ2.js");try{const serveOptions={port:argv.port,hostname:argv.hostname,profile:argv.profile,token:argv.token,mode:"http-bridge",maxSessions:argv["max-sessions"],...argv["max-total-sessions"]!==void 0?{maxTotalSessions:argv["max-total-sessions"]}:{},maxPendingPromptsPerSession,maxConnections:argv["max-connections"],eventRingSize:argv["event-ring-size"],compactedReplayMaxBytes:argv["compacted-replay-max-bytes"],...argv["max-journal-events"]!==void 0?{maxJournalEvents:argv["max-journal-events"]}:{},...argv["max-journal-bytes"]!==void 0?{maxJournalBytes:argv["max-journal-bytes"]}:{},workspace:argv.workspace,...argv["memory-project-scope"]!==void 0?{memoryProjectScope:argv["memory-project-scope"]}:{},requireAuth:argv["require-auth"],enableSessionShell:argv["enable-session-shell"],serveWebShell:argv.web,...argv["token-qr"]!==void 0?{tokenQr:argv["token-qr"]}:{},...argv["tls-cert"]!==void 0?{tlsCert:argv["tls-cert"]}:{},...argv["tls-key"]!==void 0?{tlsKey:argv["tls-key"]}:{},allowPrivateAuthBaseUrl:argv["allow-private-auth-base-url"],mcpClientBudget,mcpBudgetMode:resolvedMcpMode,...memoryBudgetMb!==void 0?{memoryBudgetMb}:{},memoryPressureMode:argv["memory-pressure-mode"],childHeapMode:argv["child-heap-mode"],...argv["allow-origin"]&&argv["allow-origin"].length>0?{allowOrigins:argv["allow-origin"]}:{},...argv["prompt-deadline-ms"]!==void 0?{promptDeadlineMs:argv["prompt-deadline-ms"]}:{},...argv["experimental-paired-engines"]?{experimentalPairedEngines:true}:{},...argv["experimental-managed-agents"]?{experimentalManagedAgents:true}:{},...argv["experimental-managed-runtime-auto-local"]?{experimentalManagedRuntimeAutoLocal:true}:{},...argv["experimental-managed-runtime-worker"]?{experimentalManagedRuntimeWorker:true}:{},...argv["experimental-managed-runtime-url"]!==void 0?{experimentalManagedRuntimeUrl:argv["experimental-managed-runtime-url"]}:{},...argv["experimental-managed-runtime-token"]!==void 0?{experimentalManagedRuntimeToken:argv["experimental-managed-runtime-token"]}:{},...argv["managed-runtime-broker-url"]!==void 0?{managedRuntimeBrokerUrl:argv["managed-runtime-broker-url"]}:{},...argv["managed-runtime-broker-token"]!==void 0?{managedRuntimeBrokerToken:argv["managed-runtime-broker-token"]}:{},...argv["hosted-harness-capability-digest"]!==void 0?{hostedHarnessCapabilityDigest:argv["hosted-harness-capability-digest"]}:{},...argv["writer-idle-timeout-ms"]!==void 0?{writerIdleTimeoutMs:argv["writer-idle-timeout-ms"]}:{},...argv["channel-idle-timeout-ms"]!==void 0?{channelIdleTimeoutMs:argv["channel-idle-timeout-ms"]}:{},...argv["initialize-timeout-ms"]!==void 0?{initializeTimeoutMs:argv["initialize-timeout-ms"]}:{},...argv["session-restore-timeout-ms"]!==void 0?{sessionRestoreTimeoutMs:argv["session-restore-timeout-ms"]}:{},...argv["session-reap-interval-ms"]!==void 0?{sessionReapIntervalMs:argv["session-reap-interval-ms"]}:{},...argv["session-idle-timeout-ms"]!==void 0?{sessionIdleTimeoutMs:argv["session-idle-timeout-ms"]}:{},...argv["session-prompt-settled-close-grace-ms"]!==void 0?{sessionPromptSettledCloseGraceMs:argv["session-prompt-settled-close-grace-ms"]}:{},...argv["permission-response-timeout-ms"]!==void 0?{permissionResponseTimeoutMs:argv["permission-response-timeout-ms"]}:{},...argv["external-tool-guard-mode"]==="required"?{externalToolGuard:{mode:"required",endpoint:argv["external-tool-guard-endpoint"]??"",token:externalToolGuardToken,...argv["external-tool-guard-timeout-ms"]!==void 0?{timeoutMs:argv["external-tool-guard-timeout-ms"]}:{}}}:{},...rateLimit?{rateLimit:true}:{},...rateLimitPrompt!==void 0?{rateLimitPrompt}:{},...rateLimitMutation!==void 0?{rateLimitMutation}:{},...rateLimitRead!==void 0?{rateLimitRead}:{},...rateLimitWindowMs!==void 0?{rateLimitWindowMs}:{},...argv.experimentalLsp===true?{experimentalLsp:true}:{},...argv.restoreAskUserQuestion===true?{restoreAskUserQuestion:true}:{},...channelSelection!==void 0?{channelSelection}:{}};if(openWithAuth){const{applyOpenWithAuth}=await import("./open-with-auth-KXZ7DU2D.js");applyOpenWithAuth(serveOptions)}const handle=await runQwenServe(serveOptions,{updateRestartArgv:process.argv.slice(2)});const joined=argv["join"]?parseJoinLink(argv["join"]):void 0;const hostTarget=joined?{...joined,token:agentHostEnrollmentToken}:argv["agent-host-server"]&&argv["agent-host-workspace-id"]?{serverUrl:argv["agent-host-server"],workspaceId:argv["agent-host-workspace-id"],token:agentHostEnrollmentToken}:void 0;if(hostTarget){try{await handle.runtimeReady;const runtime=handle.getPrimaryWorkspaceRuntime();if(!runtime?.trusted||!runtime.generationGuard||runtime.generationGuard.closed){throw new Error("Agent Host join requires a trusted active workspace.")}const{startAgentHostConnection}=await import("./agent-host-client-PXIIFCCS.js");await startAgentHostConnection({bridge:runtime.bridge,serverUrl:hostTarget.serverUrl,workspaceId:hostTarget.workspaceId,workspaceCwd:runtime.workspaceCwd,allowHttp:argv["agent-host-allow-http"]===true,generationGuard:runtime.generationGuard,...hostTarget.token?{enrollmentToken:hostTarget.token}:{},...argv["agent-host-name"]?{name:argv["agent-host-name"]}:{}})}catch(error){await handle.close().catch(()=>void 0);throw error}}if(argv["local-control"]){try{await startLocalControl(handle,argv["local-control-address"])}catch(err){await handle.close().catch(()=>void 0);throw err}}await maybeOpenWebShellBrowser(handle,open,openWithAuth)}catch(err){writeStderrLine(`qwen serve: ${err instanceof Error?err.message:String(err)}`);process.exit(1)}await blockForever()},"handler")};export{parseJoinLink,maybeOpenWebShellBrowser,serveCommand};
5
5
  /**
6
6
  * @license
7
7
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{collectProviderModelsForProtocol}from"./chunk-YVEPPENZ.js";import{loadSettings}from"./chunk-JV5FCFG4.js";import{loadEnvironment}from"./chunk-QTYA6TES.js";import{t}from"./chunk-4IE26CIN.js";import{resolveModelSelectionAuthType}from"./chunk-KAEW65QP.js";import{VERTEX_ADC_HINT,hasVertexProjectConfigured}from"./chunk-HXA3X4PB.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var DEFAULT_ENV_KEYS={["openai"]:"OPENAI_API_KEY",["openai-responses"]:"OPENAI_API_KEY",["anthropic"]:"ANTHROPIC_API_KEY",["gemini"]:"GEMINI_API_KEY",["vertex-ai"]:"GOOGLE_API_KEY"};function findModelConfig(modelProviders,providerProtocol,authType,modelId,baseUrl){if(!modelProviders||!modelId){return void 0}const models=collectProviderModelsForProtocol(modelProviders,providerProtocol,authType);if(models.length===0){return void 0}if(baseUrl){return models.find(m=>m.id===modelId&&m.baseUrl===baseUrl)??models.find(m=>m.id===modelId)}return models.find(m=>m.id===modelId)}__name(findModelConfig,"findModelConfig");function resolveSelectedModel(settings,config){const modelsConfig=config?.getModelsConfig();if(modelsConfig){return{modelId:modelsConfig.getModel(),baseUrl:modelsConfig.getGenerationConfig()?.baseUrl}}return{modelId:settings.model?.name,baseUrl:settings.model?.baseUrl}}__name(resolveSelectedModel,"resolveSelectedModel");function hasEnvValue(settings,envKey){if(!envKey){return false}if(process.env[envKey]){return true}const settingsEnv=settings.env;const settingsEnvValue=settingsEnv?.[envKey];return typeof settingsEnvValue==="string"&&settingsEnvValue.trim().length>0}__name(hasEnvValue,"hasEnvValue");function hasApiKeyForAuth(authType,settings,config){const modelProviders=settings.modelProviders;const{modelId,baseUrl}=resolveSelectedModel(settings,config);const modelAuthType=!config&&(authType==="openai"||authType==="openai-responses")?resolveModelSelectionAuthType(authType,modelId,modelProviders,settings.providerProtocol,baseUrl):authType;const modelConfig=findModelConfig(modelProviders,settings.providerProtocol,modelAuthType,modelId,baseUrl);const resolvedApiKey=config?.getModelsConfig().getGenerationConfig()?.apiKey;if(resolvedApiKey){return{hasKey:true,checkedEnvKey:modelConfig?.envKey??DEFAULT_ENV_KEYS[authType],isExplicitEnvKey:!!modelConfig?.envKey}}if(modelConfig?.envKey){const hasKey=hasEnvValue(settings,modelConfig.envKey);return{hasKey,checkedEnvKey:modelConfig.envKey,isExplicitEnvKey:true}}const defaultEnvKey=DEFAULT_ENV_KEYS[authType];if(defaultEnvKey){const hasKey=hasEnvValue(settings,defaultEnvKey);if(hasKey){return{hasKey,checkedEnvKey:defaultEnvKey,isExplicitEnvKey:false}}}if(settings.security?.auth?.apiKey){return{hasKey:true,checkedEnvKey:defaultEnvKey||void 0,isExplicitEnvKey:false}}return{hasKey:false,checkedEnvKey:defaultEnvKey,isExplicitEnvKey:false}}__name(hasApiKeyForAuth,"hasApiKeyForAuth");function isVertexAdcEligible(settings,config){const{modelId,baseUrl}=resolveSelectedModel(settings,config);const modelConfig=findModelConfig(settings.modelProviders,settings.providerProtocol,"vertex-ai",modelId,baseUrl);return!modelConfig?.envKey}__name(isVertexAdcEligible,"isVertexAdcEligible");function hasVertexProject(settings){const settingsEnv=settings.env;return hasVertexProjectConfigured(key=>{const fromProcess=process.env[key];if(fromProcess!==void 0){return fromProcess}const fromSettings=settingsEnv?.[key];return typeof fromSettings==="string"?fromSettings:void 0})}__name(hasVertexProject,"hasVertexProject");function getApiKeyError(authMethod,settings,config){const{hasKey,checkedEnvKey,isExplicitEnvKey}=hasApiKeyForAuth(authMethod,settings,config);if(hasKey){return null}const envKeyHint=checkedEnvKey||DEFAULT_ENV_KEYS[authMethod];if(isExplicitEnvKey){return t("{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.",{envKeyHint})}return t("{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.",{envKeyHint})}__name(getApiKeyError,"getApiKeyError");function validateAuthMethod(authMethod,config){const settings=loadSettings(process.cwd(),false);loadEnvironment(settings.merged);if(authMethod==="openai"||authMethod==="openai-responses"){const{hasKey,checkedEnvKey,isExplicitEnvKey}=hasApiKeyForAuth(authMethod,settings.merged,config);if(!hasKey){const envKeyHint=checkedEnvKey?`'${checkedEnvKey}'`:"'OPENAI_API_KEY'";if(isExplicitEnvKey){return t("Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.",{envKeyHint})}return t("Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.",{envKeyHint})}return null}if(authMethod==="qwen-oauth"){return t("Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.")}if(authMethod==="anthropic"){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return apiKeyError}const modelProviders=settings.merged.modelProviders;const{modelId,baseUrl}=resolveSelectedModel(settings.merged,config);const modelConfig=findModelConfig(modelProviders,settings.merged.providerProtocol,authMethod,modelId,baseUrl);if(modelConfig&&!modelConfig.baseUrl){return t("Anthropic provider missing required baseUrl in modelProviders[].baseUrl.")}if(!modelConfig&&!process.env["ANTHROPIC_BASE_URL"]){return t("ANTHROPIC_BASE_URL environment variable not found.")}return null}if(authMethod==="gemini"){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return apiKeyError}return null}if(authMethod==="vertex-ai"){const adcEligible=isVertexAdcEligible(settings.merged,config);if(!adcEligible||!hasVertexProject(settings.merged)){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return adcEligible?apiKeyError+VERTEX_ADC_HINT:apiKeyError}}process.env["GOOGLE_GENAI_USE_VERTEXAI"]="true";return null}return t("Invalid auth method selected.")}__name(validateAuthMethod,"validateAuthMethod");init_esbuild_shims();import{EventEmitter}from"node:events";var SUPPRESS_AFTER_MS=1e3;var EXTENSION_RELOAD_FAILED_REASON="extension reload failed";var ExtensionRefreshState=class{constructor(events=new EventEmitter){this.events=events}static{__name(this,"ExtensionRefreshState")}extensionRefreshNeeded=false;reloadInProgress=false;changedDuringReload=false;contentChangedDuringReload=false;suppressionDepth=0;suppressUntil=0;on(event,listener){this.events.on(event,listener)}off(event,listener){this.events.off(event,listener)}markExtensionsChanged(reason){if(this.isSuppressed()){return false}if(this.reloadInProgress){this.changedDuringReload=true;return false}if(this.extensionRefreshNeeded){return false}this.extensionRefreshNeeded=true;this.events.emit("extension-refresh-needed",reason);return true}markExtensionContentChanged(reason){if(this.isSuppressed()){return false}if(this.reloadInProgress){this.contentChangedDuringReload=true;return false}if(this.extensionRefreshNeeded){return false}this.events.emit("extension-content-changed",reason);return true}clearExtensionsChanged(){const changedDuringReload=this.changedDuringReload;const contentChangedDuringReload=this.contentChangedDuringReload;this.extensionRefreshNeeded=changedDuringReload;this.reloadInProgress=false;this.changedDuringReload=false;this.contentChangedDuringReload=false;this.suppressUntil=0;this.events.emit("extensions-reloaded");if(changedDuringReload){this.events.emit("extension-refresh-needed","extension files changed during reload")}else if(contentChangedDuringReload){this.events.emit("extension-content-changed","extension content files changed during reload")}}notifyExtensionsReloadStarted(){this.reloadInProgress=true;this.changedDuringReload=false;this.contentChangedDuringReload=false;this.events.emit("extensions-reload-started")}markExtensionsReloadFailed(reason=EXTENSION_RELOAD_FAILED_REASON){const changedDuringReload=this.changedDuringReload;const contentChangedDuringReload=this.contentChangedDuringReload;this.extensionRefreshNeeded=true;this.reloadInProgress=false;this.changedDuringReload=changedDuringReload;this.contentChangedDuringReload=contentChangedDuringReload;this.suppressUntil=0;this.events.emit("extensions-reloaded");this.events.emit("extension-refresh-needed",reason)}needsExtensionRefresh(){return this.extensionRefreshNeeded}isSuppressed(){return this.suppressionDepth>0||Date.now()<this.suppressUntil}isReloadInProgress(){return this.reloadInProgress}beginSuppression(onSettle){this.suppressionDepth++;let settled=false;return()=>{if(settled)return;settled=true;this.suppressionDepth=Math.max(0,this.suppressionDepth-1);this.suppressUntil=Date.now()+SUPPRESS_AFTER_MS;if(this.suppressionDepth===0){onSettle?.()}}}suppressNotifications(fn,onSettle){const endSuppression=this.beginSuppression(onSettle);try{const result=fn();if(isPromiseLike(result)){return Promise.resolve(result).finally(endSuppression)}endSuppression();return result}catch(error){endSuppression();throw error}}resetForTesting(){this.extensionRefreshNeeded=false;this.reloadInProgress=false;this.changedDuringReload=false;this.contentChangedDuringReload=false;this.suppressionDepth=0;this.suppressUntil=0}};function isPromiseLike(value){return typeof value==="object"&&value!==null&&"then"in value&&typeof value.then==="function"}__name(isPromiseLike,"isPromiseLike");export{validateAuthMethod,EXTENSION_RELOAD_FAILED_REASON,ExtensionRefreshState};
3
+ import{collectProviderModelsForProtocol}from"./chunk-FFLFTXO7.js";import{loadSettings}from"./chunk-4WFWZWR3.js";import{loadEnvironment}from"./chunk-LJLS3MDJ.js";import{t}from"./chunk-4IE26CIN.js";import{resolveModelSelectionAuthType}from"./chunk-B5XDGUAK.js";import{VERTEX_ADC_HINT,hasVertexProjectConfigured}from"./chunk-MJUFVFH3.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var DEFAULT_ENV_KEYS={["openai"]:"OPENAI_API_KEY",["openai-responses"]:"OPENAI_API_KEY",["anthropic"]:"ANTHROPIC_API_KEY",["gemini"]:"GEMINI_API_KEY",["vertex-ai"]:"GOOGLE_API_KEY"};function findModelConfig(modelProviders,providerProtocol,authType,modelId,baseUrl){if(!modelProviders||!modelId){return void 0}const models=collectProviderModelsForProtocol(modelProviders,providerProtocol,authType);if(models.length===0){return void 0}if(baseUrl){return models.find(m=>m.id===modelId&&m.baseUrl===baseUrl)??models.find(m=>m.id===modelId)}return models.find(m=>m.id===modelId)}__name(findModelConfig,"findModelConfig");function resolveSelectedModel(settings,config){const modelsConfig=config?.getModelsConfig();if(modelsConfig){return{modelId:modelsConfig.getModel(),baseUrl:modelsConfig.getGenerationConfig()?.baseUrl}}return{modelId:settings.model?.name,baseUrl:settings.model?.baseUrl}}__name(resolveSelectedModel,"resolveSelectedModel");function hasEnvValue(settings,envKey){if(!envKey){return false}if(process.env[envKey]){return true}const settingsEnv=settings.env;const settingsEnvValue=settingsEnv?.[envKey];return typeof settingsEnvValue==="string"&&settingsEnvValue.trim().length>0}__name(hasEnvValue,"hasEnvValue");function hasApiKeyForAuth(authType,settings,config){const modelProviders=settings.modelProviders;const{modelId,baseUrl}=resolveSelectedModel(settings,config);const modelAuthType=!config&&(authType==="openai"||authType==="openai-responses")?resolveModelSelectionAuthType(authType,modelId,modelProviders,settings.providerProtocol,baseUrl):authType;const modelConfig=findModelConfig(modelProviders,settings.providerProtocol,modelAuthType,modelId,baseUrl);const resolvedApiKey=config?.getModelsConfig().getGenerationConfig()?.apiKey;if(resolvedApiKey){return{hasKey:true,checkedEnvKey:modelConfig?.envKey??DEFAULT_ENV_KEYS[authType],isExplicitEnvKey:!!modelConfig?.envKey}}if(modelConfig?.envKey){const hasKey=hasEnvValue(settings,modelConfig.envKey);return{hasKey,checkedEnvKey:modelConfig.envKey,isExplicitEnvKey:true}}const defaultEnvKey=DEFAULT_ENV_KEYS[authType];if(defaultEnvKey){const hasKey=hasEnvValue(settings,defaultEnvKey);if(hasKey){return{hasKey,checkedEnvKey:defaultEnvKey,isExplicitEnvKey:false}}}if(settings.security?.auth?.apiKey){return{hasKey:true,checkedEnvKey:defaultEnvKey||void 0,isExplicitEnvKey:false}}return{hasKey:false,checkedEnvKey:defaultEnvKey,isExplicitEnvKey:false}}__name(hasApiKeyForAuth,"hasApiKeyForAuth");function isVertexAdcEligible(settings,config){const{modelId,baseUrl}=resolveSelectedModel(settings,config);const modelConfig=findModelConfig(settings.modelProviders,settings.providerProtocol,"vertex-ai",modelId,baseUrl);return!modelConfig?.envKey}__name(isVertexAdcEligible,"isVertexAdcEligible");function hasVertexProject(settings){const settingsEnv=settings.env;return hasVertexProjectConfigured(key=>{const fromProcess=process.env[key];if(fromProcess!==void 0){return fromProcess}const fromSettings=settingsEnv?.[key];return typeof fromSettings==="string"?fromSettings:void 0})}__name(hasVertexProject,"hasVertexProject");function getApiKeyError(authMethod,settings,config){const{hasKey,checkedEnvKey,isExplicitEnvKey}=hasApiKeyForAuth(authMethod,settings,config);if(hasKey){return null}const envKeyHint=checkedEnvKey||DEFAULT_ENV_KEYS[authMethod];if(isExplicitEnvKey){return t("{{envKeyHint}} environment variable not found. Please set it in your .env file or environment variables.",{envKeyHint})}return t("{{envKeyHint}} environment variable not found (or set settings.security.auth.apiKey). Please set it in your .env file or environment variables.",{envKeyHint})}__name(getApiKeyError,"getApiKeyError");function validateAuthMethod(authMethod,config){const settings=loadSettings(process.cwd(),false);loadEnvironment(settings.merged);if(authMethod==="openai"||authMethod==="openai-responses"){const{hasKey,checkedEnvKey,isExplicitEnvKey}=hasApiKeyForAuth(authMethod,settings.merged,config);if(!hasKey){const envKeyHint=checkedEnvKey?`'${checkedEnvKey}'`:"'OPENAI_API_KEY'";if(isExplicitEnvKey){return t("Missing API key for OpenAI-compatible auth. Set the {{envKeyHint}} environment variable.",{envKeyHint})}return t("Missing API key for OpenAI-compatible auth. Set settings.security.auth.apiKey, or set the {{envKeyHint}} environment variable.",{envKeyHint})}return null}if(authMethod==="qwen-oauth"){return t("Qwen OAuth free tier was discontinued on 2026-04-15. Run /auth to switch to Coding Plan, OpenRouter, Fireworks AI, or another provider.")}if(authMethod==="anthropic"){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return apiKeyError}const modelProviders=settings.merged.modelProviders;const{modelId,baseUrl}=resolveSelectedModel(settings.merged,config);const modelConfig=findModelConfig(modelProviders,settings.merged.providerProtocol,authMethod,modelId,baseUrl);if(modelConfig&&!modelConfig.baseUrl){return t("Anthropic provider missing required baseUrl in modelProviders[].baseUrl.")}if(!modelConfig&&!process.env["ANTHROPIC_BASE_URL"]){return t("ANTHROPIC_BASE_URL environment variable not found.")}return null}if(authMethod==="gemini"){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return apiKeyError}return null}if(authMethod==="vertex-ai"){const adcEligible=isVertexAdcEligible(settings.merged,config);if(!adcEligible||!hasVertexProject(settings.merged)){const apiKeyError=getApiKeyError(authMethod,settings.merged,config);if(apiKeyError){return adcEligible?apiKeyError+VERTEX_ADC_HINT:apiKeyError}}process.env["GOOGLE_GENAI_USE_VERTEXAI"]="true";return null}return t("Invalid auth method selected.")}__name(validateAuthMethod,"validateAuthMethod");init_esbuild_shims();import{EventEmitter}from"node:events";var SUPPRESS_AFTER_MS=1e3;var EXTENSION_RELOAD_FAILED_REASON="extension reload failed";var ExtensionRefreshState=class{constructor(events=new EventEmitter){this.events=events}static{__name(this,"ExtensionRefreshState")}extensionRefreshNeeded=false;reloadInProgress=false;changedDuringReload=false;contentChangedDuringReload=false;suppressionDepth=0;suppressUntil=0;on(event,listener){this.events.on(event,listener)}off(event,listener){this.events.off(event,listener)}markExtensionsChanged(reason){if(this.isSuppressed()){return false}if(this.reloadInProgress){this.changedDuringReload=true;return false}if(this.extensionRefreshNeeded){return false}this.extensionRefreshNeeded=true;this.events.emit("extension-refresh-needed",reason);return true}markExtensionContentChanged(reason){if(this.isSuppressed()){return false}if(this.reloadInProgress){this.contentChangedDuringReload=true;return false}if(this.extensionRefreshNeeded){return false}this.events.emit("extension-content-changed",reason);return true}clearExtensionsChanged(){const changedDuringReload=this.changedDuringReload;const contentChangedDuringReload=this.contentChangedDuringReload;this.extensionRefreshNeeded=changedDuringReload;this.reloadInProgress=false;this.changedDuringReload=false;this.contentChangedDuringReload=false;this.suppressUntil=0;this.events.emit("extensions-reloaded");if(changedDuringReload){this.events.emit("extension-refresh-needed","extension files changed during reload")}else if(contentChangedDuringReload){this.events.emit("extension-content-changed","extension content files changed during reload")}}notifyExtensionsReloadStarted(){this.reloadInProgress=true;this.changedDuringReload=false;this.contentChangedDuringReload=false;this.events.emit("extensions-reload-started")}markExtensionsReloadFailed(reason=EXTENSION_RELOAD_FAILED_REASON){const changedDuringReload=this.changedDuringReload;const contentChangedDuringReload=this.contentChangedDuringReload;this.extensionRefreshNeeded=true;this.reloadInProgress=false;this.changedDuringReload=changedDuringReload;this.contentChangedDuringReload=contentChangedDuringReload;this.suppressUntil=0;this.events.emit("extensions-reloaded");this.events.emit("extension-refresh-needed",reason)}needsExtensionRefresh(){return this.extensionRefreshNeeded}isSuppressed(){return this.suppressionDepth>0||Date.now()<this.suppressUntil}isReloadInProgress(){return this.reloadInProgress}beginSuppression(onSettle){this.suppressionDepth++;let settled=false;return()=>{if(settled)return;settled=true;this.suppressionDepth=Math.max(0,this.suppressionDepth-1);this.suppressUntil=Date.now()+SUPPRESS_AFTER_MS;if(this.suppressionDepth===0){onSettle?.()}}}suppressNotifications(fn,onSettle){const endSuppression=this.beginSuppression(onSettle);try{const result=fn();if(isPromiseLike(result)){return Promise.resolve(result).finally(endSuppression)}endSuppression();return result}catch(error){endSuppression();throw error}}resetForTesting(){this.extensionRefreshNeeded=false;this.reloadInProgress=false;this.changedDuringReload=false;this.contentChangedDuringReload=false;this.suppressionDepth=0;this.suppressUntil=0}};function isPromiseLike(value){return typeof value==="object"&&value!==null&&"then"in value&&typeof value.then==="function"}__name(isPromiseLike,"isPromiseLike");export{validateAuthMethod,EXTENSION_RELOAD_FAILED_REASON,ExtensionRefreshState};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{WriteFileTool}from"./chunk-ZEYCGUHI.js";import{EditTool}from"./chunk-KLXL3FSI.js";import{GlobTool}from"./chunk-6OP7FXSJ.js";import{GrepTool}from"./chunk-6SEPEJQZ.js";import{LSTool}from"./chunk-XUQ73TBA.js";import{NotebookEditTool}from"./chunk-L7WFW57T.js";import{TaskStopTool}from"./chunk-IDMI4UMG.js";import{ShellTool,isModifiableDeclarativeTool}from"./chunk-GG7RNHZW.js";import{stableJson}from"./chunk-JUPGJYC2.js";import{ReadFileTool}from"./chunk-KBPIYGHG.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stat}from"node:fs/promises";function createExecutionTools(config){const tools=[new ReadFileTool(config),new WriteFileTool(config),new EditTool(config),new NotebookEditTool(config),new GlobTool(config),new GrepTool(config),new LSTool(config),new ShellTool(config),new TaskStopTool(config)];return new Map(tools.map(tool=>[tool.name,tool]))}__name(createExecutionTools,"createExecutionTools");var LocalExecutionEnvironment=class{constructor(config,options={}){this.config=config;this.toolNames=options.toolNames;this.run=options.run;this.tools=createExecutionTools(config);if(options.toolNames){for(const name of this.tools.keys()){if(!options.toolNames.has(name))this.tools.delete(name)}}}static{__name(this,"LocalExecutionEnvironment")}toolNames;tools;invocations=new Map;controllers=new Set;run;disposed=false;tool(name){if(this.disposed)throw new Error("Execution environment is disposed.");const tool=this.tools.get(name);if(!tool)throw new Error(`Unsupported execution tool: ${name}`);return tool}pending(id){if(this.disposed)throw new Error("Execution environment is disposed.");const pending=this.invocations.get(id);if(!pending)throw new Error(`Unknown execution invocation: ${id}`);if(pending.executing)throw new Error(`Invocation is executing: ${id}`);return pending}toolDefinition(name){const{name:toolName,description,parametersJsonSchema}=this.tool(name).schema;return{name:toolName,description,parametersJsonSchema}}async prepare(request,signal){signal.throwIfAborted();const tool=this.tool(request.toolName);if(this.invocations.has(request.id))throw new Error(`Duplicate invocation: ${request.id}`);if(this.invocations.size>=256)throw new Error("Too many pending execution invocations.");let params=structuredClone(request.params);if(request.modification){if(!isModifiableDeclarativeTool(tool))throw new Error("Tool does not support modification.");params=tool.getModifyContext(signal).createUpdatedParams(request.modification.oldContent,request.modification.newContent,params)}const invocation=tool.build(params);this.invocations.set(request.id,{toolName:request.toolName,invocation,executing:false,...request.callId===void 0?{}:{callId:request.callId}});return{params:invocation.params,description:invocation.getDescription(),locations:invocation.toolLocations()}}async permission(id,signal){signal.throwIfAborted();return this.pending(id).invocation.getDefaultPermission(signal)}async confirmation(id,signal){signal.throwIfAborted();const pending=this.pending(id);const details=await pending.invocation.getConfirmationDetails(signal);pending.confirmation=details;const{onConfirm:_onConfirm,...serializable}=details;return serializable}async confirm(id,outcome,payload,signal){signal.throwIfAborted();const pending=this.pending(id);await pending.confirmation?.onConfirm(outcome,payload);if(outcome==="cancel")this.invocations.delete(id)}async execute(id,signal,updateOutput){signal.throwIfAborted();const pending=this.pending(id);pending.executing=true;const controller=new AbortController;const abort=__name(()=>controller.abort(signal.reason),"abort");signal.addEventListener("abort",abort,{once:true});this.controllers.add(controller);try{if(this.run){const params=structuredClone(pending.invocation.params);const rebuilt=this.tool(pending.toolName).build(structuredClone(params)).params;if(stableJson(rebuilt)!==stableJson(params)){throw new Error("The approved parameters change when the tool builds them again; the call did not run.")}return await this.run({id,toolName:pending.toolName,params,...pending.callId===void 0?{}:{callId:pending.callId}},controller.signal,updateOutput)}return await pending.invocation.execute(controller.signal,updateOutput,{...this.config.getShellExecutionConfig(),streamBufferedOutput:true})}finally{signal.removeEventListener("abort",abort);this.controllers.delete(controller);this.invocations.delete(id)}}async modificationContent(toolName,params,signal){signal.throwIfAborted();const tool=this.tool(toolName);if(!isModifiableDeclarativeTool(tool))throw new Error("Tool does not support modification.");const context=tool.getModifyContext(signal);const current=await context.getCurrentContent(params);const proposed=await context.getProposedContent(params);return{current,proposed}}async release(id,signal){signal.throwIfAborted();if(!this.invocations.get(id)?.executing)this.invocations.delete(id)}async invalidateReadCache(paths){const cache=this.config.getFileReadCache();if(!paths){cache.clear();return}await Promise.all(paths.map(async filePath=>{const stats=await stat(filePath).catch(()=>void 0);if(!stats||!cache.markReadEvictedFromHistory(stats))cache.invalidateByPath(filePath)}))}async dispose(){this.disposed=true;for(const controller of this.controllers)controller.abort();this.config.getBackgroundShellRegistry().abortAll();this.invocations.clear();this.tools.clear()}};export{createExecutionTools,LocalExecutionEnvironment};
3
+ import{WriteFileTool}from"./chunk-BVARURDD.js";import{EditTool}from"./chunk-SFETIBPP.js";import{GlobTool}from"./chunk-6OP7FXSJ.js";import{GrepTool}from"./chunk-6SEPEJQZ.js";import{LSTool}from"./chunk-XUQ73TBA.js";import{NotebookEditTool}from"./chunk-PODFLAH7.js";import{TaskStopTool}from"./chunk-IDMI4UMG.js";import{ShellTool,isModifiableDeclarativeTool}from"./chunk-IFAUFERF.js";import{stableJson}from"./chunk-JUPGJYC2.js";import{ReadFileTool}from"./chunk-KBPIYGHG.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{stat}from"node:fs/promises";function createExecutionTools(config){const tools=[new ReadFileTool(config),new WriteFileTool(config),new EditTool(config),new NotebookEditTool(config),new GlobTool(config),new GrepTool(config),new LSTool(config),new ShellTool(config),new TaskStopTool(config)];return new Map(tools.map(tool=>[tool.name,tool]))}__name(createExecutionTools,"createExecutionTools");var LocalExecutionEnvironment=class{constructor(config,options={}){this.config=config;this.toolNames=options.toolNames;this.run=options.run;this.tools=createExecutionTools(config);if(options.toolNames){for(const name of this.tools.keys()){if(!options.toolNames.has(name))this.tools.delete(name)}}}static{__name(this,"LocalExecutionEnvironment")}toolNames;tools;invocations=new Map;controllers=new Set;run;disposed=false;tool(name){if(this.disposed)throw new Error("Execution environment is disposed.");const tool=this.tools.get(name);if(!tool)throw new Error(`Unsupported execution tool: ${name}`);return tool}pending(id){if(this.disposed)throw new Error("Execution environment is disposed.");const pending=this.invocations.get(id);if(!pending)throw new Error(`Unknown execution invocation: ${id}`);if(pending.executing)throw new Error(`Invocation is executing: ${id}`);return pending}toolDefinition(name){const{name:toolName,description,parametersJsonSchema}=this.tool(name).schema;return{name:toolName,description,parametersJsonSchema}}async prepare(request,signal){signal.throwIfAborted();const tool=this.tool(request.toolName);if(this.invocations.has(request.id))throw new Error(`Duplicate invocation: ${request.id}`);if(this.invocations.size>=256)throw new Error("Too many pending execution invocations.");let params=structuredClone(request.params);if(request.modification){if(!isModifiableDeclarativeTool(tool))throw new Error("Tool does not support modification.");params=tool.getModifyContext(signal).createUpdatedParams(request.modification.oldContent,request.modification.newContent,params)}const invocation=tool.build(params);this.invocations.set(request.id,{toolName:request.toolName,invocation,executing:false,...request.callId===void 0?{}:{callId:request.callId}});return{params:invocation.params,description:invocation.getDescription(),locations:invocation.toolLocations()}}async permission(id,signal){signal.throwIfAborted();return this.pending(id).invocation.getDefaultPermission(signal)}async confirmation(id,signal){signal.throwIfAborted();const pending=this.pending(id);const details=await pending.invocation.getConfirmationDetails(signal);pending.confirmation=details;const{onConfirm:_onConfirm,...serializable}=details;return serializable}async confirm(id,outcome,payload,signal){signal.throwIfAborted();const pending=this.pending(id);await pending.confirmation?.onConfirm(outcome,payload);if(outcome==="cancel")this.invocations.delete(id)}async execute(id,signal,updateOutput){signal.throwIfAborted();const pending=this.pending(id);pending.executing=true;const controller=new AbortController;const abort=__name(()=>controller.abort(signal.reason),"abort");signal.addEventListener("abort",abort,{once:true});this.controllers.add(controller);try{if(this.run){const params=structuredClone(pending.invocation.params);const rebuilt=this.tool(pending.toolName).build(structuredClone(params)).params;if(stableJson(rebuilt)!==stableJson(params)){throw new Error("The approved parameters change when the tool builds them again; the call did not run.")}return await this.run({id,toolName:pending.toolName,params,...pending.callId===void 0?{}:{callId:pending.callId}},controller.signal,updateOutput)}return await pending.invocation.execute(controller.signal,updateOutput,{...this.config.getShellExecutionConfig(),streamBufferedOutput:true})}finally{signal.removeEventListener("abort",abort);this.controllers.delete(controller);this.invocations.delete(id)}}async modificationContent(toolName,params,signal){signal.throwIfAborted();const tool=this.tool(toolName);if(!isModifiableDeclarativeTool(tool))throw new Error("Tool does not support modification.");const context=tool.getModifyContext(signal);const current=await context.getCurrentContent(params);const proposed=await context.getProposedContent(params);return{current,proposed}}async release(id,signal){signal.throwIfAborted();if(!this.invocations.get(id)?.executing)this.invocations.delete(id)}async invalidateReadCache(paths){const cache=this.config.getFileReadCache();if(!paths){cache.clear();return}await Promise.all(paths.map(async filePath=>{const stats=await stat(filePath).catch(()=>void 0);if(!stats||!cache.markReadEvictedFromHistory(stats))cache.invalidateByPath(filePath)}))}async dispose(){this.disposed=true;for(const controller of this.controllers)controller.abort();this.config.getBackgroundShellRegistry().abortAll();this.invocations.clear();this.tools.clear()}};export{createExecutionTools,LocalExecutionEnvironment};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,7 +1,7 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{EXTENSION_CONTEXT_BUDGET,buildExtensionMentionContext,buildExtensionRef,getSanitizedExtensionDisplayName,matchExtensionByRef,parseExtensionRef,sanitizeDisplayText}from"./chunk-2HJZ3OYW.js";import{t}from"./chunk-4IE26CIN.js";import{SessionReferenceService,readManyFiles}from"./chunk-B3L4LODR.js";import{emptyMcpResourceText,formatMcpResourceContents,summarizeMcpResource}from"./chunk-46VUDNCL.js";import{SessionService}from"./chunk-GG7RNHZW.js";import{shouldRunVisionBridge}from"./chunk-KBPIYGHG.js";import{Storage}from"./chunk-EPODBRBP.js";import{isSubpath,unescapePath,unescapeShellSpecials}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs/promises";import*as path from"node:path";init_esbuild_shims();function matchMcpServerPrefix(input,serverNames){let serverName=null;for(const name of serverNames){if(input.startsWith(`${name}:`)&&(serverName===null||name.length>serverName.length)){serverName=name}}if(serverName===null)return null;return{serverName,rest:input.slice(serverName.length+1)}}__name(matchMcpServerPrefix,"matchMcpServerPrefix");function buildMcpResourceRef(serverName,uri){return`${serverName}:${uri}`}__name(buildMcpResourceRef,"buildMcpResourceRef");init_esbuild_shims();init_esbuild_shims();var MAX_SUGGESTIONS_TO_SHOW=8;function normalizeDescription(description){return description.replace(/\s+/g," ").trim()}__name(normalizeDescription,"normalizeDescription");function getExtensionSuggestions(config,pattern){if(!config)return[];if(config.isTrustedFolder?.()===false)return[];const extensions=config.getActiveExtensions?.()??[];if(extensions.length===0)return[];const query=pattern.toLowerCase();return extensions.map(ext=>({ext,safeLabel:sanitizeDisplayText(ext.displayName||ext.name)||ext.name})).filter(({safeLabel,ext})=>{const label=safeLabel.toLowerCase();const name=ext.name.toLowerCase();return label.includes(query)||name.includes(query)}).sort((a,b)=>{const aName=a.safeLabel.toLowerCase();const bName=b.safeLabel.toLowerCase();const aPrefix=aName.startsWith(query)?0:1;const bPrefix=bName.startsWith(query)?0:1;if(aPrefix!==bPrefix)return aPrefix-bPrefix;return aName.localeCompare(bName)}).slice(0,MAX_SUGGESTIONS_TO_SHOW).map(({ext,safeLabel})=>({label:safeLabel,value:buildExtensionRef(ext.name),description:ext.config.description?sanitizeDisplayText(ext.config.description)??void 0:void 0,sourceBadge:t("Extension"),isDirectory:false,category:"extension"}))}__name(getExtensionSuggestions,"getExtensionSuggestions");init_esbuild_shims();var SESSION_MENTION_PREFIX="session:";var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function isSessionId(value){return UUID_RE.test(value.trim())}__name(isSessionId,"isSessionId");function parseSessionRef(pathName){if(!pathName.startsWith(SESSION_MENTION_PREFIX))return null;const rawRemainder=pathName.slice(SESSION_MENTION_PREFIX.length).trim();const remainder=process.platform==="win32"?unescapeShellSpecials(rawRemainder):rawRemainder;if(remainder.length===0)return null;return isSessionId(remainder)?{id:remainder}:{title:remainder}}__name(parseSessionRef,"parseSessionRef");function buildSessionRef(idOrTitle){return`${SESSION_MENTION_PREFIX}${idOrTitle}`}__name(buildSessionRef,"buildSessionRef");init_esbuild_shims();var MCP_SERVER_REF_PREFIX="mcp:";function parseMcpServerRef(pathName){if(!pathName.startsWith(MCP_SERVER_REF_PREFIX))return null;const name=pathName.slice(MCP_SERVER_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseMcpServerRef,"parseMcpServerRef");function buildMcpServerRef(serverName){return`${MCP_SERVER_REF_PREFIX}${serverName}`}__name(buildMcpServerRef,"buildMcpServerRef");function matchMcpServerByRef(name,servers){const lower=name.toLowerCase();const matchedName=Object.keys(servers).find(serverName=>serverName.toLowerCase()===lower);if(!matchedName)return void 0;return{serverName:matchedName,server:servers[matchedName]}}__name(matchMcpServerByRef,"matchMcpServerByRef");function buildMcpServerContextText(config,serverName){const lines=[`--- MCP Server: ${serverName} ---`,`The user explicitly mentioned this MCP server. Prefer using tools and resources from this server when relevant for this turn. This is advisory context, not a hard restriction.`];const prompts=config.getPromptRegistry?.()?.getPromptsByServer(serverName)??[];const resources=config.getResourceRegistry?.()?.getResourcesByServer(serverName)??[];const details=[];if(resources.length>0){details.push(`- Resources: ${resources.length}`)}if(prompts.length>0){details.push(`- Prompts: ${prompts.length}`)}if(details.length>0){lines.push("Available capabilities from this MCP server:");lines.push(...details)}lines.push(`--- End MCP Server: ${serverName} ---`);return lines.join("\n")}__name(buildMcpServerContextText,"buildMcpServerContextText");function parseAllAtCommands(query){const parts=[];let currentIndex=0;while(currentIndex<query.length){let atIndex=-1;let nextSearchIndex=currentIndex;while(nextSearchIndex<query.length){if(query[nextSearchIndex]==="@"&&(nextSearchIndex===0||query[nextSearchIndex-1]!=="\\")){atIndex=nextSearchIndex;break}nextSearchIndex++}if(atIndex===-1){if(currentIndex<query.length){parts.push({type:"text",content:query.substring(currentIndex)})}break}if(atIndex>currentIndex){parts.push({type:"text",content:query.substring(currentIndex,atIndex)})}const isUrlRef=/^https?:\/\//i.test(query.slice(atIndex+1));const NON_URL_CHAR=/[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]/;let pathEndIndex=atIndex+1;let inEscape=false;while(pathEndIndex<query.length){const char=query[pathEndIndex];if(inEscape){inEscape=false}else if(char==="\\"){inEscape=true}else if(isUrlRef){if(NON_URL_CHAR.test(char))break}else if(/[,\s;!?()[\]{}]/.test(char)){break}else if(char==="."){const nextChar=pathEndIndex+1<query.length?query[pathEndIndex+1]:"";if(nextChar===""||/\s/.test(nextChar)){break}}pathEndIndex++}let rawAtPath=query.substring(atIndex,pathEndIndex);if(isUrlRef){const trimmed=rawAtPath.replace(/[.,;:!?]+$/,"");pathEndIndex=atIndex+trimmed.length;rawAtPath=trimmed}const atPath=unescapePath(rawAtPath);parts.push({type:"atPath",content:atPath});currentIndex=pathEndIndex}return parts.filter(part=>!(part.type==="text"&&part.content.trim()===""))}__name(parseAllAtCommands,"parseAllAtCommands");function extractAtPathCommands(query){return parseAllAtCommands(query).flatMap(part=>part.type==="atPath"&&part.content!=="@"?[part.content.substring(1)]:[])}__name(extractAtPathCommands,"extractAtPathCommands");function parseMcpResourceRef(pathName,mcpServerNames){const match=matchMcpServerPrefix(pathName,mcpServerNames);if(!match||!match.rest)return null;return{serverName:match.serverName,uri:match.rest}}__name(parseMcpResourceRef,"parseMcpResourceRef");async function resolveAtCommandQuery({query,config,onDebugMessage,messageId:userMessageTimestamp,signal}){const commandParts=parseAllAtCommands(query);const atPathCommandParts=commandParts.filter(part=>part.type==="atPath");if(atPathCommandParts.length===0){return{processedQuery:[{text:query}],shouldProceed:true}}const fileDiscovery=config.getFileService();const respectFileIgnore=config.getFileFilteringOptions();const configuredProjectTempDir=Storage.getGlobalTempDir();const projectTempDir=await fs.realpath(configuredProjectTempDir).catch(()=>path.resolve(configuredProjectTempDir));const pathSpecsToRead=[];const atPathToResolvedSpecMap=new Map;const contentLabelsForDisplay=[];const displayPaths=new Map;const displayPathsByCanonicalPath=new Map;const ignoredByReason={git:[],qwen:[],both:[]};const getIgnoreReason=__name(candidate=>{const gitIgnored=respectFileIgnore.respectGitIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:true,respectQwenIgnore:false});const qwenIgnored=respectFileIgnore.respectQwenIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:false,respectQwenIgnore:true});return gitIgnored&&qwenIgnored?"both":gitIgnored?"git":qwenIgnored?"qwen":void 0},"getIgnoreReason");const mcpServerNames=new Set(Object.keys(config.getMcpServers()||{}));const mcpResourceRefs=[];const mcpServerMentions=[];const activeExtensions=config.getActiveExtensions?.()??[];const extensionMentions=[];const sessionMentions=[];const urlMediaRefs=[];const rememberedMediaRefs=[];for(const atPathPart of atPathCommandParts){const originalAtPath=atPathPart.content;if(originalAtPath==="@"){onDebugMessage("Lone @ detected, will be treated as text in the modified query.");continue}const pathName=originalAtPath.substring(1);if(/^https?:\/\//i.test(pathName)&&config.isOmniEnabled?.()){const omni=await import("./omni-H3GFC6KR.js");if(omni.isOmniDeliveryActive(config)&&omni.parseHttpUrlRef(pathName)){if(!urlMediaRefs.some(r=>r.url===pathName)){urlMediaRefs.push({originalAtPath,url:pathName})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}}const extRef=parseExtensionRef(pathName);if(extRef){const extension=matchExtensionByRef(extRef.name,activeExtensions);if(extension){if(!extensionMentions.some(m=>m.extension.name===extension.name)){extensionMentions.push({originalAtPath,extension})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}onDebugMessage(`Extension "${extRef.name}" not found among active extensions. Available: ${activeExtensions.map(e=>e.name).join(", ")||"(none)"}`);continue}const sessionRef=parseSessionRef(pathName);if(sessionRef){if(!sessionMentions.some(m=>(m.ref.id??m.ref.title)===(sessionRef.id??sessionRef.title))){sessionMentions.push({originalAtPath,ref:sessionRef})}atPathToResolvedSpecMap.set(originalAtPath,buildSessionRef(sessionRef.id??sessionRef.title));continue}const resourceRef=parseMcpResourceRef(pathName,mcpServerNames);if(resourceRef){mcpResourceRefs.push({originalAtPath,...resourceRef});atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}const mcpServerRef=parseMcpServerRef(pathName);if(mcpServerRef){const matched=matchMcpServerByRef(mcpServerRef.name,config.getMcpServers()||{});if(matched){if(!mcpServerMentions.some(m=>m.serverName===matched.serverName)){mcpServerMentions.push({originalAtPath,serverName:matched.serverName})}atPathToResolvedSpecMap.set(originalAtPath,buildMcpServerRef(matched.serverName));continue}onDebugMessage(`MCP server "${mcpServerRef.name}" not found among configured MCP servers. Available: ${Object.keys(config.getMcpServers()||{}).join(", ")||"(none)"}`);continue}const workspaceContext=config.getWorkspaceContext();const absolutePathName=path.isAbsolute(pathName)?pathName:path.resolve(workspaceContext.getDirectories()[0]||"",pathName);if(!isSubpath(configuredProjectTempDir,absolutePathName)&&!isSubpath(projectTempDir,absolutePathName)&&!workspaceContext.isPathWithinWorkspace(pathName)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const ignoredReason=getIgnoreReason(pathName);if(ignoredReason){const reason=ignoredReason;ignoredByReason[reason].push(pathName);const reasonText=reason==="both"?"ignored by both git and qwen":reason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}let resolvedSuccessfully=false;let sawNotFound=false;let deferredIgnoreReason;for(const dir of config.getWorkspaceContext().getDirectories()){try{const absolutePath=path.resolve(dir,pathName);const canonicalPath=await fs.realpath(absolutePath);const stats=await fs.stat(canonicalPath);if(!isSubpath(configuredProjectTempDir,canonicalPath)&&!isSubpath(projectTempDir,canonicalPath)&&!workspaceContext.isPathWithinWorkspace(canonicalPath)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const canonicalIgnoreReason=getIgnoreReason(canonicalPath);if(canonicalIgnoreReason){deferredIgnoreReason=canonicalIgnoreReason;const reasonText=canonicalIgnoreReason==="both"?"ignored by both git and qwen":canonicalIgnoreReason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}if(stats.isDirectory()){onDebugMessage(`Path ${pathName} resolved to directory.`)}else{onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`)}pathSpecsToRead.push(canonicalPath);atPathToResolvedSpecMap.set(originalAtPath,pathName);contentLabelsForDisplay.push(pathName);displayPaths.set(canonicalPath,pathName);const canonicalDisplays=displayPathsByCanonicalPath.get(canonicalPath)??new Set;canonicalDisplays.add(pathName);displayPathsByCanonicalPath.set(canonicalPath,canonicalDisplays);resolvedSuccessfully=true}catch(error){if(isNodeError(error)&&error.code==="ENOENT"){sawNotFound=true;continue}else{onDebugMessage(`Error stating path ${pathName}: ${getErrorMessage(error)}. Path ${pathName} will be skipped.`)}}if(resolvedSuccessfully){break}}if(!resolvedSuccessfully&&sawNotFound){let reanchored=false;if(config.isOmniEnabled?.()){const{reanchorRememberedMedia}=await import("./omni-H3GFC6KR.js");for(const dir of config.getWorkspaceContext().getDirectories()){const anchor=await reanchorRememberedMedia(config,path.resolve(dir,pathName));if(!anchor)continue;rememberedMediaRefs.push({originalAtPath,pathName,annotation:anchor.annotation});atPathToResolvedSpecMap.set(originalAtPath,pathName);onDebugMessage(`Path ${pathName} is gone but remembered; re-anchored as ${anchor.resourceId} (bytes unavailable).`);reanchored=true;break}}if(!reanchored){onDebugMessage(`Path ${pathName} not found. Path ${pathName} will be skipped.`)}}if(!resolvedSuccessfully&&deferredIgnoreReason){ignoredByReason[deferredIgnoreReason].push(pathName)}}const buildInitialQueryText=__name(()=>{let text="";for(let i=0;i<commandParts.length;i++){const part=commandParts[i];if(part.type==="text"){text+=part.content}else{const resolvedSpec=atPathToResolvedSpecMap.get(part.content);if(i>0&&text.length>0&&!text.endsWith(" ")){const prevPart=commandParts[i-1];if(prevPart.type==="text"||prevPart.type==="atPath"){text+=" "}}if(resolvedSpec){text+=`@${resolvedSpec}`}else{if(i>0&&text.length>0&&!text.endsWith(" ")&&!part.content.startsWith(" ")){text+=" "}text+=part.content}}}return text.trim()},"buildInitialQueryText");let initialQueryText=buildInitialQueryText();const totalIgnored=ignoredByReason["git"].length+ignoredByReason["qwen"].length+ignoredByReason["both"].length;if(totalIgnored>0){const messages=[];if(ignoredByReason["git"].length){messages.push(`Git-ignored: ${ignoredByReason["git"].join(", ")}`)}if(ignoredByReason["qwen"].length){messages.push(`Qwen-ignored: ${ignoredByReason["qwen"].join(", ")}`)}if(ignoredByReason["both"].length){messages.push(`Ignored by both: ${ignoredByReason["both"].join(", ")}`)}const message=`Ignored ${totalIgnored} files:
4
- ${messages.join("\n")}`;onDebugMessage(message)}const resourceReads=await Promise.allSettled(mcpResourceRefs.map(ref=>config.getToolRegistry().readMcpResource(ref.serverName,ref.uri,{signal})));const urlMediaParts=[];const urlMediaDisplays=[];const urlMediaLabels=[];if(urlMediaRefs.length>0){const core=await import("./omni-H3GFC6KR.js");for(let i=0;i<urlMediaRefs.length;i++){const ref=urlMediaRefs[i];const callId=`client-url-media-${userMessageTimestamp}-${i}`;const hostLabel=(()=>{try{return new URL(ref.url).hostname}catch{return"invalid-url"}})();let tempPartPath;try{const store=new core.OmniObjectStore(config.storage.getQwenDir());const downloadsDir=path.join(store.getOmniRootDir(),"downloads");const downloaded=await core.downloadMediaUrl({url:ref.url,downloadsDir,maxBytes:core.effectiveMaxDownloadFileBytes(config),signal});tempPartPath=downloaded.partPath;const urlBase=path.basename(new URL(ref.url).pathname)||hostLabel;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};const sniffedModality=await core.sniffFileModality(downloaded.partPath);if(sniffedModality&&!modalities[sniffedModality]){urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Skipped ${urlBase}: the active model does not accept ${sniffedModality} input.`,confirmationDetails:void 0});continue}const delivery=await core.processMediaForOmniDelivery(downloaded.partPath,config,{signal,displayName:urlBase,sourceUrl:ref.url});const transcriptParts=core.buildTranscriptParts(urlBase,delivery.transcripts);const additionalParts=core.buildAdditionalMediaParts(urlBase,delivery.additionalMedia);const handleParts=delivery.resourceId?[{text:core.formatResourceHandleText(urlBase,delivery.resourceId)}]:[];if(delivery.omission){urlMediaParts.push(...handleParts);urlMediaParts.push({text:core.formatOmissionText(urlBase,delivery.omission.reason)});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Media omitted by the omni transport guard: ${urlBase}`,confirmationDetails:void 0});continue}if(!delivery.fileUri&&transcriptParts.length>0){urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} and delivered as transcript (omni policy).`,confirmationDetails:void 0});continue}urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push({fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName:urlBase}});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} (${delivery.recognized.modality}, ${(delivery.recognized.sizeBytes/1024/1024).toFixed(1)}MB) and delivered via omni upload${delivery.degraded?" (degraded by media policy)":""}.`,confirmationDetails:void 0})}catch(error){if(signal.aborted){if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}return{processedQuery:null,shouldProceed:false,toolDisplays:[...urlMediaDisplays],filesRead:urlMediaLabels}}const reason=getErrorMessage(error);onDebugMessage(`Failed to localize media URL ${ref.url}: ${reason}`);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Failed to fetch media from ${hostLabel}: ${reason}`,confirmationDetails:void 0})}finally{if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}}}}const resourceParts=[];const resourceDisplays=[];const resourceLabels=[];for(let i=0;i<mcpResourceRefs.length;i++){const ref=mcpResourceRefs[i];const label=`${ref.serverName}:${ref.uri}`;const callId=`client-mcp-resource-${userMessageTimestamp}-${i}`;const outcome=resourceReads[i];if(outcome.status==="rejected"){onDebugMessage(`Failed to read MCP resource ${label}: ${getErrorMessage(outcome.reason)}`);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Error",resultDisplay:`Failed to read resource ${label}: ${getErrorMessage(outcome.reason)}`,confirmationDetails:void 0});continue}const formatted=formatMcpResourceContents(outcome.value,label);if(formatted.parts.length>0){resourceParts.push(...formatted.parts)}else{resourceParts.push({text:emptyMcpResourceText(formatted,label)})}resourceLabels.push(label);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Success",resultDisplay:summarizeMcpResource(formatted),confirmationDetails:void 0})}if(pathSpecsToRead.length===0&&mcpResourceRefs.length===0&&mcpServerMentions.length===0&&extensionMentions.length===0&&sessionMentions.length===0&&urlMediaRefs.length===0){onDebugMessage("No valid file paths found in @ commands to read.");if(initialQueryText==="@"&&query.trim()==="@"){return{processedQuery:[{text:query}],shouldProceed:true}}else if(!initialQueryText&&query){return{processedQuery:[{text:query}],shouldProceed:true}}return{processedQuery:[{text:initialQueryText||query}],shouldProceed:true}}let extensionContextBudgetRemaining=EXTENSION_CONTEXT_BUDGET;const scopedMentionEntries=[];for(let i=0;i<extensionMentions.length;i++){const{originalAtPath,extension}=extensionMentions[i];const displayName=getSanitizedExtensionDisplayName(extension);const callId=`client-extension-${userMessageTimestamp}-${i}`;const context=await buildExtensionMentionContext(extension,{remainingBudget:extensionContextBudgetRemaining,signal,onDebugMessage});extensionContextBudgetRemaining=context.remainingBudget;scopedMentionEntries.push({originalAtPath,part:{text:context.text},label:buildExtensionRef(extension.name),display:{callId,name:"Activate Extension",description:`Activated extension ${displayName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}for(let i=0;i<mcpServerMentions.length;i++){const{originalAtPath,serverName}=mcpServerMentions[i];scopedMentionEntries.push({originalAtPath,part:{text:buildMcpServerContextText(config,serverName)},label:buildMcpServerRef(serverName),display:{callId:`client-mcp-server-${userMessageTimestamp}-${i}`,name:"Activate MCP Server",description:`Activated MCP server ${serverName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const resolvedSessionIds=new Set;for(let i=0;i<sessionMentions.length;i++){const{originalAtPath,ref}=sessionMentions[i];const callId=`client-session-${userMessageTimestamp}-${i}`;let sessionId=ref.id;if(!sessionId&&ref.title){let matches=[];try{matches=await new SessionService(config.getProjectRoot()).findSessionsByTitle(ref.title)}catch(error){const reason=`Could not look up sessions matching "@${originalAtPath.substring(1)}" (${getErrorMessage(error)}); try a session id instead.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(matches.length===1){sessionId=matches[0].sessionId}else{const reason=matches.length===0?`No session matches "@${originalAtPath.substring(1)}".`:`"@${originalAtPath.substring(1)}" is ambiguous (${matches.length} matches); use the picker or a session id.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}}if(!sessionId){const reason=`Session reference "@${originalAtPath.substring(1)}" could not be resolved.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??ref.id??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??ref.id??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(resolvedSessionIds.has(sessionId)){onDebugMessage(`Session reference "@${originalAtPath.substring(1)}" resolves to session ${sessionId}, which was already referenced; skipping duplicate.`);continue}resolvedSessionIds.add(sessionId);let resolved;try{resolved=await new SessionReferenceService(config.getProjectRoot()).resolve(sessionId,ref.title?{title:ref.title}:{})}catch(error){const reason=`Failed to load session "${sessionId}" (${getErrorMessage(error)}); the transcript may be corrupted or unreadable.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if("notFound"in resolved){const reason=`Session "${sessionId}" not found in this project.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}scopedMentionEntries.push({originalAtPath,part:{text:resolved.text},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Referenced session "${resolved.meta.title}"${resolved.truncated?" (truncated)":""}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const scopedMentionOrder=new Map(atPathCommandParts.map((part,index)=>[part.content,index]));scopedMentionEntries.sort((a,b)=>(scopedMentionOrder.get(a.originalAtPath)??Number.MAX_SAFE_INTEGER)-(scopedMentionOrder.get(b.originalAtPath)??Number.MAX_SAFE_INTEGER));const scopedMentionParts=scopedMentionEntries.map(entry=>entry.part);const scopedMentionLabels=scopedMentionEntries.map(entry=>entry.label);const scopedMentionDisplays=scopedMentionEntries.map(entry=>entry.display);const fileParts=[];let fileDisplays=[];const revalidatedPathSpecs=[];const revalidatedDisplayPaths=new Map;const validatedPathIdentities=new Map;const pruneSkippedPath=__name(approvedPath=>{const displayPath=displayPaths.get(approvedPath);const displayLabels=displayPathsByCanonicalPath.get(approvedPath)??new Set(displayPath?[displayPath]:[]);for(const[originalAtPath,resolvedSpec]of atPathToResolvedSpecMap){if(resolvedSpec===approvedPath||displayLabels.has(resolvedSpec)){atPathToResolvedSpecMap.delete(originalAtPath)}}for(let index=contentLabelsForDisplay.length-1;index>=0;index--){const label=contentLabelsForDisplay[index];if(label===approvedPath||displayLabels.has(label)){contentLabelsForDisplay.splice(index,1)}}},"pruneSkippedPath");for(const approvedPath of pathSpecsToRead){try{const currentPath=await fs.realpath(approvedPath);const stats=await fs.stat(currentPath);if(currentPath===approvedPath&&(stats.isFile()||stats.isDirectory())&&(isSubpath(configuredProjectTempDir,currentPath)||isSubpath(projectTempDir,currentPath)||config.getWorkspaceContext().isPathWithinWorkspace(currentPath))&&getIgnoreReason(currentPath)===void 0){revalidatedPathSpecs.push(currentPath);const displayPath=displayPaths.get(approvedPath);if(displayPath)revalidatedDisplayPaths.set(currentPath,displayPath);validatedPathIdentities.set(currentPath,{dev:stats.dev,ino:stats.ino})}else{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} failed revalidation and will be skipped.`)}}catch{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} changed before it could be read and will be skipped.`)}}initialQueryText=buildInitialQueryText();if(revalidatedPathSpecs.length>0){try{const result=await readManyFiles(config,{paths:revalidatedPathSpecs,signal,preserveUnsupportedImageForBridge:shouldRunVisionBridge(config),validatedPathIdentities,displayPaths:revalidatedDisplayPaths});const parts=Array.isArray(result.contentParts)?result.contentParts:[result.contentParts];fileDisplays=result.files.map((file,index)=>({callId:`client-read-${userMessageTimestamp}-${index}`,name:file.isDirectory?"Read Directory":"Read File",description:`@${path.basename(file.filePath)}`,status:file.error?"Error":"Success",resultDisplay:file.error?`Failed to read ${path.basename(file.filePath)}: ${file.error}`:void 0,confirmationDetails:void 0}));if(parts.length>0&&!result.error){for(const part of parts){fileParts.push(typeof part==="string"?{text:part}:part)}}else{onDebugMessage("readManyFiles returned no content or empty content.")}}catch(error){const errorToolCallDisplay={callId:`client-read-${userMessageTimestamp}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:`Error reading files (${contentLabelsForDisplay.join(", ")}): ${getErrorMessage(error)}`,confirmationDetails:void 0};const errorMessage=typeof errorToolCallDisplay.resultDisplay==="string"?errorToolCallDisplay.resultDisplay:void 0;const labelsOnError=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels];return{processedQuery:null,shouldProceed:false,toolDisplays:[...scopedMentionDisplays,...resourceDisplays,...urlMediaDisplays,errorToolCallDisplay],filesRead:labelsOnError,recording:{filesRead:labelsOnError,status:"error",message:errorMessage}}}}const rememberedMediaParts=rememberedMediaRefs.flatMap(ref=>[{text:ref.annotation},{text:`\u3010\u5A92\u4F53\u7F3A\u5931\u3011${ref.pathName}\uFF1A\u6587\u4EF6\u5DF2\u4E0D\u5728\u78C1\u76D8\u4E0A\uFF0C\u65E0\u6CD5\u6295\u9012\u753B\u9762/\u97F3\u9891\u3002\u5176\u5904\u7406\u8BB0\u5FC6\u4ECD\u53EF\u7528\u2014\u2014\u7528\u4E0A\u9762\u7684\u53E5\u67C4\u8C03\u7528 omni_recall_media_memory \u53D6\u56DE\u3002`}]);const processedQueryParts=[{text:initialQueryText},...scopedMentionParts,...fileParts,...resourceParts,...urlMediaParts,...rememberedMediaParts];const allLabels=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels,...rememberedMediaRefs.map(ref=>`${ref.pathName} (\u8BB0\u5FC6)`)];return{processedQuery:processedQueryParts,shouldProceed:true,toolDisplays:[...scopedMentionDisplays,...fileDisplays,...resourceDisplays,...urlMediaDisplays],filesRead:allLabels,recording:{filesRead:allLabels,status:"success"}}}__name(resolveAtCommandQuery,"resolveAtCommandQuery");async function handleAtCommand(params){const result=await resolveAtCommandQuery(params);if(result.recording){const chatRecorder=params.config.getChatRecordingService?.();chatRecorder?.recordAtCommand({filesRead:result.recording.filesRead,status:result.recording.status,...result.recording.message?{message:result.recording.message}:{},userText:params.query})}if(params.addItem&&result.toolDisplays&&result.toolDisplays.length>0){const toolGroupItem={type:"tool_group",tools:result.toolDisplays};params.addItem(toolGroupItem,params.messageId)}return{processedQuery:result.processedQuery,shouldProceed:result.shouldProceed,toolDisplays:result.toolDisplays,filesRead:result.filesRead}}__name(handleAtCommand,"handleAtCommand");export{matchMcpServerPrefix,buildMcpResourceRef,MAX_SUGGESTIONS_TO_SHOW,normalizeDescription,getExtensionSuggestions,SESSION_MENTION_PREFIX,buildSessionRef,parseMcpServerRef,buildMcpServerRef,matchMcpServerByRef,buildMcpServerContextText,extractAtPathCommands,resolveAtCommandQuery,handleAtCommand};
3
+ import{EXTENSION_CONTEXT_BUDGET,buildExtensionMentionContext,buildExtensionRef,getSanitizedExtensionDisplayName,matchExtensionByRef,parseExtensionRef,sanitizeDisplayText}from"./chunk-3C34EMBZ.js";import{t}from"./chunk-4IE26CIN.js";import{SessionReferenceService,readManyFiles}from"./chunk-RV54BGL2.js";import{emptyMcpResourceText,formatMcpResourceContents,summarizeMcpResource}from"./chunk-46VUDNCL.js";import{SessionService}from"./chunk-IFAUFERF.js";import{shouldRunVisionBridge}from"./chunk-KBPIYGHG.js";import{Storage}from"./chunk-EPODBRBP.js";import{isSubpath,unescapePath,unescapeShellSpecials}from"./chunk-OKN3Z5C5.js";import{getErrorMessage,isNodeError}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import*as fs from"node:fs/promises";import*as path from"node:path";init_esbuild_shims();function matchMcpServerPrefix(input,serverNames){let serverName=null;for(const name of serverNames){if(input.startsWith(`${name}:`)&&(serverName===null||name.length>serverName.length)){serverName=name}}if(serverName===null)return null;return{serverName,rest:input.slice(serverName.length+1)}}__name(matchMcpServerPrefix,"matchMcpServerPrefix");function buildMcpResourceRef(serverName,uri){return`${serverName}:${uri}`}__name(buildMcpResourceRef,"buildMcpResourceRef");init_esbuild_shims();init_esbuild_shims();var MAX_SUGGESTIONS_TO_SHOW=8;function normalizeDescription(description){return description.replace(/\s+/g," ").trim()}__name(normalizeDescription,"normalizeDescription");function getExtensionSuggestions(config,pattern){if(!config)return[];if(config.isTrustedFolder?.()===false)return[];const extensions=config.getActiveExtensions?.()??[];if(extensions.length===0)return[];const query=pattern.toLowerCase();return extensions.map(ext=>({ext,safeLabel:sanitizeDisplayText(ext.displayName||ext.name)||ext.name})).filter(({safeLabel,ext})=>{const label=safeLabel.toLowerCase();const name=ext.name.toLowerCase();return label.includes(query)||name.includes(query)}).sort((a,b)=>{const aName=a.safeLabel.toLowerCase();const bName=b.safeLabel.toLowerCase();const aPrefix=aName.startsWith(query)?0:1;const bPrefix=bName.startsWith(query)?0:1;if(aPrefix!==bPrefix)return aPrefix-bPrefix;return aName.localeCompare(bName)}).slice(0,MAX_SUGGESTIONS_TO_SHOW).map(({ext,safeLabel})=>({label:safeLabel,value:buildExtensionRef(ext.name),description:ext.config.description?sanitizeDisplayText(ext.config.description)??void 0:void 0,sourceBadge:t("Extension"),isDirectory:false,category:"extension"}))}__name(getExtensionSuggestions,"getExtensionSuggestions");init_esbuild_shims();var SESSION_MENTION_PREFIX="session:";var UUID_RE=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function isSessionId(value){return UUID_RE.test(value.trim())}__name(isSessionId,"isSessionId");function parseSessionRef(pathName){if(!pathName.startsWith(SESSION_MENTION_PREFIX))return null;const rawRemainder=pathName.slice(SESSION_MENTION_PREFIX.length).trim();const remainder=process.platform==="win32"?unescapeShellSpecials(rawRemainder):rawRemainder;if(remainder.length===0)return null;return isSessionId(remainder)?{id:remainder}:{title:remainder}}__name(parseSessionRef,"parseSessionRef");function buildSessionRef(idOrTitle){return`${SESSION_MENTION_PREFIX}${idOrTitle}`}__name(buildSessionRef,"buildSessionRef");init_esbuild_shims();var MCP_SERVER_REF_PREFIX="mcp:";function parseMcpServerRef(pathName){if(!pathName.startsWith(MCP_SERVER_REF_PREFIX))return null;const name=pathName.slice(MCP_SERVER_REF_PREFIX.length);if(!name)return null;return{name}}__name(parseMcpServerRef,"parseMcpServerRef");function buildMcpServerRef(serverName){return`${MCP_SERVER_REF_PREFIX}${serverName}`}__name(buildMcpServerRef,"buildMcpServerRef");function matchMcpServerByRef(name,servers){const lower=name.toLowerCase();const matchedName=Object.keys(servers).find(serverName=>serverName.toLowerCase()===lower);if(!matchedName)return void 0;return{serverName:matchedName,server:servers[matchedName]}}__name(matchMcpServerByRef,"matchMcpServerByRef");function buildMcpServerContextText(config,serverName){const lines=[`--- MCP Server: ${serverName} ---`,`The user explicitly mentioned this MCP server. Prefer using tools and resources from this server when relevant for this turn. This is advisory context, not a hard restriction.`];const prompts=config.getPromptRegistry?.()?.getPromptsByServer(serverName)??[];const resources=config.getResourceRegistry?.()?.getResourcesByServer(serverName)??[];const details=[];if(resources.length>0){details.push(`- Resources: ${resources.length}`)}if(prompts.length>0){details.push(`- Prompts: ${prompts.length}`)}if(details.length>0){lines.push("Available capabilities from this MCP server:");lines.push(...details)}lines.push(`--- End MCP Server: ${serverName} ---`);return lines.join("\n")}__name(buildMcpServerContextText,"buildMcpServerContextText");function parseAllAtCommands(query){const parts=[];let currentIndex=0;while(currentIndex<query.length){let atIndex=-1;let nextSearchIndex=currentIndex;while(nextSearchIndex<query.length){if(query[nextSearchIndex]==="@"&&(nextSearchIndex===0||query[nextSearchIndex-1]!=="\\")){atIndex=nextSearchIndex;break}nextSearchIndex++}if(atIndex===-1){if(currentIndex<query.length){parts.push({type:"text",content:query.substring(currentIndex)})}break}if(atIndex>currentIndex){parts.push({type:"text",content:query.substring(currentIndex,atIndex)})}const isUrlRef=/^https?:\/\//i.test(query.slice(atIndex+1));const NON_URL_CHAR=/[^A-Za-z0-9\-._~:/?#[\]@!$&'()*+,;=%]/;let pathEndIndex=atIndex+1;let inEscape=false;while(pathEndIndex<query.length){const char=query[pathEndIndex];if(inEscape){inEscape=false}else if(char==="\\"){inEscape=true}else if(isUrlRef){if(NON_URL_CHAR.test(char))break}else if(/[,\s;!?()[\]{}]/.test(char)){break}else if(char==="."){const nextChar=pathEndIndex+1<query.length?query[pathEndIndex+1]:"";if(nextChar===""||/\s/.test(nextChar)){break}}pathEndIndex++}let rawAtPath=query.substring(atIndex,pathEndIndex);if(isUrlRef){const trimmed=rawAtPath.replace(/[.,;:!?]+$/,"");pathEndIndex=atIndex+trimmed.length;rawAtPath=trimmed}const atPath=unescapePath(rawAtPath);parts.push({type:"atPath",content:atPath});currentIndex=pathEndIndex}return parts.filter(part=>!(part.type==="text"&&part.content.trim()===""))}__name(parseAllAtCommands,"parseAllAtCommands");function extractAtPathCommands(query){return parseAllAtCommands(query).flatMap(part=>part.type==="atPath"&&part.content!=="@"?[part.content.substring(1)]:[])}__name(extractAtPathCommands,"extractAtPathCommands");function parseMcpResourceRef(pathName,mcpServerNames){const match=matchMcpServerPrefix(pathName,mcpServerNames);if(!match||!match.rest)return null;return{serverName:match.serverName,uri:match.rest}}__name(parseMcpResourceRef,"parseMcpResourceRef");async function resolveAtCommandQuery({query,config,onDebugMessage,messageId:userMessageTimestamp,signal}){const commandParts=parseAllAtCommands(query);const atPathCommandParts=commandParts.filter(part=>part.type==="atPath");if(atPathCommandParts.length===0){return{processedQuery:[{text:query}],shouldProceed:true}}const fileDiscovery=config.getFileService();const respectFileIgnore=config.getFileFilteringOptions();const configuredProjectTempDir=Storage.getGlobalTempDir();const projectTempDir=await fs.realpath(configuredProjectTempDir).catch(()=>path.resolve(configuredProjectTempDir));const pathSpecsToRead=[];const atPathToResolvedSpecMap=new Map;const contentLabelsForDisplay=[];const displayPaths=new Map;const displayPathsByCanonicalPath=new Map;const ignoredByReason={git:[],qwen:[],both:[]};const getIgnoreReason=__name(candidate=>{const gitIgnored=respectFileIgnore.respectGitIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:true,respectQwenIgnore:false});const qwenIgnored=respectFileIgnore.respectQwenIgnore&&fileDiscovery.shouldIgnoreFile(candidate,{respectGitIgnore:false,respectQwenIgnore:true});return gitIgnored&&qwenIgnored?"both":gitIgnored?"git":qwenIgnored?"qwen":void 0},"getIgnoreReason");const mcpServerNames=new Set(Object.keys(config.getMcpServers()||{}));const mcpResourceRefs=[];const mcpServerMentions=[];const activeExtensions=config.getActiveExtensions?.()??[];const extensionMentions=[];const sessionMentions=[];const urlMediaRefs=[];const rememberedMediaRefs=[];for(const atPathPart of atPathCommandParts){const originalAtPath=atPathPart.content;if(originalAtPath==="@"){onDebugMessage("Lone @ detected, will be treated as text in the modified query.");continue}const pathName=originalAtPath.substring(1);if(/^https?:\/\//i.test(pathName)&&config.isOmniEnabled?.()){const omni=await import("./omni-MEUE65XC.js");if(omni.isOmniDeliveryActive(config)&&omni.parseHttpUrlRef(pathName)){if(!urlMediaRefs.some(r=>r.url===pathName)){urlMediaRefs.push({originalAtPath,url:pathName})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}}const extRef=parseExtensionRef(pathName);if(extRef){const extension=matchExtensionByRef(extRef.name,activeExtensions);if(extension){if(!extensionMentions.some(m=>m.extension.name===extension.name)){extensionMentions.push({originalAtPath,extension})}atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}onDebugMessage(`Extension "${extRef.name}" not found among active extensions. Available: ${activeExtensions.map(e=>e.name).join(", ")||"(none)"}`);continue}const sessionRef=parseSessionRef(pathName);if(sessionRef){if(!sessionMentions.some(m=>(m.ref.id??m.ref.title)===(sessionRef.id??sessionRef.title))){sessionMentions.push({originalAtPath,ref:sessionRef})}atPathToResolvedSpecMap.set(originalAtPath,buildSessionRef(sessionRef.id??sessionRef.title));continue}const resourceRef=parseMcpResourceRef(pathName,mcpServerNames);if(resourceRef){mcpResourceRefs.push({originalAtPath,...resourceRef});atPathToResolvedSpecMap.set(originalAtPath,pathName);continue}const mcpServerRef=parseMcpServerRef(pathName);if(mcpServerRef){const matched=matchMcpServerByRef(mcpServerRef.name,config.getMcpServers()||{});if(matched){if(!mcpServerMentions.some(m=>m.serverName===matched.serverName)){mcpServerMentions.push({originalAtPath,serverName:matched.serverName})}atPathToResolvedSpecMap.set(originalAtPath,buildMcpServerRef(matched.serverName));continue}onDebugMessage(`MCP server "${mcpServerRef.name}" not found among configured MCP servers. Available: ${Object.keys(config.getMcpServers()||{}).join(", ")||"(none)"}`);continue}const workspaceContext=config.getWorkspaceContext();const absolutePathName=path.isAbsolute(pathName)?pathName:path.resolve(workspaceContext.getDirectories()[0]||"",pathName);if(!isSubpath(configuredProjectTempDir,absolutePathName)&&!isSubpath(projectTempDir,absolutePathName)&&!workspaceContext.isPathWithinWorkspace(pathName)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const ignoredReason=getIgnoreReason(pathName);if(ignoredReason){const reason=ignoredReason;ignoredByReason[reason].push(pathName);const reasonText=reason==="both"?"ignored by both git and qwen":reason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}let resolvedSuccessfully=false;let sawNotFound=false;let deferredIgnoreReason;for(const dir of config.getWorkspaceContext().getDirectories()){try{const absolutePath=path.resolve(dir,pathName);const canonicalPath=await fs.realpath(absolutePath);const stats=await fs.stat(canonicalPath);if(!isSubpath(configuredProjectTempDir,canonicalPath)&&!isSubpath(projectTempDir,canonicalPath)&&!workspaceContext.isPathWithinWorkspace(canonicalPath)){onDebugMessage(`Path ${pathName} is not in the workspace and will be skipped.`);continue}const canonicalIgnoreReason=getIgnoreReason(canonicalPath);if(canonicalIgnoreReason){deferredIgnoreReason=canonicalIgnoreReason;const reasonText=canonicalIgnoreReason==="both"?"ignored by both git and qwen":canonicalIgnoreReason==="git"?"git-ignored":"qwen-ignored";onDebugMessage(`Path ${pathName} is ${reasonText} and will be skipped.`);continue}if(stats.isDirectory()){onDebugMessage(`Path ${pathName} resolved to directory.`)}else{onDebugMessage(`Path ${pathName} resolved to file: ${absolutePath}`)}pathSpecsToRead.push(canonicalPath);atPathToResolvedSpecMap.set(originalAtPath,pathName);contentLabelsForDisplay.push(pathName);displayPaths.set(canonicalPath,pathName);const canonicalDisplays=displayPathsByCanonicalPath.get(canonicalPath)??new Set;canonicalDisplays.add(pathName);displayPathsByCanonicalPath.set(canonicalPath,canonicalDisplays);resolvedSuccessfully=true}catch(error){if(isNodeError(error)&&error.code==="ENOENT"){sawNotFound=true;continue}else{onDebugMessage(`Error stating path ${pathName}: ${getErrorMessage(error)}. Path ${pathName} will be skipped.`)}}if(resolvedSuccessfully){break}}if(!resolvedSuccessfully&&sawNotFound){let reanchored=false;if(config.isOmniEnabled?.()){const{reanchorRememberedMedia}=await import("./omni-MEUE65XC.js");for(const dir of config.getWorkspaceContext().getDirectories()){const anchor=await reanchorRememberedMedia(config,path.resolve(dir,pathName));if(!anchor)continue;rememberedMediaRefs.push({originalAtPath,pathName,annotation:anchor.annotation});atPathToResolvedSpecMap.set(originalAtPath,pathName);onDebugMessage(`Path ${pathName} is gone but remembered; re-anchored as ${anchor.resourceId} (bytes unavailable).`);reanchored=true;break}}if(!reanchored){onDebugMessage(`Path ${pathName} not found. Path ${pathName} will be skipped.`)}}if(!resolvedSuccessfully&&deferredIgnoreReason){ignoredByReason[deferredIgnoreReason].push(pathName)}}const buildInitialQueryText=__name(()=>{let text="";for(let i=0;i<commandParts.length;i++){const part=commandParts[i];if(part.type==="text"){text+=part.content}else{const resolvedSpec=atPathToResolvedSpecMap.get(part.content);if(i>0&&text.length>0&&!text.endsWith(" ")){const prevPart=commandParts[i-1];if(prevPart.type==="text"||prevPart.type==="atPath"){text+=" "}}if(resolvedSpec){text+=`@${resolvedSpec}`}else{if(i>0&&text.length>0&&!text.endsWith(" ")&&!part.content.startsWith(" ")){text+=" "}text+=part.content}}}return text.trim()},"buildInitialQueryText");let initialQueryText=buildInitialQueryText();const totalIgnored=ignoredByReason["git"].length+ignoredByReason["qwen"].length+ignoredByReason["both"].length;if(totalIgnored>0){const messages=[];if(ignoredByReason["git"].length){messages.push(`Git-ignored: ${ignoredByReason["git"].join(", ")}`)}if(ignoredByReason["qwen"].length){messages.push(`Qwen-ignored: ${ignoredByReason["qwen"].join(", ")}`)}if(ignoredByReason["both"].length){messages.push(`Ignored by both: ${ignoredByReason["both"].join(", ")}`)}const message=`Ignored ${totalIgnored} files:
4
+ ${messages.join("\n")}`;onDebugMessage(message)}const resourceReads=await Promise.allSettled(mcpResourceRefs.map(ref=>config.getToolRegistry().readMcpResource(ref.serverName,ref.uri,{signal})));const urlMediaParts=[];const urlMediaDisplays=[];const urlMediaLabels=[];if(urlMediaRefs.length>0){const core=await import("./omni-MEUE65XC.js");for(let i=0;i<urlMediaRefs.length;i++){const ref=urlMediaRefs[i];const callId=`client-url-media-${userMessageTimestamp}-${i}`;const hostLabel=(()=>{try{return new URL(ref.url).hostname}catch{return"invalid-url"}})();let tempPartPath;try{const store=new core.OmniObjectStore(config.storage.getQwenDir());const downloadsDir=path.join(store.getOmniRootDir(),"downloads");const downloaded=await core.downloadMediaUrl({url:ref.url,downloadsDir,maxBytes:core.effectiveMaxDownloadFileBytes(config),signal});tempPartPath=downloaded.partPath;const urlBase=path.basename(new URL(ref.url).pathname)||hostLabel;const modalities=config.getContentGeneratorConfig?.()?.modalities??{};const sniffedModality=await core.sniffFileModality(downloaded.partPath);if(sniffedModality&&!modalities[sniffedModality]){urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Skipped ${urlBase}: the active model does not accept ${sniffedModality} input.`,confirmationDetails:void 0});continue}const delivery=await core.processMediaForOmniDelivery(downloaded.partPath,config,{signal,displayName:urlBase,sourceUrl:ref.url});const transcriptParts=core.buildTranscriptParts(urlBase,delivery.transcripts);const additionalParts=core.buildAdditionalMediaParts(urlBase,delivery.additionalMedia);const handleParts=delivery.resourceId?[{text:core.formatResourceHandleText(urlBase,delivery.resourceId)}]:[];if(delivery.omission){urlMediaParts.push(...handleParts);urlMediaParts.push({text:core.formatOmissionText(urlBase,delivery.omission.reason)});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Media omitted by the omni transport guard: ${urlBase}`,confirmationDetails:void 0});continue}if(!delivery.fileUri&&transcriptParts.length>0){urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} and delivered as transcript (omni policy).`,confirmationDetails:void 0});continue}urlMediaParts.push(...handleParts);if(delivery.disclosure){urlMediaParts.push({text:core.formatDisclosureText(urlBase,delivery.disclosure)})}urlMediaParts.push({fileData:{fileUri:delivery.fileUri,mimeType:delivery.mimeType,displayName:urlBase}});urlMediaParts.push(...additionalParts);urlMediaParts.push(...transcriptParts);urlMediaLabels.push(ref.url);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Downloaded ${ref.url}`,status:"Success",resultDisplay:`Localized ${urlBase} (${delivery.recognized.modality}, ${(delivery.recognized.sizeBytes/1024/1024).toFixed(1)}MB) and delivered via omni upload${delivery.degraded?" (degraded by media policy)":""}.`,confirmationDetails:void 0})}catch(error){if(signal.aborted){if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}return{processedQuery:null,shouldProceed:false,toolDisplays:[...urlMediaDisplays],filesRead:urlMediaLabels}}const reason=getErrorMessage(error);onDebugMessage(`Failed to localize media URL ${ref.url}: ${reason}`);urlMediaDisplays.push({callId,name:"Fetch Media URL",description:`Download ${ref.url}`,status:"Error",resultDisplay:`Failed to fetch media from ${hostLabel}: ${reason}`,confirmationDetails:void 0})}finally{if(tempPartPath){await fs.rm(tempPartPath,{force:true}).catch(()=>{})}}}}const resourceParts=[];const resourceDisplays=[];const resourceLabels=[];for(let i=0;i<mcpResourceRefs.length;i++){const ref=mcpResourceRefs[i];const label=`${ref.serverName}:${ref.uri}`;const callId=`client-mcp-resource-${userMessageTimestamp}-${i}`;const outcome=resourceReads[i];if(outcome.status==="rejected"){onDebugMessage(`Failed to read MCP resource ${label}: ${getErrorMessage(outcome.reason)}`);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Error",resultDisplay:`Failed to read resource ${label}: ${getErrorMessage(outcome.reason)}`,confirmationDetails:void 0});continue}const formatted=formatMcpResourceContents(outcome.value,label);if(formatted.parts.length>0){resourceParts.push(...formatted.parts)}else{resourceParts.push({text:emptyMcpResourceText(formatted,label)})}resourceLabels.push(label);resourceDisplays.push({callId,name:"Read MCP Resource",description:`Read resource ${label}`,status:"Success",resultDisplay:summarizeMcpResource(formatted),confirmationDetails:void 0})}if(pathSpecsToRead.length===0&&mcpResourceRefs.length===0&&mcpServerMentions.length===0&&extensionMentions.length===0&&sessionMentions.length===0&&urlMediaRefs.length===0){onDebugMessage("No valid file paths found in @ commands to read.");if(initialQueryText==="@"&&query.trim()==="@"){return{processedQuery:[{text:query}],shouldProceed:true}}else if(!initialQueryText&&query){return{processedQuery:[{text:query}],shouldProceed:true}}return{processedQuery:[{text:initialQueryText||query}],shouldProceed:true}}let extensionContextBudgetRemaining=EXTENSION_CONTEXT_BUDGET;const scopedMentionEntries=[];for(let i=0;i<extensionMentions.length;i++){const{originalAtPath,extension}=extensionMentions[i];const displayName=getSanitizedExtensionDisplayName(extension);const callId=`client-extension-${userMessageTimestamp}-${i}`;const context=await buildExtensionMentionContext(extension,{remainingBudget:extensionContextBudgetRemaining,signal,onDebugMessage});extensionContextBudgetRemaining=context.remainingBudget;scopedMentionEntries.push({originalAtPath,part:{text:context.text},label:buildExtensionRef(extension.name),display:{callId,name:"Activate Extension",description:`Activated extension ${displayName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}for(let i=0;i<mcpServerMentions.length;i++){const{originalAtPath,serverName}=mcpServerMentions[i];scopedMentionEntries.push({originalAtPath,part:{text:buildMcpServerContextText(config,serverName)},label:buildMcpServerRef(serverName),display:{callId:`client-mcp-server-${userMessageTimestamp}-${i}`,name:"Activate MCP Server",description:`Activated MCP server ${serverName}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const resolvedSessionIds=new Set;for(let i=0;i<sessionMentions.length;i++){const{originalAtPath,ref}=sessionMentions[i];const callId=`client-session-${userMessageTimestamp}-${i}`;let sessionId=ref.id;if(!sessionId&&ref.title){let matches=[];try{matches=await new SessionService(config.getProjectRoot()).findSessionsByTitle(ref.title)}catch(error){const reason=`Could not look up sessions matching "@${originalAtPath.substring(1)}" (${getErrorMessage(error)}); try a session id instead.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(matches.length===1){sessionId=matches[0].sessionId}else{const reason=matches.length===0?`No session matches "@${originalAtPath.substring(1)}".`:`"@${originalAtPath.substring(1)}" is ambiguous (${matches.length} matches); use the picker or a session id.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}}if(!sessionId){const reason=`Session reference "@${originalAtPath.substring(1)}" could not be resolved.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(ref.title??ref.id??originalAtPath),display:{callId,name:"Referenced Session",description:`Reference session "${ref.title??ref.id??""}"`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if(resolvedSessionIds.has(sessionId)){onDebugMessage(`Session reference "@${originalAtPath.substring(1)}" resolves to session ${sessionId}, which was already referenced; skipping duplicate.`);continue}resolvedSessionIds.add(sessionId);let resolved;try{resolved=await new SessionReferenceService(config.getProjectRoot()).resolve(sessionId,ref.title?{title:ref.title}:{})}catch(error){const reason=`Failed to load session "${sessionId}" (${getErrorMessage(error)}); the transcript may be corrupted or unreadable.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}if("notFound"in resolved){const reason=`Session "${sessionId}" not found in this project.`;onDebugMessage(reason);scopedMentionEntries.push({originalAtPath,part:{text:""},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Reference session ${sessionId}`,status:"Error",resultDisplay:reason,confirmationDetails:void 0}});continue}scopedMentionEntries.push({originalAtPath,part:{text:resolved.text},label:buildSessionRef(sessionId),display:{callId,name:"Referenced Session",description:`Referenced session "${resolved.meta.title}"${resolved.truncated?" (truncated)":""}`,status:"Success",resultDisplay:void 0,confirmationDetails:void 0}})}const scopedMentionOrder=new Map(atPathCommandParts.map((part,index)=>[part.content,index]));scopedMentionEntries.sort((a,b)=>(scopedMentionOrder.get(a.originalAtPath)??Number.MAX_SAFE_INTEGER)-(scopedMentionOrder.get(b.originalAtPath)??Number.MAX_SAFE_INTEGER));const scopedMentionParts=scopedMentionEntries.map(entry=>entry.part);const scopedMentionLabels=scopedMentionEntries.map(entry=>entry.label);const scopedMentionDisplays=scopedMentionEntries.map(entry=>entry.display);const fileParts=[];let fileDisplays=[];const revalidatedPathSpecs=[];const revalidatedDisplayPaths=new Map;const validatedPathIdentities=new Map;const pruneSkippedPath=__name(approvedPath=>{const displayPath=displayPaths.get(approvedPath);const displayLabels=displayPathsByCanonicalPath.get(approvedPath)??new Set(displayPath?[displayPath]:[]);for(const[originalAtPath,resolvedSpec]of atPathToResolvedSpecMap){if(resolvedSpec===approvedPath||displayLabels.has(resolvedSpec)){atPathToResolvedSpecMap.delete(originalAtPath)}}for(let index=contentLabelsForDisplay.length-1;index>=0;index--){const label=contentLabelsForDisplay[index];if(label===approvedPath||displayLabels.has(label)){contentLabelsForDisplay.splice(index,1)}}},"pruneSkippedPath");for(const approvedPath of pathSpecsToRead){try{const currentPath=await fs.realpath(approvedPath);const stats=await fs.stat(currentPath);if(currentPath===approvedPath&&(stats.isFile()||stats.isDirectory())&&(isSubpath(configuredProjectTempDir,currentPath)||isSubpath(projectTempDir,currentPath)||config.getWorkspaceContext().isPathWithinWorkspace(currentPath))&&getIgnoreReason(currentPath)===void 0){revalidatedPathSpecs.push(currentPath);const displayPath=displayPaths.get(approvedPath);if(displayPath)revalidatedDisplayPaths.set(currentPath,displayPath);validatedPathIdentities.set(currentPath,{dev:stats.dev,ino:stats.ino})}else{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} failed revalidation and will be skipped.`)}}catch{pruneSkippedPath(approvedPath);onDebugMessage(`Path ${approvedPath} changed before it could be read and will be skipped.`)}}initialQueryText=buildInitialQueryText();if(revalidatedPathSpecs.length>0){try{const result=await readManyFiles(config,{paths:revalidatedPathSpecs,signal,preserveUnsupportedImageForBridge:shouldRunVisionBridge(config),validatedPathIdentities,displayPaths:revalidatedDisplayPaths});const parts=Array.isArray(result.contentParts)?result.contentParts:[result.contentParts];fileDisplays=result.files.map((file,index)=>({callId:`client-read-${userMessageTimestamp}-${index}`,name:file.isDirectory?"Read Directory":"Read File",description:`@${path.basename(file.filePath)}`,status:file.error?"Error":"Success",resultDisplay:file.error?`Failed to read ${path.basename(file.filePath)}: ${file.error}`:void 0,confirmationDetails:void 0}));if(parts.length>0&&!result.error){for(const part of parts){fileParts.push(typeof part==="string"?{text:part}:part)}}else{onDebugMessage("readManyFiles returned no content or empty content.")}}catch(error){const errorToolCallDisplay={callId:`client-read-${userMessageTimestamp}`,name:"Read File(s)",description:"Error attempting to read files",status:"Error",resultDisplay:`Error reading files (${contentLabelsForDisplay.join(", ")}): ${getErrorMessage(error)}`,confirmationDetails:void 0};const errorMessage=typeof errorToolCallDisplay.resultDisplay==="string"?errorToolCallDisplay.resultDisplay:void 0;const labelsOnError=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels];return{processedQuery:null,shouldProceed:false,toolDisplays:[...scopedMentionDisplays,...resourceDisplays,...urlMediaDisplays,errorToolCallDisplay],filesRead:labelsOnError,recording:{filesRead:labelsOnError,status:"error",message:errorMessage}}}}const rememberedMediaParts=rememberedMediaRefs.flatMap(ref=>[{text:ref.annotation},{text:`\u3010\u5A92\u4F53\u7F3A\u5931\u3011${ref.pathName}\uFF1A\u6587\u4EF6\u5DF2\u4E0D\u5728\u78C1\u76D8\u4E0A\uFF0C\u65E0\u6CD5\u6295\u9012\u753B\u9762/\u97F3\u9891\u3002\u5176\u5904\u7406\u8BB0\u5FC6\u4ECD\u53EF\u7528\u2014\u2014\u7528\u4E0A\u9762\u7684\u53E5\u67C4\u8C03\u7528 omni_recall_media_memory \u53D6\u56DE\u3002`}]);const processedQueryParts=[{text:initialQueryText},...scopedMentionParts,...fileParts,...resourceParts,...urlMediaParts,...rememberedMediaParts];const allLabels=[...scopedMentionLabels,...contentLabelsForDisplay,...resourceLabels,...urlMediaLabels,...rememberedMediaRefs.map(ref=>`${ref.pathName} (\u8BB0\u5FC6)`)];return{processedQuery:processedQueryParts,shouldProceed:true,toolDisplays:[...scopedMentionDisplays,...fileDisplays,...resourceDisplays,...urlMediaDisplays],filesRead:allLabels,recording:{filesRead:allLabels,status:"success"}}}__name(resolveAtCommandQuery,"resolveAtCommandQuery");async function handleAtCommand(params){const result=await resolveAtCommandQuery(params);if(result.recording){const chatRecorder=params.config.getChatRecordingService?.();chatRecorder?.recordAtCommand({filesRead:result.recording.filesRead,status:result.recording.status,...result.recording.message?{message:result.recording.message}:{},userText:params.query})}if(params.addItem&&result.toolDisplays&&result.toolDisplays.length>0){const toolGroupItem={type:"tool_group",tools:result.toolDisplays};params.addItem(toolGroupItem,params.messageId)}return{processedQuery:result.processedQuery,shouldProceed:result.shouldProceed,toolDisplays:result.toolDisplays,filesRead:result.filesRead}}__name(handleAtCommand,"handleAtCommand");export{matchMcpServerPrefix,buildMcpResourceRef,MAX_SUGGESTIONS_TO_SHOW,normalizeDescription,getExtensionSuggestions,SESSION_MENTION_PREFIX,buildSessionRef,parseMcpServerRef,buildMcpServerRef,matchMcpServerByRef,buildMcpServerContextText,extractAtPathCommands,resolveAtCommandQuery,handleAtCommand};
5
5
  /**
6
6
  * @license
7
7
  * Copyright 2025 Google LLC