@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,3 +1,3 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{DEFAULT_DASHSCOPE_BASE_URL,DEFAULT_MAX_RETRIES,buildSessionAwareFetch,getDashscopeProxyBaseUrl,getEffectiveReasoning,isOpenRouterHostname,resolveReasoningForModel,resolveRequestTimeout}from"./chunk-KAEW65QP.js";import{REASONING_EFFORT_TIERS,clampReasoningEffort,defaultOutputCeiling,getGptReasoningCapabilities,hasExplicitOutputLimit,isQwenFamilyWireModel,isReasoningEffortPlaceholder,isTieredEffortWireModel,parsePositiveIntegerEnvValue,tokenLimit}from"./chunk-TAAJ7TDB.js";import{buildRuntimeFetchOptions}from"./chunk-ZZZAYAJW.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{OpenAI}from"./chunk-2UOMCYQG.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("DefaultOpenAICompatibleProvider");var OPENAI_COMPATIBLE_EFFORTS=["low","medium","high","xhigh"];function isQwen3Model(model){return model.toLowerCase().includes("qwen3")}__name(isQwen3Model,"isQwen3Model");function mirrorReasoningContentToReasoning(message){if(message.role!=="assistant"){return message}const assistant=message;if(typeof assistant.reasoning_content!=="string"||assistant.reasoning_content.length===0||typeof assistant.reasoning==="string"){return message}return{...assistant,reasoning:assistant.reasoning_content}}__name(mirrorReasoningContentToReasoning,"mirrorReasoningContentToReasoning");var DefaultOpenAICompatibleProvider=class{static{__name(this,"DefaultOpenAICompatibleProvider")}contentGeneratorConfig;cliConfig;effortClampWarned=false;constructor(contentGeneratorConfig,cliConfig){this.cliConfig=cliConfig;this.contentGeneratorConfig=contentGeneratorConfig}buildHeaders(){const version=this.cliConfig.getCliVersion()||"unknown";const userAgent=`QwenCode/${version} (${process.platform}; ${process.arch})`;const{customHeaders}=this.contentGeneratorConfig;const defaultHeaders={"User-Agent":userAgent};return customHeaders?{...defaultHeaders,...customHeaders}:defaultHeaders}buildClient(){const{apiKey,baseUrl,maxRetries=DEFAULT_MAX_RETRIES}=this.contentGeneratorConfig;const timeout=resolveRequestTimeout(this.contentGeneratorConfig.timeout);const defaultHeaders=this.buildHeaders();const runtimeOptions=buildRuntimeFetchOptions("openai",this.cliConfig.getProxy());return new OpenAI({apiKey,baseURL:baseUrl,timeout,maxRetries,defaultHeaders,...runtimeOptions||{},fetch:buildSessionAwareFetch(runtimeOptions?.fetch,this.cliConfig,this.contentGeneratorConfig.customHeaders)})}supportedReasoningEffortsFor(model){const configured=this.getReasoningCapabilities(model);if(!configured?.profile&&!getGptReasoningCapabilities(model))return OPENAI_COMPATIBLE_EFFORTS;if(configured&&!configured.toggleOnly)return configured.efforts;return getGptReasoningCapabilities(model)?.efforts??OPENAI_COMPATIBLE_EFFORTS}getReasoningCapabilities(model){return resolveReasoningForModel(this.cliConfig,this.contentGeneratorConfig,model)}clampConfiguredReasoningEffort(request){if(this.contentGeneratorConfig.samplingParams?.["reasoning"]!==void 0||this.getReasoningCapabilities(request.model)?.profile){return request}const loose=request;const reasoning=loose["reasoning"];const effort=reasoning?.effort;if(typeof effort!=="string"||!REASONING_EFFORT_TIERS.includes(effort)){return request}const clamped=clampReasoningEffort(effort,this.supportedReasoningEffortsFor(loose["model"]??this.contentGeneratorConfig.model));if(clamped===effort){return request}if(!this.effortClampWarned){debugLogger.warn(`reasoning.effort='${effort}' is not accepted by this OpenAI-compatible endpoint; using '${clamped}'.`);this.effortClampWarned=true}return{...loose,reasoning:{...reasoning,effort:clamped}}}buildRequest(request,_userPromptId){const extraBody=this.contentGeneratorConfig.extra_body;const requestWithTokenLimits=this.clampConfiguredReasoningEffort(this.applyOutputTokenLimit(request));const profile=this.getReasoningCapabilities(request.model)?.profile;const messages=!profile&&isQwen3Model(request.model)||profile==="qwen-chat-template"?requestWithTokenLimits.messages.map(mirrorReasoningContentToReasoning):requestWithTokenLimits.messages;const result={...requestWithTokenLimits,messages,...extraBody?extraBody:{}};this.flattenGptReasoningEffort(result);return result}flattenGptReasoningEffort(body){if(this.getReasoningCapabilities(body["model"])?.profile||!getGptReasoningCapabilities(body["model"])||isOpenRouterHostname(this.contentGeneratorConfig)||this.contentGeneratorConfig.samplingParams?.["reasoning"]!==void 0||this.contentGeneratorConfig.extra_body?.["reasoning"]!==void 0)return;const reasoning=body["reasoning"];if(typeof reasoning?.effort!=="string"||!reasoning.effort)return;if(isReasoningEffortPlaceholder(body["reasoning_effort"])){body["reasoning_effort"]=reasoning.effort}const{effort:_drop,...rest}=reasoning;if(Object.keys(rest).length>0)body["reasoning"]=rest;else delete body["reasoning"]}getDefaultGenerationConfig(){return{}}getResponseParsingOptions(model){return{contentOnlyThinkingTagLeaks:true,...model&&isQwen3Model(model)?{taggedThinkingTagsAfterReasoning:true}:{}}}applyOutputTokenLimit(request){if(this.contentGeneratorConfig.samplingParams!==void 0){return request}const userMaxTokens=request.max_tokens;const modelLimit=tokenLimit(request.model,"output");const isKnownModel=hasExplicitOutputLimit(request.model);let effectiveMaxTokens;if(userMaxTokens!==void 0&&userMaxTokens!==null){if(isKnownModel){effectiveMaxTokens=Math.min(userMaxTokens,modelLimit)}else{effectiveMaxTokens=userMaxTokens}}else{const envMaxTokens=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);if(envMaxTokens!==void 0){effectiveMaxTokens=isKnownModel?Math.min(envMaxTokens,modelLimit):envMaxTokens}else{effectiveMaxTokens=defaultOutputCeiling(request.model)}}return{...request,max_tokens:effectiveMaxTokens}}};init_esbuild_shims();var debugLogger2=createDebugLogger("DashScopeOpenAICompatibleProvider");var DASHSCOPE_TIERED_EFFORTS=["low","medium","high","xhigh"];function selectDashScopeThinkingKnob(model,extraBody,samplingParams,reasoningEffort,tieredModel=isTieredEffortWireModel(model)){if(!tieredModel){return void 0}const selectFromLayer=__name((source,layer)=>{if(layer?.["enable_thinking"]===false){return{source,field:"enable_thinking",value:false}}return selectValueFromLayer(source,layer)??selectOnSwitch(source,layer)},"selectFromLayer");const selectValueFromLayer=__name((source,layer)=>{if(layer?.["reasoning_effort"]!=null){return{source,field:"reasoning_effort",value:layer["reasoning_effort"]}}if(layer?.["thinking_budget"]!=null){return{source,field:"thinking_budget",value:layer["thinking_budget"]}}return void 0},"selectValueFromLayer");const selectOnSwitch=__name((source,layer)=>{if(layer?.["enable_thinking"]===true){return{source,field:"enable_thinking",value:true}}return void 0},"selectOnSwitch");const reasoningSelection=reasoningEffort!==void 0?{source:"reasoning",field:"reasoning_effort",value:reasoningEffort}:void 0;const extraBodySelection=selectFromLayer("extra_body",extraBody);if(extraBodySelection?.field==="enable_thinking"&&extraBodySelection.value===true){return selectValueFromLayer("samplingParams",samplingParams)??reasoningSelection??extraBodySelection}if(extraBodySelection){return extraBodySelection}const samplingSelection=selectFromLayer("samplingParams",samplingParams);return samplingSelection?.field==="enable_thinking"&&samplingSelection.value===true?reasoningSelection??samplingSelection:samplingSelection??reasoningSelection}__name(selectDashScopeThinkingKnob,"selectDashScopeThinkingKnob");function withoutNullishThinkingKnobs(layer){if(!layer){return void 0}const hasNullishEnableThinking="enable_thinking"in layer&&layer["enable_thinking"]==null;const hasNullishEffort="reasoning_effort"in layer&&layer["reasoning_effort"]==null;const hasNullishBudget="thinking_budget"in layer&&layer["thinking_budget"]==null;if(!hasNullishEnableThinking&&!hasNullishEffort&&!hasNullishBudget){return layer}const sanitized={...layer};if(hasNullishEnableThinking){delete sanitized["enable_thinking"]}if(hasNullishEffort){delete sanitized["reasoning_effort"]}if(hasNullishBudget){delete sanitized["thinking_budget"]}return sanitized}__name(withoutNullishThinkingKnobs,"withoutNullishThinkingKnobs");var DASHSCOPE_REGIONAL_HOSTS=["dashscope.aliyuncs.com","dashscope-intl.aliyuncs.com","dashscope-us.aliyuncs.com"];var DashScopeOpenAICompatibleProvider=class _DashScopeOpenAICompatibleProvider extends DefaultOpenAICompatibleProvider{static{__name(this,"DashScopeOpenAICompatibleProvider")}constructor(contentGeneratorConfig,cliConfig){super(contentGeneratorConfig,cliConfig)}static isDashScopeProvider(contentGeneratorConfig){const{authType,baseUrl}=contentGeneratorConfig;if(authType==="qwen-oauth")return true;if(!baseUrl)return true;const normalizedBaseUrl=baseUrl.endsWith("/")?baseUrl.slice(0,-1):baseUrl;let hostname=null;try{hostname=new URL(normalizedBaseUrl).hostname.toLowerCase()}catch{hostname=null}const isDashscopeOrigin=hostname!==null&&DASHSCOPE_REGIONAL_HOSTS.some(host=>hostname===host||hostname.endsWith("."+host));const isMaasOrigin=hostname!==null&&hostname.endsWith(".maas.aliyuncs.com");const isInternalOrigin=hostname!==null&&(hostname.endsWith(".alibaba-inc.com")||hostname.endsWith(".aliyun-inc.com"));const isAliCloudApiOrigin=hostname!==null&&hostname.endsWith(".alicloudapi.com");const proxyBaseUrl=getDashscopeProxyBaseUrl();const normalizedProxyUrl=proxyBaseUrl?.endsWith("/")?proxyBaseUrl.slice(0,-1):proxyBaseUrl;const isProxyMatch=Boolean(normalizedProxyUrl&&normalizedBaseUrl.toLowerCase()===normalizedProxyUrl.toLowerCase());if(normalizedProxyUrl&&!isDashscopeOrigin&&!isMaasOrigin&&!isInternalOrigin&&!isAliCloudApiOrigin&&!isProxyMatch){debugLogger2.debug(`DASHSCOPE_PROXY_BASE_URL is configured but the request baseUrl does not match. DashScope headers/cache control will be skipped.`)}if(isInternalOrigin){debugLogger2.debug(`DashScope provider activated via internal origin: ${hostname}`)}if(isAliCloudApiOrigin){debugLogger2.debug(`DashScope provider activated via alicloudapi origin: ${hostname}`)}return isDashscopeOrigin||isMaasOrigin||isInternalOrigin||isAliCloudApiOrigin||isProxyMatch}buildHeaders(){const version=this.cliConfig.getCliVersion()||"unknown";const userAgent=`QwenCode/${version} (${process.platform}; ${process.arch})`;const{authType,customHeaders}=this.contentGeneratorConfig;const defaultHeaders={"User-Agent":userAgent,"X-DashScope-CacheControl":"enable","X-DashScope-UserAgent":userAgent,"X-DashScope-AuthType":authType};if(this.cliConfig.isOmniEnabled?.()){defaultHeaders["X-DashScope-OssResourceResolve"]="enable"}return customHeaders?{...defaultHeaders,...customHeaders}:defaultHeaders}buildClient(){const{apiKey,baseUrl=DEFAULT_DASHSCOPE_BASE_URL,maxRetries=DEFAULT_MAX_RETRIES}=this.contentGeneratorConfig;const timeout=resolveRequestTimeout(this.contentGeneratorConfig.timeout);const defaultHeaders=this.buildHeaders();const runtimeOptions=buildRuntimeFetchOptions("openai",this.cliConfig.getProxy());return new OpenAI({apiKey,baseURL:baseUrl,timeout,maxRetries,defaultHeaders,...runtimeOptions||{},fetch:buildSessionAwareFetch(runtimeOptions?.fetch,this.cliConfig,this.contentGeneratorConfig.customHeaders)})}buildRequest(request,userPromptId,reattachBlockCount=0){let messages=request.messages;const tools=request.tools;const flattenPlainTextForGlm=this.isGlmModel(request.model)&&!this.hasFunctionCallingContext(request);if(flattenPlainTextForGlm){messages=this.flattenTextContent(messages)}else if(this.shouldEnableCacheControl()){messages=this.addDashScopeCacheControl(request,request.stream?"all":"system_only",reattachBlockCount)}const requestWithTokenLimits=this.applyOutputTokenLimit(request);const isTieredQwenModel=this.isTieredEffortModel(request.model);const extraBody=isTieredQwenModel?withoutNullishThinkingKnobs(this.contentGeneratorConfig.extra_body):this.contentGeneratorConfig.extra_body;const qwenEffortConfig=this.buildQwenEffortConfig(request.model);const rawRequestParams=requestWithTokenLimits;const requestParams=isTieredQwenModel?withoutNullishThinkingKnobs(rawRequestParams):rawRequestParams;if("reasoning_effort"in requestParams&&"reasoning_effort"in qwenEffortConfig){qwenEffortConfig["reasoning_effort"]=requestParams["reasoning_effort"]}const hasQwenEffortConfig=Object.keys(qwenEffortConfig).length>0;const selectedThinkingKnob=isTieredQwenModel?selectDashScopeThinkingKnob(this.resolveWireModel(request.model),extraBody,requestParams,qwenEffortConfig["reasoning_effort"],isTieredQwenModel):void 0;if(this.isVisionModel(request.model)){const dashscopeExtras2={vl_high_resolution_images:true,preserve_thinking:true,...qwenEffortConfig};const visionResult={...requestParams,messages,...tools?{tools}:{},...this.buildRequestMetadata(request.model,userPromptId),...dashscopeExtras2};if(hasQwenEffortConfig&&"reasoning"in visionResult){delete visionResult["reasoning"]}return this.mergeExtraBodyAndResolveKnobs(hasQwenEffortConfig?visionResult:this.clampConfiguredReasoningEffort(visionResult),extraBody,request.model,selectedThinkingKnob)}const dashscopeExtras={preserve_thinking:true,...qwenEffortConfig};const result={...requestParams,messages,...tools?{tools}:{},...this.buildRequestMetadata(request.model,userPromptId),...dashscopeExtras};if(hasQwenEffortConfig&&"reasoning"in result){delete result["reasoning"]}return this.mergeExtraBodyAndResolveKnobs(hasQwenEffortConfig?result:this.clampConfiguredReasoningEffort(result),extraBody,request.model,selectedThinkingKnob)}mergeExtraBodyAndResolveKnobs(result,extraBody,model,selectedThinkingKnob){const merged={...result,...extraBody?extraBody:{}};const reasoningEffort=merged["reasoning_effort"];const dropped=new Set;if(selectedThinkingKnob?.field==="thinking_budget"){if(reasoningEffort!==void 0){dropped.add("reasoning_effort")}if(merged["enable_thinking"]===false){dropped.add("enable_thinking")}}if(selectedThinkingKnob?.field==="reasoning_effort"&&merged["thinking_budget"]!==void 0){dropped.add("thinking_budget")}for(const key of dropped){delete merged[key]}for(const key of this.dropConflictingThinkingKnobs(model,merged,selectedThinkingKnob)){dropped.add(key)}this.warnConflictingKnobDrop(model,reasoningEffort,[...dropped]);this.flattenGptReasoningEffort(merged);return merged}getConfiguredReasoning(model){return this.getReasoningCapabilities(model)}isTieredEffortModel(model){const configured=this.getConfiguredReasoning(model);if(configured?.profile)return configured.profile==="dashscope-effort";return isTieredEffortWireModel(model??this.contentGeneratorConfig.model,configured)}resolveWireModel(model){return(model??this.contentGeneratorConfig.model??"").toLowerCase()}buildQwenEffortConfig(model){const configured=this.getConfiguredReasoning(model);if(configured?.profile)return{};const reasoning=getEffectiveReasoning(this.contentGeneratorConfig,configured);if(!reasoning||reasoning.effort===void 0){return{}}const wireModel=this.resolveWireModel(model);if(this.isTieredEffortModel(model)){const configured2=this.getConfiguredReasoning(model);if(configured2&&!configured2.toggleOnly){return configured2.efforts.includes(reasoning.effort)?{reasoning_effort:reasoning.effort}:{}}return{reasoning_effort:this.clampTieredEffort(reasoning.effort)}}if(isQwenFamilyWireModel(wireModel)){return{enable_thinking:true}}return{}}clampTieredEffort(effort){const clamped=clampReasoningEffort(effort,DASHSCOPE_TIERED_EFFORTS);if(clamped!==effort&&!this.effortClampWarned){debugLogger2.warn(`reasoning.effort='${effort}' is not accepted by the DashScope tiered-effort family; using '${clamped}'.`);this.effortClampWarned=true}return clamped}dropConflictingThinkingKnobs(model,merged,selectedThinkingKnob){const wireModel=this.resolveWireModel(model);if(!isQwenFamilyWireModel(wireModel)){return[]}const isTieredEffortModel=this.isTieredEffortModel(model);if(isTieredEffortModel&&selectedThinkingKnob?.field==="enable_thinking"&&selectedThinkingKnob.value===false){merged["reasoning_effort"]="none";const dropped=["enable_thinking"];if(merged["thinking_budget"]!==void 0){dropped.push("thinking_budget")}for(const key of dropped){delete merged[key]}return dropped}const effort=merged["reasoning_effort"];if(typeof effort!=="string"){return[]}if(isTieredEffortModel&&effort==="none"){if(merged["thinking_budget"]===void 0){return[]}delete merged["thinking_budget"];return["thinking_budget"]}if(isTieredEffortModel){if(selectedThinkingKnob?.field==="reasoning_effort"&&"enable_thinking"in merged){delete merged["enable_thinking"];return["enable_thinking"]}return[]}if(merged["thinking_budget"]===void 0){return[]}delete merged["reasoning_effort"];return["reasoning_effort"]}warnConflictingKnobDrop(model,reasoningEffort,dropped){if(dropped.length===0){return}if(!this.conflictingKnobDropWarned){this.conflictingKnobDropWarned=true;debugLogger2.warn("DashScope: dropped conflicting thinking knobs",{model:this.resolveWireModel(model),reasoningEffort,dropped})}}conflictingKnobDropWarned=false;buildRequestMetadata(model,userPromptId){if(!this.shouldSendRequestMetadata(model)){return{}}return this.buildMetadata(userPromptId)||{}}shouldSendRequestMetadata(model){const configured=this.contentGeneratorConfig.enableRequestMetadata;if(typeof configured==="boolean"){return configured}return isQwenFamilyWireModel(this.resolveWireModel(model))}buildMetadata(userPromptId){const channel=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:userPromptId,...channel?{channel}:{}}}}getDefaultGenerationConfig(){return{}}addDashScopeCacheControl(request,cacheControl,reattachBlockCount=0){const messages=request.messages;const systemIndex=messages.findIndex(msg=>msg.role==="system");const lastIndex=messages.length-1;const stableBlock=reattachBlockCount>0&&lastIndex>=0?this.lastStableBlock(messages,reattachBlockCount):{messageIndex:lastIndex,excludeTail:0};const updatedMessages=messages.length===0?messages:messages.map((message,index)=>{const isConversationAnchor=stableBlock?.messageIndex===index&&cacheControl==="all";const shouldAddCacheControl=Boolean(index===systemIndex&&systemIndex!==-1||isConversationAnchor);if(!shouldAddCacheControl||!("content"in message)||message.content===null||message.content===void 0){return message}return{...message,content:this.addCacheControlToContent(message.content,isConversationAnchor&&stableBlock?stableBlock.excludeTail:0)}});return updatedMessages}lastStableBlock(messages,reattachBlockCount){let remaining=reattachBlockCount;for(let index=messages.length-1;index>=0;index--){const content=messages[index].content;const blockCount=typeof content==="string"?content.length>0?1:0:Array.isArray(content)?content.length:0;if(blockCount===0)continue;if(blockCount>remaining){return{messageIndex:index,excludeTail:remaining}}remaining-=blockCount}return void 0}addCacheControlToContent(content,excludeTail=0){const contentArray=this.normalizeContentToArray(content);return this.addCacheControlToContentArray(contentArray,excludeTail)}normalizeContentToArray(content){if(typeof content==="string"){return[{type:"text",text:content}]}return[...content]}addCacheControlToContentArray(contentArray,excludeTail=0){if(contentArray.length===0){return contentArray}let targetIndex=contentArray.length-1-excludeTail;if(targetIndex<0){return contentArray}if(excludeTail>0){while(targetIndex>0&&contentArray[targetIndex].type!=="text"){targetIndex-=1}}const lastItem=contentArray[targetIndex];contentArray[targetIndex]={...lastItem,cache_control:{type:"ephemeral"}};return contentArray}isGlmModel(model){return!!model&&model.toLowerCase().startsWith("glm-")}hasFunctionCallingContext(request){if(request.tools&&request.tools.length>0){return true}return request.messages.some(message=>{if(message.role==="tool"){return true}if(message.role==="assistant"){const toolCalls=message.tool_calls;return Array.isArray(toolCalls)&&toolCalls.length>0}return false})}flattenTextContent(messages){return messages.map(message=>{if(!("content"in message)||!Array.isArray(message.content)){return message}const parts=message.content;if(parts.length===0){return message}const isTextOnly=parts.every(part=>part&&part.type==="text");if(!isTextOnly){return message}const text=parts.map(part=>part.text??"").join("\n\n");return{...message,content:text}})}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["qwen-vl","qwen3-vl-plus","qwen3.5-plus","qwen3.6-plus","qwen3.7-plus"];isVisionModel(model){if(!model){return false}const normalized=model.toLowerCase();if(_DashScopeOpenAICompatibleProvider.VISION_MODEL_EXACT_MATCHES.has(normalized)){return true}for(const prefix of _DashScopeOpenAICompatibleProvider.VISION_MODEL_PREFIX_PATTERNS){if(normalized.startsWith(prefix)){return true}}return false}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==false}};export{DefaultOpenAICompatibleProvider,selectDashScopeThinkingKnob,DASHSCOPE_REGIONAL_HOSTS,DashScopeOpenAICompatibleProvider};
3
+ import{DEFAULT_DASHSCOPE_BASE_URL,DEFAULT_MAX_RETRIES,buildSessionAwareFetch,getDashscopeProxyBaseUrl,getEffectiveReasoning,isOpenRouterHostname,resolveReasoningForModel,resolveRequestTimeout}from"./chunk-B5XDGUAK.js";import{REASONING_EFFORT_TIERS,clampReasoningEffort,defaultOutputCeiling,getGptReasoningCapabilities,hasExplicitOutputLimit,isQwenFamilyWireModel,isReasoningEffortPlaceholder,isTieredEffortWireModel,parsePositiveIntegerEnvValue,tokenLimit}from"./chunk-TAAJ7TDB.js";import{buildRuntimeFetchOptions}from"./chunk-ZZZAYAJW.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{OpenAI}from"./chunk-2UOMCYQG.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();var debugLogger=createDebugLogger("DefaultOpenAICompatibleProvider");var OPENAI_COMPATIBLE_EFFORTS=["low","medium","high","xhigh"];function isQwen3Model(model){return model.toLowerCase().includes("qwen3")}__name(isQwen3Model,"isQwen3Model");function mirrorReasoningContentToReasoning(message){if(message.role!=="assistant"){return message}const assistant=message;if(typeof assistant.reasoning_content!=="string"||assistant.reasoning_content.length===0||typeof assistant.reasoning==="string"){return message}return{...assistant,reasoning:assistant.reasoning_content}}__name(mirrorReasoningContentToReasoning,"mirrorReasoningContentToReasoning");var DefaultOpenAICompatibleProvider=class{static{__name(this,"DefaultOpenAICompatibleProvider")}contentGeneratorConfig;cliConfig;effortClampWarned=false;constructor(contentGeneratorConfig,cliConfig){this.cliConfig=cliConfig;this.contentGeneratorConfig=contentGeneratorConfig}buildHeaders(){const version=this.cliConfig.getCliVersion()||"unknown";const userAgent=`QwenCode/${version} (${process.platform}; ${process.arch})`;const{customHeaders}=this.contentGeneratorConfig;const defaultHeaders={"User-Agent":userAgent};return customHeaders?{...defaultHeaders,...customHeaders}:defaultHeaders}buildClient(){const{apiKey,baseUrl,maxRetries=DEFAULT_MAX_RETRIES}=this.contentGeneratorConfig;const timeout=resolveRequestTimeout(this.contentGeneratorConfig.timeout);const defaultHeaders=this.buildHeaders();const runtimeOptions=buildRuntimeFetchOptions("openai",this.cliConfig.getProxy());return new OpenAI({apiKey,baseURL:baseUrl,timeout,maxRetries,defaultHeaders,...runtimeOptions||{},fetch:buildSessionAwareFetch(runtimeOptions?.fetch,this.cliConfig,this.contentGeneratorConfig.customHeaders)})}supportedReasoningEffortsFor(model){const configured=this.getReasoningCapabilities(model);if(!configured?.profile&&!getGptReasoningCapabilities(model))return OPENAI_COMPATIBLE_EFFORTS;if(configured&&!configured.toggleOnly)return configured.efforts;return getGptReasoningCapabilities(model)?.efforts??OPENAI_COMPATIBLE_EFFORTS}getReasoningCapabilities(model){return resolveReasoningForModel(this.cliConfig,this.contentGeneratorConfig,model)}clampConfiguredReasoningEffort(request){if(this.contentGeneratorConfig.samplingParams?.["reasoning"]!==void 0||this.getReasoningCapabilities(request.model)?.profile){return request}const loose=request;const reasoning=loose["reasoning"];const effort=reasoning?.effort;if(typeof effort!=="string"||!REASONING_EFFORT_TIERS.includes(effort)){return request}const clamped=clampReasoningEffort(effort,this.supportedReasoningEffortsFor(loose["model"]??this.contentGeneratorConfig.model));if(clamped===effort){return request}if(!this.effortClampWarned){debugLogger.warn(`reasoning.effort='${effort}' is not accepted by this OpenAI-compatible endpoint; using '${clamped}'.`);this.effortClampWarned=true}return{...loose,reasoning:{...reasoning,effort:clamped}}}buildRequest(request,_userPromptId){const extraBody=this.contentGeneratorConfig.extra_body;const requestWithTokenLimits=this.clampConfiguredReasoningEffort(this.applyOutputTokenLimit(request));const profile=this.getReasoningCapabilities(request.model)?.profile;const messages=!profile&&isQwen3Model(request.model)||profile==="qwen-chat-template"?requestWithTokenLimits.messages.map(mirrorReasoningContentToReasoning):requestWithTokenLimits.messages;const result={...requestWithTokenLimits,messages,...extraBody?extraBody:{}};this.flattenGptReasoningEffort(result);return result}flattenGptReasoningEffort(body){if(this.getReasoningCapabilities(body["model"])?.profile||!getGptReasoningCapabilities(body["model"])||isOpenRouterHostname(this.contentGeneratorConfig)||this.contentGeneratorConfig.samplingParams?.["reasoning"]!==void 0||this.contentGeneratorConfig.extra_body?.["reasoning"]!==void 0)return;const reasoning=body["reasoning"];if(typeof reasoning?.effort!=="string"||!reasoning.effort)return;if(isReasoningEffortPlaceholder(body["reasoning_effort"])){body["reasoning_effort"]=reasoning.effort}const{effort:_drop,...rest}=reasoning;if(Object.keys(rest).length>0)body["reasoning"]=rest;else delete body["reasoning"]}getDefaultGenerationConfig(){return{}}getResponseParsingOptions(model){return{contentOnlyThinkingTagLeaks:true,...model&&isQwen3Model(model)?{taggedThinkingTagsAfterReasoning:true}:{}}}applyOutputTokenLimit(request){if(this.contentGeneratorConfig.samplingParams!==void 0){return request}const userMaxTokens=request.max_tokens;const modelLimit=tokenLimit(request.model,"output");const isKnownModel=hasExplicitOutputLimit(request.model);let effectiveMaxTokens;if(userMaxTokens!==void 0&&userMaxTokens!==null){if(isKnownModel){effectiveMaxTokens=Math.min(userMaxTokens,modelLimit)}else{effectiveMaxTokens=userMaxTokens}}else{const envMaxTokens=parsePositiveIntegerEnvValue(process.env["QWEN_CODE_MAX_OUTPUT_TOKENS"]);if(envMaxTokens!==void 0){effectiveMaxTokens=isKnownModel?Math.min(envMaxTokens,modelLimit):envMaxTokens}else{effectiveMaxTokens=defaultOutputCeiling(request.model)}}return{...request,max_tokens:effectiveMaxTokens}}};init_esbuild_shims();var debugLogger2=createDebugLogger("DashScopeOpenAICompatibleProvider");var DASHSCOPE_TIERED_EFFORTS=["low","medium","high","xhigh"];function selectDashScopeThinkingKnob(model,extraBody,samplingParams,reasoningEffort,tieredModel=isTieredEffortWireModel(model)){if(!tieredModel){return void 0}const selectFromLayer=__name((source,layer)=>{if(layer?.["enable_thinking"]===false){return{source,field:"enable_thinking",value:false}}return selectValueFromLayer(source,layer)??selectOnSwitch(source,layer)},"selectFromLayer");const selectValueFromLayer=__name((source,layer)=>{if(layer?.["reasoning_effort"]!=null){return{source,field:"reasoning_effort",value:layer["reasoning_effort"]}}if(layer?.["thinking_budget"]!=null){return{source,field:"thinking_budget",value:layer["thinking_budget"]}}return void 0},"selectValueFromLayer");const selectOnSwitch=__name((source,layer)=>{if(layer?.["enable_thinking"]===true){return{source,field:"enable_thinking",value:true}}return void 0},"selectOnSwitch");const reasoningSelection=reasoningEffort!==void 0?{source:"reasoning",field:"reasoning_effort",value:reasoningEffort}:void 0;const extraBodySelection=selectFromLayer("extra_body",extraBody);if(extraBodySelection?.field==="enable_thinking"&&extraBodySelection.value===true){return selectValueFromLayer("samplingParams",samplingParams)??reasoningSelection??extraBodySelection}if(extraBodySelection){return extraBodySelection}const samplingSelection=selectFromLayer("samplingParams",samplingParams);return samplingSelection?.field==="enable_thinking"&&samplingSelection.value===true?reasoningSelection??samplingSelection:samplingSelection??reasoningSelection}__name(selectDashScopeThinkingKnob,"selectDashScopeThinkingKnob");function withoutNullishThinkingKnobs(layer){if(!layer){return void 0}const hasNullishEnableThinking="enable_thinking"in layer&&layer["enable_thinking"]==null;const hasNullishEffort="reasoning_effort"in layer&&layer["reasoning_effort"]==null;const hasNullishBudget="thinking_budget"in layer&&layer["thinking_budget"]==null;if(!hasNullishEnableThinking&&!hasNullishEffort&&!hasNullishBudget){return layer}const sanitized={...layer};if(hasNullishEnableThinking){delete sanitized["enable_thinking"]}if(hasNullishEffort){delete sanitized["reasoning_effort"]}if(hasNullishBudget){delete sanitized["thinking_budget"]}return sanitized}__name(withoutNullishThinkingKnobs,"withoutNullishThinkingKnobs");var DASHSCOPE_REGIONAL_HOSTS=["dashscope.aliyuncs.com","dashscope-intl.aliyuncs.com","dashscope-us.aliyuncs.com"];var DashScopeOpenAICompatibleProvider=class _DashScopeOpenAICompatibleProvider extends DefaultOpenAICompatibleProvider{static{__name(this,"DashScopeOpenAICompatibleProvider")}constructor(contentGeneratorConfig,cliConfig){super(contentGeneratorConfig,cliConfig)}static isDashScopeProvider(contentGeneratorConfig){const{authType,baseUrl}=contentGeneratorConfig;if(authType==="qwen-oauth")return true;if(!baseUrl)return true;const normalizedBaseUrl=baseUrl.endsWith("/")?baseUrl.slice(0,-1):baseUrl;let hostname=null;try{hostname=new URL(normalizedBaseUrl).hostname.toLowerCase()}catch{hostname=null}const isDashscopeOrigin=hostname!==null&&DASHSCOPE_REGIONAL_HOSTS.some(host=>hostname===host||hostname.endsWith("."+host));const isMaasOrigin=hostname!==null&&hostname.endsWith(".maas.aliyuncs.com");const isInternalOrigin=hostname!==null&&(hostname.endsWith(".alibaba-inc.com")||hostname.endsWith(".aliyun-inc.com"));const isAliCloudApiOrigin=hostname!==null&&hostname.endsWith(".alicloudapi.com");const proxyBaseUrl=getDashscopeProxyBaseUrl();const normalizedProxyUrl=proxyBaseUrl?.endsWith("/")?proxyBaseUrl.slice(0,-1):proxyBaseUrl;const isProxyMatch=Boolean(normalizedProxyUrl&&normalizedBaseUrl.toLowerCase()===normalizedProxyUrl.toLowerCase());if(normalizedProxyUrl&&!isDashscopeOrigin&&!isMaasOrigin&&!isInternalOrigin&&!isAliCloudApiOrigin&&!isProxyMatch){debugLogger2.debug(`DASHSCOPE_PROXY_BASE_URL is configured but the request baseUrl does not match. DashScope headers/cache control will be skipped.`)}if(isInternalOrigin){debugLogger2.debug(`DashScope provider activated via internal origin: ${hostname}`)}if(isAliCloudApiOrigin){debugLogger2.debug(`DashScope provider activated via alicloudapi origin: ${hostname}`)}return isDashscopeOrigin||isMaasOrigin||isInternalOrigin||isAliCloudApiOrigin||isProxyMatch}buildHeaders(){const version=this.cliConfig.getCliVersion()||"unknown";const userAgent=`QwenCode/${version} (${process.platform}; ${process.arch})`;const{authType,customHeaders}=this.contentGeneratorConfig;const defaultHeaders={"User-Agent":userAgent,"X-DashScope-CacheControl":"enable","X-DashScope-UserAgent":userAgent,"X-DashScope-AuthType":authType};if(this.cliConfig.isOmniEnabled?.()){defaultHeaders["X-DashScope-OssResourceResolve"]="enable"}return customHeaders?{...defaultHeaders,...customHeaders}:defaultHeaders}buildClient(){const{apiKey,baseUrl=DEFAULT_DASHSCOPE_BASE_URL,maxRetries=DEFAULT_MAX_RETRIES}=this.contentGeneratorConfig;const timeout=resolveRequestTimeout(this.contentGeneratorConfig.timeout);const defaultHeaders=this.buildHeaders();const runtimeOptions=buildRuntimeFetchOptions("openai",this.cliConfig.getProxy());return new OpenAI({apiKey,baseURL:baseUrl,timeout,maxRetries,defaultHeaders,...runtimeOptions||{},fetch:buildSessionAwareFetch(runtimeOptions?.fetch,this.cliConfig,this.contentGeneratorConfig.customHeaders)})}buildRequest(request,userPromptId,reattachBlockCount=0){let messages=request.messages;const tools=request.tools;const flattenPlainTextForGlm=this.isGlmModel(request.model)&&!this.hasFunctionCallingContext(request);if(flattenPlainTextForGlm){messages=this.flattenTextContent(messages)}else if(this.shouldEnableCacheControl()){messages=this.addDashScopeCacheControl(request,request.stream?"all":"system_only",reattachBlockCount)}const requestWithTokenLimits=this.applyOutputTokenLimit(request);const isTieredQwenModel=this.isTieredEffortModel(request.model);const extraBody=isTieredQwenModel?withoutNullishThinkingKnobs(this.contentGeneratorConfig.extra_body):this.contentGeneratorConfig.extra_body;const qwenEffortConfig=this.buildQwenEffortConfig(request.model);const rawRequestParams=requestWithTokenLimits;const requestParams=isTieredQwenModel?withoutNullishThinkingKnobs(rawRequestParams):rawRequestParams;if("reasoning_effort"in requestParams&&"reasoning_effort"in qwenEffortConfig){qwenEffortConfig["reasoning_effort"]=requestParams["reasoning_effort"]}const hasQwenEffortConfig=Object.keys(qwenEffortConfig).length>0;const selectedThinkingKnob=isTieredQwenModel?selectDashScopeThinkingKnob(this.resolveWireModel(request.model),extraBody,requestParams,qwenEffortConfig["reasoning_effort"],isTieredQwenModel):void 0;if(this.isVisionModel(request.model)){const dashscopeExtras2={vl_high_resolution_images:true,preserve_thinking:true,...qwenEffortConfig};const visionResult={...requestParams,messages,...tools?{tools}:{},...this.buildRequestMetadata(request.model,userPromptId),...dashscopeExtras2};if(hasQwenEffortConfig&&"reasoning"in visionResult){delete visionResult["reasoning"]}return this.mergeExtraBodyAndResolveKnobs(hasQwenEffortConfig?visionResult:this.clampConfiguredReasoningEffort(visionResult),extraBody,request.model,selectedThinkingKnob)}const dashscopeExtras={preserve_thinking:true,...qwenEffortConfig};const result={...requestParams,messages,...tools?{tools}:{},...this.buildRequestMetadata(request.model,userPromptId),...dashscopeExtras};if(hasQwenEffortConfig&&"reasoning"in result){delete result["reasoning"]}return this.mergeExtraBodyAndResolveKnobs(hasQwenEffortConfig?result:this.clampConfiguredReasoningEffort(result),extraBody,request.model,selectedThinkingKnob)}mergeExtraBodyAndResolveKnobs(result,extraBody,model,selectedThinkingKnob){const merged={...result,...extraBody?extraBody:{}};const reasoningEffort=merged["reasoning_effort"];const dropped=new Set;if(selectedThinkingKnob?.field==="thinking_budget"){if(reasoningEffort!==void 0){dropped.add("reasoning_effort")}if(merged["enable_thinking"]===false){dropped.add("enable_thinking")}}if(selectedThinkingKnob?.field==="reasoning_effort"&&merged["thinking_budget"]!==void 0){dropped.add("thinking_budget")}for(const key of dropped){delete merged[key]}for(const key of this.dropConflictingThinkingKnobs(model,merged,selectedThinkingKnob)){dropped.add(key)}this.warnConflictingKnobDrop(model,reasoningEffort,[...dropped]);this.flattenGptReasoningEffort(merged);return merged}getConfiguredReasoning(model){return this.getReasoningCapabilities(model)}isTieredEffortModel(model){const configured=this.getConfiguredReasoning(model);if(configured?.profile)return configured.profile==="dashscope-effort";return isTieredEffortWireModel(model??this.contentGeneratorConfig.model,configured)}resolveWireModel(model){return(model??this.contentGeneratorConfig.model??"").toLowerCase()}buildQwenEffortConfig(model){const configured=this.getConfiguredReasoning(model);if(configured?.profile)return{};const reasoning=getEffectiveReasoning(this.contentGeneratorConfig,configured);if(!reasoning||reasoning.effort===void 0){return{}}const wireModel=this.resolveWireModel(model);if(this.isTieredEffortModel(model)){const configured2=this.getConfiguredReasoning(model);if(configured2&&!configured2.toggleOnly){return configured2.efforts.includes(reasoning.effort)?{reasoning_effort:reasoning.effort}:{}}return{reasoning_effort:this.clampTieredEffort(reasoning.effort)}}if(isQwenFamilyWireModel(wireModel)){return{enable_thinking:true}}return{}}clampTieredEffort(effort){const clamped=clampReasoningEffort(effort,DASHSCOPE_TIERED_EFFORTS);if(clamped!==effort&&!this.effortClampWarned){debugLogger2.warn(`reasoning.effort='${effort}' is not accepted by the DashScope tiered-effort family; using '${clamped}'.`);this.effortClampWarned=true}return clamped}dropConflictingThinkingKnobs(model,merged,selectedThinkingKnob){const wireModel=this.resolveWireModel(model);if(!isQwenFamilyWireModel(wireModel)){return[]}const isTieredEffortModel=this.isTieredEffortModel(model);if(isTieredEffortModel&&selectedThinkingKnob?.field==="enable_thinking"&&selectedThinkingKnob.value===false){merged["reasoning_effort"]="none";const dropped=["enable_thinking"];if(merged["thinking_budget"]!==void 0){dropped.push("thinking_budget")}for(const key of dropped){delete merged[key]}return dropped}const effort=merged["reasoning_effort"];if(typeof effort!=="string"){return[]}if(isTieredEffortModel&&effort==="none"){if(merged["thinking_budget"]===void 0){return[]}delete merged["thinking_budget"];return["thinking_budget"]}if(isTieredEffortModel){if(selectedThinkingKnob?.field==="reasoning_effort"&&"enable_thinking"in merged){delete merged["enable_thinking"];return["enable_thinking"]}return[]}if(merged["thinking_budget"]===void 0){return[]}delete merged["reasoning_effort"];return["reasoning_effort"]}warnConflictingKnobDrop(model,reasoningEffort,dropped){if(dropped.length===0){return}if(!this.conflictingKnobDropWarned){this.conflictingKnobDropWarned=true;debugLogger2.warn("DashScope: dropped conflicting thinking knobs",{model:this.resolveWireModel(model),reasoningEffort,dropped})}}conflictingKnobDropWarned=false;buildRequestMetadata(model,userPromptId){if(!this.shouldSendRequestMetadata(model)){return{}}return this.buildMetadata(userPromptId)||{}}shouldSendRequestMetadata(model){const configured=this.contentGeneratorConfig.enableRequestMetadata;if(typeof configured==="boolean"){return configured}return isQwenFamilyWireModel(this.resolveWireModel(model))}buildMetadata(userPromptId){const channel=this.cliConfig.getChannel?.();return{metadata:{sessionId:this.cliConfig.getSessionId?.(),promptId:userPromptId,...channel?{channel}:{}}}}getDefaultGenerationConfig(){return{}}addDashScopeCacheControl(request,cacheControl,reattachBlockCount=0){const messages=request.messages;const systemIndex=messages.findIndex(msg=>msg.role==="system");const lastIndex=messages.length-1;const stableBlock=reattachBlockCount>0&&lastIndex>=0?this.lastStableBlock(messages,reattachBlockCount):{messageIndex:lastIndex,excludeTail:0};const updatedMessages=messages.length===0?messages:messages.map((message,index)=>{const isConversationAnchor=stableBlock?.messageIndex===index&&cacheControl==="all";const shouldAddCacheControl=Boolean(index===systemIndex&&systemIndex!==-1||isConversationAnchor);if(!shouldAddCacheControl||!("content"in message)||message.content===null||message.content===void 0){return message}return{...message,content:this.addCacheControlToContent(message.content,isConversationAnchor&&stableBlock?stableBlock.excludeTail:0)}});return updatedMessages}lastStableBlock(messages,reattachBlockCount){let remaining=reattachBlockCount;for(let index=messages.length-1;index>=0;index--){const content=messages[index].content;const blockCount=typeof content==="string"?content.length>0?1:0:Array.isArray(content)?content.length:0;if(blockCount===0)continue;if(blockCount>remaining){return{messageIndex:index,excludeTail:remaining}}remaining-=blockCount}return void 0}addCacheControlToContent(content,excludeTail=0){const contentArray=this.normalizeContentToArray(content);return this.addCacheControlToContentArray(contentArray,excludeTail)}normalizeContentToArray(content){if(typeof content==="string"){return[{type:"text",text:content}]}return[...content]}addCacheControlToContentArray(contentArray,excludeTail=0){if(contentArray.length===0){return contentArray}let targetIndex=contentArray.length-1-excludeTail;if(targetIndex<0){return contentArray}if(excludeTail>0){while(targetIndex>0&&contentArray[targetIndex].type!=="text"){targetIndex-=1}}const lastItem=contentArray[targetIndex];contentArray[targetIndex]={...lastItem,cache_control:{type:"ephemeral"}};return contentArray}isGlmModel(model){return!!model&&model.toLowerCase().startsWith("glm-")}hasFunctionCallingContext(request){if(request.tools&&request.tools.length>0){return true}return request.messages.some(message=>{if(message.role==="tool"){return true}if(message.role==="assistant"){const toolCalls=message.tool_calls;return Array.isArray(toolCalls)&&toolCalls.length>0}return false})}flattenTextContent(messages){return messages.map(message=>{if(!("content"in message)||!Array.isArray(message.content)){return message}const parts=message.content;if(parts.length===0){return message}const isTextOnly=parts.every(part=>part&&part.type==="text");if(!isTextOnly){return message}const text=parts.map(part=>part.text??"").join("\n\n");return{...message,content:text}})}static VISION_MODEL_EXACT_MATCHES=new Set(["coder-model"]);static VISION_MODEL_PREFIX_PATTERNS=["qwen-vl","qwen3-vl-plus","qwen3.5-plus","qwen3.6-plus","qwen3.7-plus"];isVisionModel(model){if(!model){return false}const normalized=model.toLowerCase();if(_DashScopeOpenAICompatibleProvider.VISION_MODEL_EXACT_MATCHES.has(normalized)){return true}for(const prefix of _DashScopeOpenAICompatibleProvider.VISION_MODEL_PREFIX_PATTERNS){if(normalized.startsWith(prefix)){return true}}return false}shouldEnableCacheControl(){return this.cliConfig.getContentGeneratorConfig()?.enableCacheControl!==false}};export{DefaultOpenAICompatibleProvider,selectDashScopeThinkingKnob,DASHSCOPE_REGIONAL_HOSTS,DashScopeOpenAICompatibleProvider};
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{SessionService}from"./chunk-GG7RNHZW.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function runWithWorkspaceRuntimeStorage(runtime,fn){return Storage.runWithResolvedRuntimeBaseDir(runtime.sessionRuntimeBaseDir,fn)}__name(runWithWorkspaceRuntimeStorage,"runWithWorkspaceRuntimeStorage");function createWorkspaceRuntimeSessionService(runtime,options={}){return new SessionService(runtime.workspaceCwd,{...options,runtimeBaseDir:runtime.sessionRuntimeBaseDir})}__name(createWorkspaceRuntimeSessionService,"createWorkspaceRuntimeSessionService");export{runWithWorkspaceRuntimeStorage,createWorkspaceRuntimeSessionService};
3
+ import{SessionService}from"./chunk-IFAUFERF.js";import{Storage}from"./chunk-EPODBRBP.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function runWithWorkspaceRuntimeStorage(runtime,fn){return Storage.runWithResolvedRuntimeBaseDir(runtime.sessionRuntimeBaseDir,fn)}__name(runWithWorkspaceRuntimeStorage,"runWithWorkspaceRuntimeStorage");function createWorkspaceRuntimeSessionService(runtime,options={}){return new SessionService(runtime.workspaceCwd,{...options,runtimeBaseDir:runtime.sessionRuntimeBaseDir})}__name(createWorkspaceRuntimeSessionService,"createWorkspaceRuntimeSessionService");export{runWithWorkspaceRuntimeStorage,createWorkspaceRuntimeSessionService};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{loadSettings,readConfigFile}from"./chunk-JV5FCFG4.js";import{getCurrentLanguage}from"./chunk-4IE26CIN.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-LL5HVGWF.js";import{isWorkspaceTrusted}from"./chunk-ORIS5AVH.js";import{hashMcpServerConfig}from"./chunk-B3L4LODR.js";import{Config,ExtensionManager,FileDiscoveryService,MCPOAuthTokenStorage,createMcpClient,createTransport,isGatedMcpScope,normalizeClaudeMcpServer,runWithTimeout}from"./chunk-GG7RNHZW.js";import{parseBooleanEnvFlag}from"./chunk-YPIUTOL3.js";import{getMCPServerLastError,getMCPServerStatus}from"./chunk-KBPIYGHG.js";import{atomicWriteFile}from"./chunk-BMHYEQTI.js";import{writeStderrLine,writeStdoutLine}from"./chunk-SLPJ4OII.js";import{Storage}from"./chunk-EPODBRBP.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();function splitCommaList(values){if(values===void 0)return void 0;const strings=values.filter(value=>typeof value==="string");if(strings.length===0)return values.length?void 0:[];return strings.flatMap(value=>value.split(",")).map(value=>value.trim()).filter(Boolean)}__name(splitCommaList,"splitCommaList");async function addMcpServer(name,commandOrUrl,args,options){const{scope,transport,env,header,timeout,trust,description,includeTools,excludeTools,oauthClientId,oauthClientSecret,oauthRedirectUri,oauthAuthorizationUrl,oauthTokenUrl,oauthScopes}=options;const settings=loadSettings(process.cwd());const inHome=settings.workspace.path===settings.user.path;if(scope==="project"&&inHome){writeStderrLine("Error: Please use --scope user to edit settings in the home directory.");process.exit(1)}const settingsScope=scope==="user"?"User":"Workspace";let newServer={};const scopes=splitCommaList(oauthScopes);const hasOAuth=Boolean(oauthClientId||oauthClientSecret||oauthRedirectUri||oauthAuthorizationUrl||oauthTokenUrl||scopes&&scopes.length>0);if(hasOAuth&&transport==="stdio"){writeStderrLine("Error: OAuth options (--oauth-*) are only supported with --transport sse or --transport http.");process.exit(1)}const oauthConfig=hasOAuth?{enabled:true,...oauthClientId&&{clientId:oauthClientId},...oauthClientSecret&&{clientSecret:oauthClientSecret},...oauthRedirectUri&&{redirectUri:oauthRedirectUri},...oauthAuthorizationUrl&&{authorizationUrl:oauthAuthorizationUrl},...oauthTokenUrl&&{tokenUrl:oauthTokenUrl},...scopes&&scopes.length>0&&{scopes}}:void 0;const headers=header?.reduce((acc,curr)=>{const[key,...valueParts]=curr.split(":");const value=valueParts.join(":").trim();if(key.trim()&&value){acc[key.trim()]=value}return acc},{});switch(transport){case"sse":newServer={url:commandOrUrl,headers,timeout,trust,description,includeTools,excludeTools,oauth:oauthConfig};break;case"http":newServer={httpUrl:commandOrUrl,headers,timeout,trust,description,includeTools,excludeTools,oauth:oauthConfig};break;case"stdio":default:newServer={command:commandOrUrl,args:args?.map(String),env:env?.reduce((acc,curr)=>{const separator=curr.indexOf("=");if(separator===-1){return acc}const key=curr.slice(0,separator);const value=curr.slice(separator+1);if(key&&value){acc[key]=value}return acc},{}),timeout,trust,description,includeTools,excludeTools};break}const existingSettings=settings.forScope(settingsScope).settings;const mcpServers=existingSettings.mcpServers||{};const isExistingServer=!!mcpServers[name];if(isExistingServer){writeStdoutLine(`MCP server "${name}" is already configured within ${scope} settings.`)}mcpServers[name]=newServer;settings.setValue(settingsScope,"mcpServers",mcpServers);if(isExistingServer){writeStdoutLine(`MCP server "${name}" updated in ${scope} settings.`)}else{writeStdoutLine(`MCP server "${name}" added to ${scope} settings. (${transport})`)}}__name(addMcpServer,"addMcpServer");var addCommand={command:"add <name> <commandOrUrl> [args...]",describe:"Add a server",builder:__name(yargs=>yargs.usage("Usage: qwen mcp add [options] <name> <commandOrUrl> [args...]").parserConfiguration({"unknown-options-as-args":true,"populate--":true}).positional("name",{describe:"Name of the server",type:"string",demandOption:true}).positional("commandOrUrl",{describe:"Command (stdio) or URL (sse, http)",type:"string",demandOption:true}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}).option("transport",{alias:"t",describe:"Transport type (stdio, sse, http). Auto-detected from URL if not specified.",type:"string",choices:["stdio","sse","http"]}).option("env",{alias:"e",describe:"Set environment variables (e.g. -e KEY=value)",type:"array",string:true,nargs:1}).option("header",{alias:"H",describe:'Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123")',type:"array",string:true,nargs:1}).option("timeout",{describe:"Set connection timeout in milliseconds",type:"number"}).option("trust",{describe:"Trust the server (bypass its tool call confirmations in a trusted workspace)",type:"boolean"}).option("description",{describe:"Set the description for the server",type:"string"}).option("include-tools",{describe:"A comma-separated list of tools to include",type:"array",string:true}).option("exclude-tools",{describe:"A comma-separated list of tools to exclude",type:"array",string:true}).option("oauth-client-id",{describe:"OAuth client ID for MCP server authentication",type:"string"}).option("oauth-client-secret",{describe:"OAuth client secret for MCP server authentication",type:"string"}).option("oauth-redirect-uri",{describe:"OAuth redirect URI (e.g., https://your-server.com/oauth/callback). Defaults to localhost for local setups.",type:"string"}).option("oauth-authorization-url",{describe:"OAuth authorization URL",type:"string"}).option("oauth-token-url",{describe:"OAuth token URL",type:"string"}).option("oauth-scopes",{describe:"OAuth scopes (comma-separated)",type:"array",string:true}).middleware(argv=>{if(argv["--"]){const existingArgs=argv["args"]||[];argv["args"]=[...existingArgs,...argv["--"]]}if(!argv["transport"]){const commandOrUrl=argv["commandOrUrl"];if(commandOrUrl&&/^https?:\/\//i.test(commandOrUrl)){argv["transport"]="http"}else{argv["transport"]="stdio"}}}),"builder"),handler:__name(async argv=>{await addMcpServer(argv["name"],argv["commandOrUrl"],argv["args"],{scope:argv["scope"],transport:argv["transport"],env:argv["env"],header:argv["header"],timeout:argv["timeout"],trust:argv["trust"],description:argv["description"],includeTools:splitCommaList(argv["includeTools"]),excludeTools:splitCommaList(argv["excludeTools"]),oauthClientId:argv["oauthClientId"],oauthClientSecret:argv["oauthClientSecret"],oauthRedirectUri:argv["oauthRedirectUri"],oauthAuthorizationUrl:argv["oauthAuthorizationUrl"],oauthTokenUrl:argv["oauthTokenUrl"],oauthScopes:argv["oauthScopes"]})},"handler")};init_esbuild_shims();async function removeMcpServer(name,options){const{scope}=options;const settingsScope=scope==="user"?"User":"Workspace";const settings=loadSettings();const existingSettings=settings.forScope(settingsScope).settings;const mcpServers=existingSettings.mcpServers||{};if(!mcpServers[name]){writeStdoutLine(`Server "${name}" not found in ${scope} settings.`);return}delete mcpServers[name];settings.setValue(settingsScope,"mcpServers",mcpServers);try{const tokenStorage=new MCPOAuthTokenStorage;await tokenStorage.deleteCredentials(name)}catch{}writeStdoutLine(`Server "${name}" removed from ${scope} settings.`)}__name(removeMcpServer,"removeMcpServer");var removeCommand={command:"remove <name>",describe:"Remove a server",builder:__name(yargs=>yargs.usage("Usage: qwen mcp remove [options] <name>").positional("name",{describe:"Name of the server",type:"string",demandOption:true}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}),"builder"),handler:__name(async argv=>{await removeMcpServer(argv["name"],{scope:argv["scope"]})},"handler")};init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var PROJECT_MCP_FILENAME=".mcp.json";function loadProjectMcpServers(projectRoot,options={}){const filePath=path.join(projectRoot,PROJECT_MCP_FILENAME);let raw;try{raw=options.strict?readConfigFile(filePath):fs.readFileSync(filePath,"utf-8")}catch(e){if(!options.strict)return{servers:{},path:void 0,errors:[]};return{servers:{},path:filePath,errors:[`Failed to read ${filePath}: ${e.message}`]}}if(raw===void 0)return{servers:{},path:void 0,errors:[]};let parsed;try{parsed=JSON.parse((0,import_strip_json_comments.default)(stripUtf8Bom(raw)))}catch(e){return{servers:{},path:filePath,errors:[`Failed to parse ${filePath}: ${e.message}`]}}const mcpServers=parsed?.mcpServers;if(!mcpServers||typeof mcpServers!=="object"||Array.isArray(mcpServers)){return{servers:{},path:filePath,errors:[`${filePath} has no "mcpServers" object`]}}const servers=Object.create(null);const errors=[];for(const[name,value]of Object.entries(mcpServers)){if(!value||typeof value!=="object"||Array.isArray(value)){errors.push(`${filePath}: server "${name}" is not an object \u2014 skipped`);continue}servers[name]={...normalizeClaudeMcpServer(value),scope:"project"}}return{servers,path:filePath,errors}}__name(loadProjectMcpServers,"loadProjectMcpServers");function assembleMcpServers(mergedSettingsServers,cwd,cliMcpServers){const belowProject={};const aboveProject={};for(const[name,config]of Object.entries(mergedSettingsServers??{})){if(config.scope==="workspace"||config.scope==="system"){aboveProject[name]=config}else{belowProject[name]=config}}const projectResult=loadProjectMcpServers(cwd);for(const error of projectResult.errors){writeStderrLine(`Warning: ${error}`)}return{...belowProject,...projectResult.servers,...aboveProject,...cliMcpServers??{}}}__name(assembleMcpServers,"assembleMcpServers");init_esbuild_shims();import*as fs2 from"node:fs";import*as os from"node:os";import*as path2 from"node:path";var import_strip_json_comments2=__toESM(require_strip_json_comments(),1);var MCP_APPROVALS_FILENAME="mcpApprovals.json";function getMcpApprovalsPath(){if(process.env["QWEN_CODE_MCP_APPROVALS_PATH"]){return process.env["QWEN_CODE_MCP_APPROVALS_PATH"]}return path2.join(Storage.getGlobalQwenDir(),MCP_APPROVALS_FILENAME)}__name(getMcpApprovalsPath,"getMcpApprovalsPath");function normalizeProjectRoot(projectRoot){const resolved=path2.resolve(projectRoot);return os.platform()==="win32"?resolved.toLowerCase():resolved}__name(normalizeProjectRoot,"normalizeProjectRoot");function isApprovalRecordMap(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isApprovalRecordMap,"isApprovalRecordMap");function isWin32AbsolutePath(p){return/^[A-Za-z]:[\\/]/.test(p)||/^\\\\/.test(p)}__name(isWin32AbsolutePath,"isWin32AbsolutePath");function mergeApprovalRecords(existing,incoming){const merged=Object.assign(Object.create(null),existing);for(const[name,record]of Object.entries(incoming)){if(!isApprovalRecordMap(record)){continue}const current=merged[name];if(!current){merged[name]=record}else if(current.status!==record.status){merged[name]=current.status==="rejected"?current:record}}return merged}__name(mergeApprovalRecords,"mergeApprovalRecords");function normalizeStoredProjectKeys(config){if(os.platform()!=="win32"){return config}const normalized=Object.create(null);for(const[key,value]of Object.entries(config)){const projectKey=isWin32AbsolutePath(key)?key.toLowerCase():key;const existing=normalized[projectKey];normalized[projectKey]=isApprovalRecordMap(existing)&&isApprovalRecordMap(value)?mergeApprovalRecords(existing,value):isApprovalRecordMap(value)||!isApprovalRecordMap(existing)?value:existing}return normalized}__name(normalizeStoredProjectKeys,"normalizeStoredProjectKeys");var LoadedMcpApprovals=class{constructor(file,errors){this.file=file;this.errors=errors}static{__name(this,"LoadedMcpApprovals")}getState(projectRoot,serverName,config){const record=this.file.config[normalizeProjectRoot(projectRoot)]?.[serverName];if(!record){return"pending"}if(record.hash!==hashMcpServerConfig(config)){return"pending"}return record.status}async setState(projectRoot,serverName,config,status){const root=normalizeProjectRoot(projectRoot);const existing=this.file.config[root];const project=isApprovalRecordMap(existing)?existing:Object.create(null);Object.defineProperty(project,serverName,{value:{hash:hashMcpServerConfig(config),status},enumerable:true,configurable:true,writable:true});this.file.config[root]=project;await saveMcpApprovals(this.file)}};var loadedMcpApprovals;function loadMcpApprovals(){if(loadedMcpApprovals){return loadedMcpApprovals}const errors=[];let config={};const filePath=getMcpApprovalsPath();try{if(fs2.existsSync(filePath)){const content=fs2.readFileSync(filePath,"utf-8");const parsed=JSON.parse((0,import_strip_json_comments2.default)(content));if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){errors.push({message:"MCP approvals file is not a valid JSON object.",path:filePath})}else{config=normalizeStoredProjectKeys(parsed)}}}catch(error){errors.push({message:getErrorMessage(error),path:filePath})}loadedMcpApprovals=new LoadedMcpApprovals({path:filePath,config},errors);for(const error of errors){writeStderrLine(`Warning: MCP approvals file error: ${error.message}`)}return loadedMcpApprovals}__name(loadMcpApprovals,"loadMcpApprovals");function getPendingGatedMcpServers(mcpServers,projectRoot){const approvals=loadMcpApprovals();const pending=[];for(const[name,config]of Object.entries(mcpServers)){if(!isGatedMcpScope(config.scope)){continue}if(approvals.getState(projectRoot,name,config)!=="approved"){pending.push(name)}}return pending}__name(getPendingGatedMcpServers,"getPendingGatedMcpServers");function getPromptableMcpServers(mcpServers,projectRoot){const approvals=loadMcpApprovals();const promptable=[];for(const[name,config]of Object.entries(mcpServers)){if(!isGatedMcpScope(config.scope)){continue}if(approvals.getState(projectRoot,name,config)==="pending"){promptable.push(name)}}return promptable}__name(getPromptableMcpServers,"getPromptableMcpServers");async function saveMcpApprovals(file){try{const dirPath=path2.dirname(file.path);if(!fs2.existsSync(dirPath)){fs2.mkdirSync(dirPath,{recursive:true})}await atomicWriteFile(file.path,JSON.stringify(file.config,null,2),{mode:384})}catch(error){writeStderrLine("Error saving MCP approvals file.");writeStderrLine(error instanceof Error?error.message:String(error))}}__name(saveMcpApprovals,"saveMcpApprovals");var COLOR_GREEN="\x1B[32m";var COLOR_YELLOW="\x1B[33m";var COLOR_RED="\x1B[31m";var RESET_COLOR="\x1B[0m";var MCP_CONNECT_TIMEOUT_MS=1e4;async function getMcpServersFromConfig(){const settings=loadSettings();const extensionManager=new ExtensionManager({isWorkspaceTrusted:isWorkspaceTrusted(settings.merged).isTrusted??true,telemetrySettings:settings.merged.telemetry,locale:getCurrentLanguage()});await extensionManager.refreshCache();const extensions=extensionManager.getLoadedExtensions();const mcpServers=assembleMcpServers(settings.merged.mcpServers,process.cwd());for(const extension of extensions){if(extension.isActive){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key]){return}mcpServers[key]={...server,extensionName:extension.config.name}})}}return mcpServers}__name(getMcpServersFromConfig,"getMcpServersFromConfig");async function testMCPConnection(serverName,config){const client=createMcpClient("mcp-test-client",config);let transport;try{transport=await createTransport(serverName,config,false)}catch(_error){await client.close();return{status:"disconnected",timedOut:false}}try{await runWithTimeout(client.connect(transport,{timeout:MCP_CONNECT_TIMEOUT_MS}),MCP_CONNECT_TIMEOUT_MS,`MCP connection for ${serverName}`);await client.close();return{status:"connected",timedOut:false}}catch(error){await transport.close();return{status:"disconnected",timedOut:error instanceof Error&&error.message.startsWith("Timed out after ")}}}__name(testMCPConnection,"testMCPConnection");async function getServerStatus(serverName,server){return await testMCPConnection(serverName,server)}__name(getServerStatus,"getServerStatus");async function listMcpServers(){const mcpServers=await getMcpServersFromConfig();const serverNames=Object.keys(mcpServers);if(serverNames.length===0){writeStdoutLine("No MCP servers configured.");return}writeStdoutLine("Configured MCP servers:\n");const cwd=process.cwd();let approvals;for(const serverName of serverNames){const server=mcpServers[serverName];let serverInfo=`${serverName}: `;if(server.httpUrl){serverInfo+=`${server.httpUrl} (http)`}else if(server.url){serverInfo+=`${server.url} (sse)`}else if(server.command){serverInfo+=`${server.command} ${server.args?.join(" ")||""} (stdio)`}if(isGatedMcpScope(server.scope)){approvals??=loadMcpApprovals();const state=approvals.getState(cwd,serverName,server);if(state!=="approved"){const statusText2=state==="rejected"?"Rejected":"Pending approval";writeStdoutLine(`${COLOR_YELLOW}\u25CF${RESET_COLOR} ${serverInfo} - ${statusText2}`);continue}}const{status,timedOut}=await getServerStatus(serverName,server);let statusIndicator="";let statusText="";switch(status){case"connected":statusIndicator=COLOR_GREEN+"\u2713"+RESET_COLOR;statusText="Connected";break;case"connecting":statusIndicator=COLOR_YELLOW+"\u2026"+RESET_COLOR;statusText="Connecting";break;case"disconnected":default:statusIndicator=COLOR_RED+"\u2717"+RESET_COLOR;statusText=timedOut?`Disconnected (timed out after ${MCP_CONNECT_TIMEOUT_MS}ms)`:"Disconnected";break}writeStdoutLine(`${statusIndicator} ${serverInfo} - ${statusText}`)}}__name(listMcpServers,"listMcpServers");var listCommand={command:"list",describe:"List all configured MCP servers",handler:__name(async()=>{await listMcpServers()},"handler")};init_esbuild_shims();async function getMcpServersFromConfig2(extensionManager){const settings=loadSettings();const extManager=extensionManager??new ExtensionManager({isWorkspaceTrusted:isWorkspaceTrusted(settings.merged).isTrusted??true,telemetrySettings:settings.merged.telemetry,locale:getCurrentLanguage()});if(!extensionManager){await extManager.refreshCache()}const extensions=extManager.getLoadedExtensions();const mcpServers=assembleMcpServers(settings.merged.mcpServers,process.cwd());for(const extension of extensions){if(extension.isActive){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key]){return}mcpServers[key]={...server,extensionName:extension.config.name}})}}return mcpServers}__name(getMcpServersFromConfig2,"getMcpServersFromConfig");async function createMinimalConfig(){const settings=loadSettings();const cwd=process.cwd();const fileFiltering=settings.merged.context?.fileFiltering;const fileService=new FileDiscoveryService(cwd,fileFiltering?.customIgnoreFiles);const mcpServers=await getMcpServersFromConfig2();const allowedMcpServers=settings.merged.mcp?.allowed?new Set(settings.merged.mcp.allowed.filter(Boolean)):void 0;const excludedMcpServers=settings.merged.mcp?.excluded?new Set(settings.merged.mcp.excluded.filter(Boolean)):void 0;const config=new Config({sessionId:"mcp-reconnect",targetDir:cwd,cwd,debugMode:false,chatRecording:false,mcpServers,pendingMcpServers:getPendingGatedMcpServers(mcpServers,cwd),fileDiscoveryService:fileService,mcpServerCommand:settings.merged.mcp?.serverCommand,allowedMcpServers:allowedMcpServers?Array.from(allowedMcpServers):void 0,excludedMcpServers:excludedMcpServers?Array.from(excludedMcpServers):void 0,trustedFolder:isWorkspaceTrusted(settings.merged).isTrusted??true,usageStatisticsEnabled:parseBooleanEnvFlag(process.env["QWEN_USAGE_STATISTICS_ENABLED"])??settings.merged.privacy?.usageStatisticsEnabled??true,proxy:settings.merged.proxy||process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"],...fileFiltering!==void 0?{fileFiltering}:{}});await config.initialize({skipMcpDiscovery:true});return config}__name(createMinimalConfig,"createMinimalConfig");var SkippedConnectionError=class extends Error{static{__name(this,"SkippedConnectionError")}skipReason;constructor(skipReason){super(`no connection attempt was made: ${skipReason}`);this.name="SkippedConnectionError";this.skipReason=skipReason}};var SESSION_SCOPE_NOTE="Note: this command reconnects in a separate process; it cannot refresh the MCP tools of an already-running Qwen Code session. Restart that session if its tools remain unavailable.";function createReconnectError(message,exitCode=1){const error=new Error(message);error.exitCode=exitCode;return error}__name(createReconnectError,"createReconnectError");function describeSkippedConnectionReason(config,serverName){const unavailableReason=config.getMcpServerUnavailableReason(serverName);if(unavailableReason==="excluded"){return"server is excluded in settings (mcp.excluded)"}if(unavailableReason==="not_allowed"){return"server is not in the mcp.allowed list"}if(config.isMcpServerDisabled(serverName)){return"server is disabled in settings"}if(config.isMcpServerPendingApproval(serverName)){return"server is pending approval (.mcp.json)"}if(config.isTrustedFolder()===false){return"workspace folder is not trusted"}return void 0}__name(describeSkippedConnectionReason,"describeSkippedConnectionReason");async function discoverAndVerifyConnection(config,serverName){const toolRegistry=config.getToolRegistry();await toolRegistry.discoverToolsForServer(serverName);const status=getMCPServerStatus(serverName);if(status!=="connected"){const skippedReason=describeSkippedConnectionReason(config,serverName);if(skippedReason){throw new SkippedConnectionError(skippedReason)}const lastError=getMCPServerLastError(serverName);throw new Error(`connection attempt finished without a live connection (status: ${status})`+(lastError?`: ${lastError}`:""))}}__name(discoverAndVerifyConnection,"discoverAndVerifyConnection");async function reconnectMcpServer(serverName){const mcpServers=await getMcpServersFromConfig2();if(!mcpServers[serverName]){throw createReconnectError(`Error: Server "${serverName}" not found in configuration.`)}writeStdoutLine(`Reconnecting to server "${serverName}"...`);let config;try{config=await createMinimalConfig();await discoverAndVerifyConnection(config,serverName);writeStdoutLine(`Successfully reconnected to server "${serverName}".`);writeStdoutLine(SESSION_SCOPE_NOTE)}catch(error){const message=error instanceof Error?error.message:String(error);writeStdoutLine(SESSION_SCOPE_NOTE);throw createReconnectError(`Failed to reconnect to server "${serverName}": ${message}`)}finally{if(config){await config.shutdown()}}}__name(reconnectMcpServer,"reconnectMcpServer");async function reconnectAllMcpServers(){const settings=loadSettings();const extensionManager=new ExtensionManager({isWorkspaceTrusted:isWorkspaceTrusted(settings.merged).isTrusted??true,telemetrySettings:settings.merged.telemetry,locale:getCurrentLanguage()});await extensionManager.refreshCache();const mcpServers=await getMcpServersFromConfig2(extensionManager);const serverNames=Object.keys(mcpServers);if(serverNames.length===0){writeStdoutLine("No MCP servers configured.");return}writeStdoutLine("Reconnecting to all MCP servers...\n");let config;let failedCount=0;try{config=await createMinimalConfig();for(const serverName of serverNames){try{await discoverAndVerifyConnection(config,serverName);writeStdoutLine(`\u2713 ${serverName}: Reconnected successfully`)}catch(error){if(error instanceof SkippedConnectionError){writeStdoutLine(`- ${serverName}: Skipped - ${error.skipReason}`);continue}failedCount++;const message=error instanceof Error?error.message:String(error);writeStdoutLine(`\u2717 ${serverName}: Failed - ${message}`)}}writeStdoutLine("");writeStdoutLine(SESSION_SCOPE_NOTE)}finally{if(config){await config.shutdown()}}if(failedCount>0){throw createReconnectError(`Failed to reconnect ${failedCount} of ${serverNames.length} configured server(s).`)}}__name(reconnectAllMcpServers,"reconnectAllMcpServers");var reconnectCommand={command:"reconnect [server-name]",describe:"Reconnect MCP server(s)",builder:__name(yargs=>yargs.usage("Usage: qwen mcp reconnect [options] [server-name]").positional("server-name",{describe:"Name of the server to reconnect",type:"string"}).option("all",{alias:"a",describe:"Reconnect all configured servers",type:"boolean",default:false}).conflicts("server-name","all").check(argv=>{const serverName=argv["server-name"];const all=argv["all"];if(!serverName&&!all){throw new Error("Please specify a server name or use --all to reconnect all servers.")}return true}),"builder"),handler:__name(async argv=>{const serverName=argv["server-name"];const all=argv["all"];try{if(all){await reconnectAllMcpServers()}else if(serverName){await reconnectMcpServer(serverName)}}catch(error){const message=error instanceof Error?error.message:String(error);const exitCode=error?.exitCode??1;writeStderrLine(message);process.exit(exitCode)}},"handler")};init_esbuild_shims();function loadGatedServers(cwd){const settings=loadSettings(cwd);const all=assembleMcpServers(settings.merged.mcpServers,cwd);const gated={};for(const[serverName,config]of Object.entries(all)){if(isGatedMcpScope(config.scope)){gated[serverName]=config}}return gated}__name(loadGatedServers,"loadGatedServers");async function setProjectServerStatus(name,status,all){const cwd=process.cwd();const servers=loadGatedServers(cwd);const names=Object.keys(servers);if(names.length===0){writeStdoutLine("No approval-requiring MCP servers found (looked in .mcp.json and .qwen/settings.json).");return}const verb=status==="approved"?"Approved":"Rejected";const approvals=loadMcpApprovals();const targets=all?names:name?[name]:[];if(targets.length===0){writeStdoutLine("Specify a server name or pass --all.");return}for(const target of targets){const config=servers[target];if(!config){writeStdoutLine(`Server "${target}" not found. Available: ${names.join(", ")}`);continue}await approvals.setState(cwd,target,config,status);writeStdoutLine(`${verb} MCP server "${target}" (bound to its current config).`)}if(status==="approved"){writeStdoutLine("Approved servers connect in your next interactive session.")}}__name(setProjectServerStatus,"setProjectServerStatus");var approveCommand={command:"approve [name]",describe:"Approve a gated MCP server (.mcp.json or workspace .qwen/settings.json)",builder:__name(yargs=>yargs.usage("Usage: qwen mcp approve [options] [name]").positional("name",{describe:"Name of the gated server to approve",type:"string"}).option("all",{describe:"Approve all gated servers in this workspace",type:"boolean",default:false}),"builder"),handler:__name(async argv=>{await setProjectServerStatus(argv["name"],"approved",argv["all"])},"handler")};var rejectCommand={command:"reject [name]",describe:"Reject a gated MCP server (.mcp.json or workspace .qwen/settings.json)",builder:__name(yargs=>yargs.usage("Usage: qwen mcp reject [options] [name]").positional("name",{describe:"Name of the gated server to reject",type:"string"}).option("all",{describe:"Reject all gated servers in this workspace",type:"boolean",default:false}),"builder"),handler:__name(async argv=>{await setProjectServerStatus(argv["name"],"rejected",argv["all"])},"handler")};var mcpCommand={command:"mcp",describe:"Manage MCP servers",builder:__name(yargs=>yargs.command(addCommand).command(removeCommand).command(listCommand).command(reconnectCommand).command(approveCommand).command(rejectCommand).demandCommand(1,"You need at least one command before continuing.").version(false),"builder"),handler:__name(()=>{},"handler")};export{assembleMcpServers,loadMcpApprovals,getPendingGatedMcpServers,getPromptableMcpServers,mcpCommand};
3
+ import{loadSettings,readConfigFile}from"./chunk-4WFWZWR3.js";import{getCurrentLanguage}from"./chunk-4IE26CIN.js";import{require_strip_json_comments,stripUtf8Bom}from"./chunk-LL5HVGWF.js";import{isWorkspaceTrusted}from"./chunk-SYO5FPHL.js";import{hashMcpServerConfig}from"./chunk-RV54BGL2.js";import{Config,ExtensionManager,FileDiscoveryService,MCPOAuthTokenStorage,createMcpClient,createTransport,isGatedMcpScope,normalizeClaudeMcpServer,runWithTimeout}from"./chunk-IFAUFERF.js";import{parseBooleanEnvFlag}from"./chunk-YPIUTOL3.js";import{getMCPServerLastError,getMCPServerStatus}from"./chunk-KBPIYGHG.js";import{atomicWriteFile}from"./chunk-BMHYEQTI.js";import{writeStderrLine,writeStdoutLine}from"./chunk-SLPJ4OII.js";import{Storage}from"./chunk-EPODBRBP.js";import{getErrorMessage}from"./chunk-XYB7GC5U.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name,__toESM}from"./chunk-KBWJGX7I.js";init_esbuild_shims();init_esbuild_shims();function splitCommaList(values){if(values===void 0)return void 0;const strings=values.filter(value=>typeof value==="string");if(strings.length===0)return values.length?void 0:[];return strings.flatMap(value=>value.split(",")).map(value=>value.trim()).filter(Boolean)}__name(splitCommaList,"splitCommaList");async function addMcpServer(name,commandOrUrl,args,options){const{scope,transport,env,header,timeout,trust,description,includeTools,excludeTools,oauthClientId,oauthClientSecret,oauthRedirectUri,oauthAuthorizationUrl,oauthTokenUrl,oauthScopes}=options;const settings=loadSettings(process.cwd());const inHome=settings.workspace.path===settings.user.path;if(scope==="project"&&inHome){writeStderrLine("Error: Please use --scope user to edit settings in the home directory.");process.exit(1)}const settingsScope=scope==="user"?"User":"Workspace";let newServer={};const scopes=splitCommaList(oauthScopes);const hasOAuth=Boolean(oauthClientId||oauthClientSecret||oauthRedirectUri||oauthAuthorizationUrl||oauthTokenUrl||scopes&&scopes.length>0);if(hasOAuth&&transport==="stdio"){writeStderrLine("Error: OAuth options (--oauth-*) are only supported with --transport sse or --transport http.");process.exit(1)}const oauthConfig=hasOAuth?{enabled:true,...oauthClientId&&{clientId:oauthClientId},...oauthClientSecret&&{clientSecret:oauthClientSecret},...oauthRedirectUri&&{redirectUri:oauthRedirectUri},...oauthAuthorizationUrl&&{authorizationUrl:oauthAuthorizationUrl},...oauthTokenUrl&&{tokenUrl:oauthTokenUrl},...scopes&&scopes.length>0&&{scopes}}:void 0;const headers=header?.reduce((acc,curr)=>{const[key,...valueParts]=curr.split(":");const value=valueParts.join(":").trim();if(key.trim()&&value){acc[key.trim()]=value}return acc},{});switch(transport){case"sse":newServer={url:commandOrUrl,headers,timeout,trust,description,includeTools,excludeTools,oauth:oauthConfig};break;case"http":newServer={httpUrl:commandOrUrl,headers,timeout,trust,description,includeTools,excludeTools,oauth:oauthConfig};break;case"stdio":default:newServer={command:commandOrUrl,args:args?.map(String),env:env?.reduce((acc,curr)=>{const separator=curr.indexOf("=");if(separator===-1){return acc}const key=curr.slice(0,separator);const value=curr.slice(separator+1);if(key&&value){acc[key]=value}return acc},{}),timeout,trust,description,includeTools,excludeTools};break}const existingSettings=settings.forScope(settingsScope).settings;const mcpServers=existingSettings.mcpServers||{};const isExistingServer=!!mcpServers[name];if(isExistingServer){writeStdoutLine(`MCP server "${name}" is already configured within ${scope} settings.`)}mcpServers[name]=newServer;settings.setValue(settingsScope,"mcpServers",mcpServers);if(isExistingServer){writeStdoutLine(`MCP server "${name}" updated in ${scope} settings.`)}else{writeStdoutLine(`MCP server "${name}" added to ${scope} settings. (${transport})`)}}__name(addMcpServer,"addMcpServer");var addCommand={command:"add <name> <commandOrUrl> [args...]",describe:"Add a server",builder:__name(yargs=>yargs.usage("Usage: qwen mcp add [options] <name> <commandOrUrl> [args...]").parserConfiguration({"unknown-options-as-args":true,"populate--":true}).positional("name",{describe:"Name of the server",type:"string",demandOption:true}).positional("commandOrUrl",{describe:"Command (stdio) or URL (sse, http)",type:"string",demandOption:true}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}).option("transport",{alias:"t",describe:"Transport type (stdio, sse, http). Auto-detected from URL if not specified.",type:"string",choices:["stdio","sse","http"]}).option("env",{alias:"e",describe:"Set environment variables (e.g. -e KEY=value)",type:"array",string:true,nargs:1}).option("header",{alias:"H",describe:'Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123")',type:"array",string:true,nargs:1}).option("timeout",{describe:"Set connection timeout in milliseconds",type:"number"}).option("trust",{describe:"Trust the server (bypass its tool call confirmations in a trusted workspace)",type:"boolean"}).option("description",{describe:"Set the description for the server",type:"string"}).option("include-tools",{describe:"A comma-separated list of tools to include",type:"array",string:true}).option("exclude-tools",{describe:"A comma-separated list of tools to exclude",type:"array",string:true}).option("oauth-client-id",{describe:"OAuth client ID for MCP server authentication",type:"string"}).option("oauth-client-secret",{describe:"OAuth client secret for MCP server authentication",type:"string"}).option("oauth-redirect-uri",{describe:"OAuth redirect URI (e.g., https://your-server.com/oauth/callback). Defaults to localhost for local setups.",type:"string"}).option("oauth-authorization-url",{describe:"OAuth authorization URL",type:"string"}).option("oauth-token-url",{describe:"OAuth token URL",type:"string"}).option("oauth-scopes",{describe:"OAuth scopes (comma-separated)",type:"array",string:true}).middleware(argv=>{if(argv["--"]){const existingArgs=argv["args"]||[];argv["args"]=[...existingArgs,...argv["--"]]}if(!argv["transport"]){const commandOrUrl=argv["commandOrUrl"];if(commandOrUrl&&/^https?:\/\//i.test(commandOrUrl)){argv["transport"]="http"}else{argv["transport"]="stdio"}}}),"builder"),handler:__name(async argv=>{await addMcpServer(argv["name"],argv["commandOrUrl"],argv["args"],{scope:argv["scope"],transport:argv["transport"],env:argv["env"],header:argv["header"],timeout:argv["timeout"],trust:argv["trust"],description:argv["description"],includeTools:splitCommaList(argv["includeTools"]),excludeTools:splitCommaList(argv["excludeTools"]),oauthClientId:argv["oauthClientId"],oauthClientSecret:argv["oauthClientSecret"],oauthRedirectUri:argv["oauthRedirectUri"],oauthAuthorizationUrl:argv["oauthAuthorizationUrl"],oauthTokenUrl:argv["oauthTokenUrl"],oauthScopes:argv["oauthScopes"]})},"handler")};init_esbuild_shims();async function removeMcpServer(name,options){const{scope}=options;const settingsScope=scope==="user"?"User":"Workspace";const settings=loadSettings();const existingSettings=settings.forScope(settingsScope).settings;const mcpServers=existingSettings.mcpServers||{};if(!mcpServers[name]){writeStdoutLine(`Server "${name}" not found in ${scope} settings.`);return}delete mcpServers[name];settings.setValue(settingsScope,"mcpServers",mcpServers);try{const tokenStorage=new MCPOAuthTokenStorage;await tokenStorage.deleteCredentials(name)}catch{}writeStdoutLine(`Server "${name}" removed from ${scope} settings.`)}__name(removeMcpServer,"removeMcpServer");var removeCommand={command:"remove <name>",describe:"Remove a server",builder:__name(yargs=>yargs.usage("Usage: qwen mcp remove [options] <name>").positional("name",{describe:"Name of the server",type:"string",demandOption:true}).option("scope",{alias:"s",describe:"Configuration scope (user or project)",type:"string",default:"user",choices:["user","project"]}),"builder"),handler:__name(async argv=>{await removeMcpServer(argv["name"],{scope:argv["scope"]})},"handler")};init_esbuild_shims();init_esbuild_shims();init_esbuild_shims();import*as fs from"node:fs";import*as path from"node:path";var import_strip_json_comments=__toESM(require_strip_json_comments(),1);var PROJECT_MCP_FILENAME=".mcp.json";function loadProjectMcpServers(projectRoot,options={}){const filePath=path.join(projectRoot,PROJECT_MCP_FILENAME);let raw;try{raw=options.strict?readConfigFile(filePath):fs.readFileSync(filePath,"utf-8")}catch(e){if(!options.strict)return{servers:{},path:void 0,errors:[]};return{servers:{},path:filePath,errors:[`Failed to read ${filePath}: ${e.message}`]}}if(raw===void 0)return{servers:{},path:void 0,errors:[]};let parsed;try{parsed=JSON.parse((0,import_strip_json_comments.default)(stripUtf8Bom(raw)))}catch(e){return{servers:{},path:filePath,errors:[`Failed to parse ${filePath}: ${e.message}`]}}const mcpServers=parsed?.mcpServers;if(!mcpServers||typeof mcpServers!=="object"||Array.isArray(mcpServers)){return{servers:{},path:filePath,errors:[`${filePath} has no "mcpServers" object`]}}const servers=Object.create(null);const errors=[];for(const[name,value]of Object.entries(mcpServers)){if(!value||typeof value!=="object"||Array.isArray(value)){errors.push(`${filePath}: server "${name}" is not an object \u2014 skipped`);continue}servers[name]={...normalizeClaudeMcpServer(value),scope:"project"}}return{servers,path:filePath,errors}}__name(loadProjectMcpServers,"loadProjectMcpServers");function assembleMcpServers(mergedSettingsServers,cwd,cliMcpServers){const belowProject={};const aboveProject={};for(const[name,config]of Object.entries(mergedSettingsServers??{})){if(config.scope==="workspace"||config.scope==="system"){aboveProject[name]=config}else{belowProject[name]=config}}const projectResult=loadProjectMcpServers(cwd);for(const error of projectResult.errors){writeStderrLine(`Warning: ${error}`)}return{...belowProject,...projectResult.servers,...aboveProject,...cliMcpServers??{}}}__name(assembleMcpServers,"assembleMcpServers");init_esbuild_shims();import*as fs2 from"node:fs";import*as os from"node:os";import*as path2 from"node:path";var import_strip_json_comments2=__toESM(require_strip_json_comments(),1);var MCP_APPROVALS_FILENAME="mcpApprovals.json";function getMcpApprovalsPath(){if(process.env["QWEN_CODE_MCP_APPROVALS_PATH"]){return process.env["QWEN_CODE_MCP_APPROVALS_PATH"]}return path2.join(Storage.getGlobalQwenDir(),MCP_APPROVALS_FILENAME)}__name(getMcpApprovalsPath,"getMcpApprovalsPath");function normalizeProjectRoot(projectRoot){const resolved=path2.resolve(projectRoot);return os.platform()==="win32"?resolved.toLowerCase():resolved}__name(normalizeProjectRoot,"normalizeProjectRoot");function isApprovalRecordMap(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isApprovalRecordMap,"isApprovalRecordMap");function isWin32AbsolutePath(p){return/^[A-Za-z]:[\\/]/.test(p)||/^\\\\/.test(p)}__name(isWin32AbsolutePath,"isWin32AbsolutePath");function mergeApprovalRecords(existing,incoming){const merged=Object.assign(Object.create(null),existing);for(const[name,record]of Object.entries(incoming)){if(!isApprovalRecordMap(record)){continue}const current=merged[name];if(!current){merged[name]=record}else if(current.status!==record.status){merged[name]=current.status==="rejected"?current:record}}return merged}__name(mergeApprovalRecords,"mergeApprovalRecords");function normalizeStoredProjectKeys(config){if(os.platform()!=="win32"){return config}const normalized=Object.create(null);for(const[key,value]of Object.entries(config)){const projectKey=isWin32AbsolutePath(key)?key.toLowerCase():key;const existing=normalized[projectKey];normalized[projectKey]=isApprovalRecordMap(existing)&&isApprovalRecordMap(value)?mergeApprovalRecords(existing,value):isApprovalRecordMap(value)||!isApprovalRecordMap(existing)?value:existing}return normalized}__name(normalizeStoredProjectKeys,"normalizeStoredProjectKeys");var LoadedMcpApprovals=class{constructor(file,errors){this.file=file;this.errors=errors}static{__name(this,"LoadedMcpApprovals")}getState(projectRoot,serverName,config){const record=this.file.config[normalizeProjectRoot(projectRoot)]?.[serverName];if(!record){return"pending"}if(record.hash!==hashMcpServerConfig(config)){return"pending"}return record.status}async setState(projectRoot,serverName,config,status){const root=normalizeProjectRoot(projectRoot);const existing=this.file.config[root];const project=isApprovalRecordMap(existing)?existing:Object.create(null);Object.defineProperty(project,serverName,{value:{hash:hashMcpServerConfig(config),status},enumerable:true,configurable:true,writable:true});this.file.config[root]=project;await saveMcpApprovals(this.file)}};var loadedMcpApprovals;function loadMcpApprovals(){if(loadedMcpApprovals){return loadedMcpApprovals}const errors=[];let config={};const filePath=getMcpApprovalsPath();try{if(fs2.existsSync(filePath)){const content=fs2.readFileSync(filePath,"utf-8");const parsed=JSON.parse((0,import_strip_json_comments2.default)(content));if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)){errors.push({message:"MCP approvals file is not a valid JSON object.",path:filePath})}else{config=normalizeStoredProjectKeys(parsed)}}}catch(error){errors.push({message:getErrorMessage(error),path:filePath})}loadedMcpApprovals=new LoadedMcpApprovals({path:filePath,config},errors);for(const error of errors){writeStderrLine(`Warning: MCP approvals file error: ${error.message}`)}return loadedMcpApprovals}__name(loadMcpApprovals,"loadMcpApprovals");function getPendingGatedMcpServers(mcpServers,projectRoot){const approvals=loadMcpApprovals();const pending=[];for(const[name,config]of Object.entries(mcpServers)){if(!isGatedMcpScope(config.scope)){continue}if(approvals.getState(projectRoot,name,config)!=="approved"){pending.push(name)}}return pending}__name(getPendingGatedMcpServers,"getPendingGatedMcpServers");function getPromptableMcpServers(mcpServers,projectRoot){const approvals=loadMcpApprovals();const promptable=[];for(const[name,config]of Object.entries(mcpServers)){if(!isGatedMcpScope(config.scope)){continue}if(approvals.getState(projectRoot,name,config)==="pending"){promptable.push(name)}}return promptable}__name(getPromptableMcpServers,"getPromptableMcpServers");async function saveMcpApprovals(file){try{const dirPath=path2.dirname(file.path);if(!fs2.existsSync(dirPath)){fs2.mkdirSync(dirPath,{recursive:true})}await atomicWriteFile(file.path,JSON.stringify(file.config,null,2),{mode:384})}catch(error){writeStderrLine("Error saving MCP approvals file.");writeStderrLine(error instanceof Error?error.message:String(error))}}__name(saveMcpApprovals,"saveMcpApprovals");var COLOR_GREEN="\x1B[32m";var COLOR_YELLOW="\x1B[33m";var COLOR_RED="\x1B[31m";var RESET_COLOR="\x1B[0m";var MCP_CONNECT_TIMEOUT_MS=1e4;async function getMcpServersFromConfig(){const settings=loadSettings();const extensionManager=new ExtensionManager({isWorkspaceTrusted:isWorkspaceTrusted(settings.merged).isTrusted??true,telemetrySettings:settings.merged.telemetry,locale:getCurrentLanguage()});await extensionManager.refreshCache();const extensions=extensionManager.getLoadedExtensions();const mcpServers=assembleMcpServers(settings.merged.mcpServers,process.cwd());for(const extension of extensions){if(extension.isActive){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key]){return}mcpServers[key]={...server,extensionName:extension.config.name}})}}return mcpServers}__name(getMcpServersFromConfig,"getMcpServersFromConfig");async function testMCPConnection(serverName,config){const client=createMcpClient("mcp-test-client",config);let transport;try{transport=await createTransport(serverName,config,false)}catch(_error){await client.close();return{status:"disconnected",timedOut:false}}try{await runWithTimeout(client.connect(transport,{timeout:MCP_CONNECT_TIMEOUT_MS}),MCP_CONNECT_TIMEOUT_MS,`MCP connection for ${serverName}`);await client.close();return{status:"connected",timedOut:false}}catch(error){await transport.close();return{status:"disconnected",timedOut:error instanceof Error&&error.message.startsWith("Timed out after ")}}}__name(testMCPConnection,"testMCPConnection");async function getServerStatus(serverName,server){return await testMCPConnection(serverName,server)}__name(getServerStatus,"getServerStatus");async function listMcpServers(){const mcpServers=await getMcpServersFromConfig();const serverNames=Object.keys(mcpServers);if(serverNames.length===0){writeStdoutLine("No MCP servers configured.");return}writeStdoutLine("Configured MCP servers:\n");const cwd=process.cwd();let approvals;for(const serverName of serverNames){const server=mcpServers[serverName];let serverInfo=`${serverName}: `;if(server.httpUrl){serverInfo+=`${server.httpUrl} (http)`}else if(server.url){serverInfo+=`${server.url} (sse)`}else if(server.command){serverInfo+=`${server.command} ${server.args?.join(" ")||""} (stdio)`}if(isGatedMcpScope(server.scope)){approvals??=loadMcpApprovals();const state=approvals.getState(cwd,serverName,server);if(state!=="approved"){const statusText2=state==="rejected"?"Rejected":"Pending approval";writeStdoutLine(`${COLOR_YELLOW}\u25CF${RESET_COLOR} ${serverInfo} - ${statusText2}`);continue}}const{status,timedOut}=await getServerStatus(serverName,server);let statusIndicator="";let statusText="";switch(status){case"connected":statusIndicator=COLOR_GREEN+"\u2713"+RESET_COLOR;statusText="Connected";break;case"connecting":statusIndicator=COLOR_YELLOW+"\u2026"+RESET_COLOR;statusText="Connecting";break;case"disconnected":default:statusIndicator=COLOR_RED+"\u2717"+RESET_COLOR;statusText=timedOut?`Disconnected (timed out after ${MCP_CONNECT_TIMEOUT_MS}ms)`:"Disconnected";break}writeStdoutLine(`${statusIndicator} ${serverInfo} - ${statusText}`)}}__name(listMcpServers,"listMcpServers");var listCommand={command:"list",describe:"List all configured MCP servers",handler:__name(async()=>{await listMcpServers()},"handler")};init_esbuild_shims();async function getMcpServersFromConfig2(extensionManager){const settings=loadSettings();const extManager=extensionManager??new ExtensionManager({isWorkspaceTrusted:isWorkspaceTrusted(settings.merged).isTrusted??true,telemetrySettings:settings.merged.telemetry,locale:getCurrentLanguage()});if(!extensionManager){await extManager.refreshCache()}const extensions=extManager.getLoadedExtensions();const mcpServers=assembleMcpServers(settings.merged.mcpServers,process.cwd());for(const extension of extensions){if(extension.isActive){Object.entries(extension.config.mcpServers||{}).forEach(([key,server])=>{if(mcpServers[key]){return}mcpServers[key]={...server,extensionName:extension.config.name}})}}return mcpServers}__name(getMcpServersFromConfig2,"getMcpServersFromConfig");async function createMinimalConfig(){const settings=loadSettings();const cwd=process.cwd();const fileFiltering=settings.merged.context?.fileFiltering;const fileService=new FileDiscoveryService(cwd,fileFiltering?.customIgnoreFiles);const mcpServers=await getMcpServersFromConfig2();const allowedMcpServers=settings.merged.mcp?.allowed?new Set(settings.merged.mcp.allowed.filter(Boolean)):void 0;const excludedMcpServers=settings.merged.mcp?.excluded?new Set(settings.merged.mcp.excluded.filter(Boolean)):void 0;const config=new Config({sessionId:"mcp-reconnect",targetDir:cwd,cwd,debugMode:false,chatRecording:false,mcpServers,pendingMcpServers:getPendingGatedMcpServers(mcpServers,cwd),fileDiscoveryService:fileService,mcpServerCommand:settings.merged.mcp?.serverCommand,allowedMcpServers:allowedMcpServers?Array.from(allowedMcpServers):void 0,excludedMcpServers:excludedMcpServers?Array.from(excludedMcpServers):void 0,trustedFolder:isWorkspaceTrusted(settings.merged).isTrusted??true,usageStatisticsEnabled:parseBooleanEnvFlag(process.env["QWEN_USAGE_STATISTICS_ENABLED"])??settings.merged.privacy?.usageStatisticsEnabled??true,proxy:settings.merged.proxy||process.env["HTTPS_PROXY"]||process.env["https_proxy"]||process.env["HTTP_PROXY"]||process.env["http_proxy"],...fileFiltering!==void 0?{fileFiltering}:{}});await config.initialize({skipMcpDiscovery:true});return config}__name(createMinimalConfig,"createMinimalConfig");var SkippedConnectionError=class extends Error{static{__name(this,"SkippedConnectionError")}skipReason;constructor(skipReason){super(`no connection attempt was made: ${skipReason}`);this.name="SkippedConnectionError";this.skipReason=skipReason}};var SESSION_SCOPE_NOTE="Note: this command reconnects in a separate process; it cannot refresh the MCP tools of an already-running Qwen Code session. Restart that session if its tools remain unavailable.";function createReconnectError(message,exitCode=1){const error=new Error(message);error.exitCode=exitCode;return error}__name(createReconnectError,"createReconnectError");function describeSkippedConnectionReason(config,serverName){const unavailableReason=config.getMcpServerUnavailableReason(serverName);if(unavailableReason==="excluded"){return"server is excluded in settings (mcp.excluded)"}if(unavailableReason==="not_allowed"){return"server is not in the mcp.allowed list"}if(config.isMcpServerDisabled(serverName)){return"server is disabled in settings"}if(config.isMcpServerPendingApproval(serverName)){return"server is pending approval (.mcp.json)"}if(config.isTrustedFolder()===false){return"workspace folder is not trusted"}return void 0}__name(describeSkippedConnectionReason,"describeSkippedConnectionReason");async function discoverAndVerifyConnection(config,serverName){const toolRegistry=config.getToolRegistry();await toolRegistry.discoverToolsForServer(serverName);const status=getMCPServerStatus(serverName);if(status!=="connected"){const skippedReason=describeSkippedConnectionReason(config,serverName);if(skippedReason){throw new SkippedConnectionError(skippedReason)}const lastError=getMCPServerLastError(serverName);throw new Error(`connection attempt finished without a live connection (status: ${status})`+(lastError?`: ${lastError}`:""))}}__name(discoverAndVerifyConnection,"discoverAndVerifyConnection");async function reconnectMcpServer(serverName){const mcpServers=await getMcpServersFromConfig2();if(!mcpServers[serverName]){throw createReconnectError(`Error: Server "${serverName}" not found in configuration.`)}writeStdoutLine(`Reconnecting to server "${serverName}"...`);let config;try{config=await createMinimalConfig();await discoverAndVerifyConnection(config,serverName);writeStdoutLine(`Successfully reconnected to server "${serverName}".`);writeStdoutLine(SESSION_SCOPE_NOTE)}catch(error){const message=error instanceof Error?error.message:String(error);writeStdoutLine(SESSION_SCOPE_NOTE);throw createReconnectError(`Failed to reconnect to server "${serverName}": ${message}`)}finally{if(config){await config.shutdown()}}}__name(reconnectMcpServer,"reconnectMcpServer");async function reconnectAllMcpServers(){const settings=loadSettings();const extensionManager=new ExtensionManager({isWorkspaceTrusted:isWorkspaceTrusted(settings.merged).isTrusted??true,telemetrySettings:settings.merged.telemetry,locale:getCurrentLanguage()});await extensionManager.refreshCache();const mcpServers=await getMcpServersFromConfig2(extensionManager);const serverNames=Object.keys(mcpServers);if(serverNames.length===0){writeStdoutLine("No MCP servers configured.");return}writeStdoutLine("Reconnecting to all MCP servers...\n");let config;let failedCount=0;try{config=await createMinimalConfig();for(const serverName of serverNames){try{await discoverAndVerifyConnection(config,serverName);writeStdoutLine(`\u2713 ${serverName}: Reconnected successfully`)}catch(error){if(error instanceof SkippedConnectionError){writeStdoutLine(`- ${serverName}: Skipped - ${error.skipReason}`);continue}failedCount++;const message=error instanceof Error?error.message:String(error);writeStdoutLine(`\u2717 ${serverName}: Failed - ${message}`)}}writeStdoutLine("");writeStdoutLine(SESSION_SCOPE_NOTE)}finally{if(config){await config.shutdown()}}if(failedCount>0){throw createReconnectError(`Failed to reconnect ${failedCount} of ${serverNames.length} configured server(s).`)}}__name(reconnectAllMcpServers,"reconnectAllMcpServers");var reconnectCommand={command:"reconnect [server-name]",describe:"Reconnect MCP server(s)",builder:__name(yargs=>yargs.usage("Usage: qwen mcp reconnect [options] [server-name]").positional("server-name",{describe:"Name of the server to reconnect",type:"string"}).option("all",{alias:"a",describe:"Reconnect all configured servers",type:"boolean",default:false}).conflicts("server-name","all").check(argv=>{const serverName=argv["server-name"];const all=argv["all"];if(!serverName&&!all){throw new Error("Please specify a server name or use --all to reconnect all servers.")}return true}),"builder"),handler:__name(async argv=>{const serverName=argv["server-name"];const all=argv["all"];try{if(all){await reconnectAllMcpServers()}else if(serverName){await reconnectMcpServer(serverName)}}catch(error){const message=error instanceof Error?error.message:String(error);const exitCode=error?.exitCode??1;writeStderrLine(message);process.exit(exitCode)}},"handler")};init_esbuild_shims();function loadGatedServers(cwd){const settings=loadSettings(cwd);const all=assembleMcpServers(settings.merged.mcpServers,cwd);const gated={};for(const[serverName,config]of Object.entries(all)){if(isGatedMcpScope(config.scope)){gated[serverName]=config}}return gated}__name(loadGatedServers,"loadGatedServers");async function setProjectServerStatus(name,status,all){const cwd=process.cwd();const servers=loadGatedServers(cwd);const names=Object.keys(servers);if(names.length===0){writeStdoutLine("No approval-requiring MCP servers found (looked in .mcp.json and .qwen/settings.json).");return}const verb=status==="approved"?"Approved":"Rejected";const approvals=loadMcpApprovals();const targets=all?names:name?[name]:[];if(targets.length===0){writeStdoutLine("Specify a server name or pass --all.");return}for(const target of targets){const config=servers[target];if(!config){writeStdoutLine(`Server "${target}" not found. Available: ${names.join(", ")}`);continue}await approvals.setState(cwd,target,config,status);writeStdoutLine(`${verb} MCP server "${target}" (bound to its current config).`)}if(status==="approved"){writeStdoutLine("Approved servers connect in your next interactive session.")}}__name(setProjectServerStatus,"setProjectServerStatus");var approveCommand={command:"approve [name]",describe:"Approve a gated MCP server (.mcp.json or workspace .qwen/settings.json)",builder:__name(yargs=>yargs.usage("Usage: qwen mcp approve [options] [name]").positional("name",{describe:"Name of the gated server to approve",type:"string"}).option("all",{describe:"Approve all gated servers in this workspace",type:"boolean",default:false}),"builder"),handler:__name(async argv=>{await setProjectServerStatus(argv["name"],"approved",argv["all"])},"handler")};var rejectCommand={command:"reject [name]",describe:"Reject a gated MCP server (.mcp.json or workspace .qwen/settings.json)",builder:__name(yargs=>yargs.usage("Usage: qwen mcp reject [options] [name]").positional("name",{describe:"Name of the gated server to reject",type:"string"}).option("all",{describe:"Reject all gated servers in this workspace",type:"boolean",default:false}),"builder"),handler:__name(async argv=>{await setProjectServerStatus(argv["name"],"rejected",argv["all"])},"handler")};var mcpCommand={command:"mcp",describe:"Manage MCP servers",builder:__name(yargs=>yargs.command(addCommand).command(removeCommand).command(listCommand).command(reconnectCommand).command(approveCommand).command(rejectCommand).demandCommand(1,"You need at least one command before continuing.").version(false),"builder"),handler:__name(()=>{},"handler")};export{assembleMcpServers,loadMcpApprovals,getPendingGatedMcpServers,getPromptableMcpServers,mcpCommand};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{DropNoticeThrottle,DropReceiptCoalescer,getPeerControllerRegistryPath,readPeerControllerRegistrySync,resolveControllerToken,startPeerInbox}from"./chunk-B3L4LODR.js";import{InboundGate,MAX_HELD_MESSAGES,PEER_ADMISSION_LIMITS,canonicalizeMsgId,drainSendPacer,forgetSendPacerMessages,peerSenderKey,refundSendPacerMessage,refundSendPacerToken,sendDeliveryStatus,settleSentPeerMessage}from"./chunk-LJGQNGCO.js";import{formatPeerDisplay,formatPeerEnvelope}from"./chunk-Y77BXKWA.js";import{MESSAGING_SOCKET_ENV,MESSAGING_TOKEN_ENV,clearInheritedPeerMessagingEnv}from"./chunk-NPAX2UFU.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{randomBytes}from"node:crypto";var debugLogger=createDebugLogger("PEER_MESSAGING");var MAX_ACCEPTED_BACKLOG=MAX_HELD_MESSAGES;var CLOSE_DROP_FLUSH_BOUND_MS=1e3;var MAX_UNHEARD_DROP_NOTICES=20;var RECEIVER_REFILL_MS=PEER_ADMISSION_LIMITS.bucketCapacity/PEER_ADMISSION_LIMITS.refillPerSecond*1e3;var PeerMessaging=class _PeerMessaging{static{__name(this,"PeerMessaging")}inbox=null;gate=null;updateSessionRegistryIpcPath=__name(async()=>{},"updateSessionRegistryIpcPath");getSessionId=null;ownsSessionId=null;settleSentMessage=settleSentPeerMessage;reassertSessionRecord=null;drainMirror=drainSendPacer;forgetMirror=forgetSendPacerMessages;refundMirror=refundSendPacerMessage;refundMirrorToken=refundSendPacerToken;receiptListeners=new Set;dropListeners=new Set;unheardDrops=[];dropReceipts=null;submitFn=null;buffered=[];controllerRegistryPath=null;validControllerIds=null;outstanding=[];queuedPeerCount=null;heldListeners=new Set;listedHeld=null;closed=false;constructor(){}static async start(options){if(options.getSessionId&&options.ownsSessionId){throw new Error("PeerMessaging: pass getSessionId or ownsSessionId, not both")}const messaging=new _PeerMessaging;const controllerRegistryPath=options.controllerRegistryPath??getPeerControllerRegistryPath();messaging.controllerRegistryPath=controllerRegistryPath;const dropReceipts=new DropReceiptCoalescer(({frame,reason,droppedMsgIds})=>{if(!frame.from)return;return sendDeliveryStatus(frame.from,{status:"dropped",origMsgId:frame.msgId,from:messaging.inbox?.socketPath,dropReason:reason,droppedMsgIds},frame.replyToken)},options.dropReceiptTrailMs!==void 0?{trailMs:options.dropReceiptTrailMs}:{});messaging.dropReceipts=dropReceipts;const dropNotices=new DropNoticeThrottle(notice=>messaging.emitDropped(notice));const gate=new InboundGate({getApprovalMode:options.getApprovalMode,getPolicySetting:options.getPolicySetting,...options.getHeldExpiryMs!==void 0?{getHeldExpiryMs:options.getHeldExpiryMs}:{},...options.getPolicyScope?{getPolicyScope:options.getPolicyScope}:{},isControllerValid:__name(id=>messaging.validControllerIds?.has(id)??true,"isControllerValid"),...options.admission?{admission:options.admission}:{},getSessionId:options.getSessionId,...options.ownsSessionId?{ownsSessionId:options.ownsSessionId}:{},deliver:__name((frame,origin)=>messaging.deliver(frame,origin),"deliver"),reportDropped:__name((frame,reason,origin)=>dropReceipts.note(frame,origin??{selfSent:false},reason),"reportDropped"),onDropped:__name((frame,origin,reason)=>dropNotices.note(frame,origin,reason),"onDropped"),reportStatus:__name((frame,status)=>{if(!frame.from)return;return sendDeliveryStatus(frame.from,{status,origMsgId:frame.msgId,from:messaging.inbox?.socketPath},frame.replyToken)},"reportStatus"),onHeldChange:__name(held=>messaging.emitHeldChange(held),"onHeldChange")});messaging.gate=gate;messaging.getSessionId=options.getSessionId??null;messaging.ownsSessionId=options.ownsSessionId??null;messaging.settleSentMessage=options.settleSentMessage??settleSentPeerMessage;messaging.reassertSessionRecord=options.reassertSessionRecord??null;messaging.drainMirror=options.drainMirror??drainSendPacer;messaging.forgetMirror=options.forgetMirror??forgetSendPacerMessages;messaging.refundMirror=options.refundMirror??refundSendPacerMessage;messaging.refundMirrorToken=options.refundMirrorToken??refundSendPacerToken;clearInheritedPeerMessagingEnv();const ipcToken=options.ipcToken??randomBytes(32).toString("hex");const childToken=options.childToken??randomBytes(32).toString("hex");const inbox=await startPeerInbox({...options.socketPath!==void 0?{socketPath:options.socketPath}:{},requiredToken:ipcToken,childToken,resolveController:__name(presented=>resolveControllerToken(presented,controllerRegistryPath),"resolveController"),onFrame:__name((frame,auth,controller)=>messaging.onFrame(frame,{selfSent:auth==="child",...controller?{controller}:{}}),"onFrame")});if(!inbox)return null;messaging.inbox=inbox;messaging.updateSessionRegistryIpcPath=options.updateSessionRegistryIpcPath;await messaging.updateSessionRegistryIpcPath(inbox.socketPath,ipcToken);process.env[MESSAGING_SOCKET_ENV]=inbox.socketPath;process.env[MESSAGING_TOKEN_ENV]=childToken;return messaging}get socketPath(){return this.inbox?.socketPath}setSubmitFn(fn){if(this.closed)return;this.withControllerValidity(()=>{this.submitFn=fn;while(this.buffered.length>0){const head=this.buffered[0];if(!head||!this.submit(head.frame,head.origin))break;this.buffered.shift()}})}setQueuedPeerCount(fn){this.queuedPeerCount=fn}getHeld(){return this.withControllerValidity(()=>this.gate?.getHeld()??[])}getHeldExpiryMs(sessionId){return this.gate?.getHeldExpiryMs(sessionId)??null}recordHeldListing(heldEntries){this.listedHeld=heldEntries.map(entry=>({id:entry.frame.msgId,heldAt:entry.heldAt}))}heldSetChangedSinceListing(){const listed=this.listedHeld;if(listed===null)return true;const pinned=new Map(listed.map(entry=>[entry.id,entry.heldAt]));const current=this.getHeld();if(current.some(entry=>pinned.get(entry.frame.msgId)!==entry.heldAt))return true;const liveIds=current.map(entry=>canonicalizeMsgId(entry.frame.msgId));const liveSet=new Set(liveIds);for(const id of pinned.keys()){const departed=canonicalizeMsgId(id);if(liveSet.has(departed))continue;if(liveIds.some(live=>live.startsWith(departed)))return true}return false}decide(msgId,decision){return this.withControllerValidity(()=>this.gate?.decide(msgId,decision)??"gone")}forgetController(id){return this.withControllerValidity(()=>this.gate?.forgetController(id)??0)}reevaluate(reason){return this.withControllerValidity(()=>this.gate?.reevaluate(reason)??0)}onHeldChange(listener){this.heldListeners.add(listener);try{listener(this.getHeld())}catch(error){debugLogger.debug(`held-change listener threw: ${error instanceof Error?error.message:String(error)}`)}return()=>this.heldListeners.delete(listener)}onReceipt(listener){this.receiptListeners.add(listener);return()=>this.receiptListeners.delete(listener)}onDropped(listener){const first=this.dropListeners.size===0;this.dropListeners.add(listener);if(first&&this.unheardDrops.length>0){const unheard=this.unheardDrops.splice(0,this.unheardDrops.length);for(const notice of unheard){try{listener(notice)}catch(error){debugLogger.debug(`drop listener threw on replay: ${error instanceof Error?error.message:String(error)}`)}}}return()=>this.dropListeners.delete(listener)}emitDropped(notice){if(this.dropListeners.size===0){if(this.unheardDrops.length<MAX_UNHEARD_DROP_NOTICES){this.unheardDrops.push(notice)}return}for(const listener of this.dropListeners){try{listener(notice)}catch(error){debugLogger.debug(`drop listener threw: ${error instanceof Error?error.message:String(error)}`)}}}emitReceipt(receipt){for(const listener of this.receiptListeners){try{listener(receipt)}catch(error){debugLogger.debug(`receipt listener threw: ${error instanceof Error?error.message:String(error)}`)}}}async close(){if(this.closed)return;this.closed=true;const shuttingDown=this.gate?.shutdown();await this.inbox?.close();await shuttingDown;await this.settleUnconsumed();clearInheritedPeerMessagingEnv();await this.updateSessionRegistryIpcPath(void 0);await this.dropReceipts?.flush(CLOSE_DROP_FLUSH_BOUND_MS);this.dropReceipts?.dispose()}async settleUnconsumed(){const queued=this.queuedPeerCount?.()??0;const dropped=this.outstanding.slice(Math.max(0,this.outstanding.length-this.buffered.length-queued));const receipts=dropped.filter(frame=>frame.from!==void 0).map(frame=>sendDeliveryStatus(frame.from,{status:"expired",origMsgId:frame.msgId,from:this.inbox?.socketPath},frame.replyToken));await Promise.allSettled(receipts)}onDroppedReceipt(frame){const ids=[frame.origMsgId,...frame.droppedMsgIds??[]];let first;let settledCount=0;const settledByPath=new Map;for(const id of ids){const settled=this.settleSentMessage(id,"dropped");if(!settled)continue;first??=settled;settledCount+=1;const entry=settledByPath.get(settled.ipcPath)??{ids:[],freshestAgeMs:Number.POSITIVE_INFINITY};entry.ids.push(id);entry.freshestAgeMs=Math.min(entry.freshestAgeMs,settled.ageMs);settledByPath.set(settled.ipcPath,entry)}if(!first){debugLogger.debug(`ignoring dropped receipt for ${frame.origMsgId}: unknown message or repeated receipt`);return}debugLogger.debug(`dropped receipt from ${first.address} (${frame.dropReason??"unspecified"}) settled ${settledCount} message(s)`);if(frame.dropReason==="duplicate"){for(const[ipcPath,entry]of settledByPath){for(const id of entry.ids)this.refundMirrorToken(ipcPath,id)}}else{for(const[ipcPath,entry]of settledByPath){this.forgetMirror(ipcPath,entry.ids)}}if(frame.dropReason==="rate-limited"){for(const[ipcPath,entry]of settledByPath){if(entry.freshestAgeMs<=RECEIVER_REFILL_MS)this.drainMirror(ipcPath)}}this.emitReceipt({status:"dropped",address:first.address,origMsgId:frame.origMsgId,previous:"pending",...frame.dropReason?{dropReason:frame.dropReason}:{},dropped:settledCount})}onFrame(frame,origin){if(frame.type==="control"){if(frame.status==="dropped"){this.onDroppedReceipt(frame);return}const settled=this.settleSentMessage(frame.origMsgId,frame.status);if(!settled){debugLogger.debug(`ignoring delivery status ${frame.status} for ${frame.origMsgId}: unknown message or repeated receipt`);return}debugLogger.debug(`delivery status from ${settled.address}: ${settled.previous} -> ${frame.status} for ${frame.origMsgId}`);if(frame.status!=="held"&&frame.status!=="delivered"){if(frame.status==="misaddressed"){this.refundMirror(settled.ipcPath,frame.origMsgId)}else{this.forgetMirror(settled.ipcPath,[frame.origMsgId])}}this.emitReceipt({status:frame.status,address:settled.address,origMsgId:frame.origMsgId,previous:settled.previous});return}const ownSessionId=this.getSessionId?.();const ownsSessionId=this.ownsSessionId;const misaddressed=ownsSessionId?frame.toSessionId===void 0||!ownsSessionId(frame.toSessionId):frame.toSessionId!==void 0&&ownSessionId!==void 0&&frame.toSessionId!==ownSessionId;if(misaddressed){debugLogger.debug(`refusing peer message ${frame.msgId}: addressed to session ${frame.toSessionId??"(unspecified)"}, this process does not hold it`);if(frame.from){void sendDeliveryStatus(frame.from,{status:"misaddressed",origMsgId:frame.msgId,from:this.inbox?.socketPath},frame.replyToken)}void this.reassertSessionRecord?.().catch(error=>{debugLogger.debug(`re-asserting the session record failed: ${error instanceof Error?error.message:String(error)}`)});return}this.gate?.admit(frame,origin)}deliver(frame,origin){if(!this.submitFn){if(this.buffered.length>=MAX_ACCEPTED_BACKLOG){throw new Error("accepted-message backlog is full")}this.buffered.push({frame,origin});this.trackOutstanding(frame);return}if(this.buffered.length>0){this.withControllerValidity(()=>{while(this.buffered.length>0){const head=this.buffered[0];if(!head||!this.submit(head.frame,head.origin)){throw new Error("accepted-message backlog is full")}this.buffered.shift()}})}if(!this.submit(frame,origin)){throw new Error("accepted-message backlog is full")}this.trackOutstanding(frame)}trackOutstanding(frame){this.outstanding.push(frame);while(this.outstanding.length>2*MAX_ACCEPTED_BACKLOG){this.outstanding.shift()}}withControllerValidity(action){if(this.controllerRegistryPath===null||this.validControllerIds){return action()}this.validControllerIds=new Set(readPeerControllerRegistrySync(this.controllerRegistryPath).controllers.map(controller=>controller.id));for(const delivery of this.buffered){const controller=delivery.origin.controller;if(controller&&!this.validControllerIds.has(controller.id)){delete delivery.origin.controller}}try{return action()}finally{this.validControllerIds=null}}submit(frame,origin){const from=frame.from??(origin.controller?"controller":origin.selfSent?"own process":"unknown session");const attribution={selfSent:origin.selfSent,...origin.controller?{controller:origin.controller}:{}};return this.submitFn?.(formatPeerEnvelope({from,...frame.fromName!==void 0?{fromName:frame.fromName}:{},content:frame.message.content,...attribution}),formatPeerDisplay({from,...frame.fromName!==void 0?{fromName:frame.fromName}:{},content:frame.message.content,...attribution}),{msgId:frame.msgId,admissionKey:peerSenderKey(frame,origin),...frame.from!==void 0?{from:frame.from}:{},...frame.replyToken!==void 0?{replyToken:frame.replyToken}:{},...frame.toSessionId!==void 0?{toSessionId:frame.toSessionId}:{}})??false}drainQueuedFrame(delivery){const ownSessionId=this.getSessionId?.();if(delivery?.toSessionId===void 0||ownSessionId===void 0||delivery.toSessionId===ownSessionId){return true}debugLogger.debug(`dropping queued peer message ${delivery.msgId}: addressed to session ${delivery.toSessionId}, this is ${ownSessionId}`);if(delivery.from){void sendDeliveryStatus(delivery.from,{status:"misaddressed",origMsgId:delivery.msgId,from:this.inbox?.socketPath},delivery.replyToken)}if(delivery.admissionKey!==void 0){this.gate?.forgetAdmittedMessage(delivery.admissionKey,delivery.msgId)}return false}emitHeldChange(held){for(const listener of this.heldListeners){try{listener(held)}catch(error){debugLogger.debug(`held-change listener threw: ${error instanceof Error?error.message:String(error)}`)}}}};init_esbuild_shims();function classifyApiError(error){const status=error.status;const message=error.message?.toLowerCase()??"";if(status===429||message.includes("rate limit")){return"rate_limit"}if(status===401||message.includes("unauthorized")){return"authentication_failed"}if(status===402||status===403||message.includes("billing")||message.includes("quota")){return"billing_error"}if(status===400||message.includes("invalid")){return"invalid_request"}if(status!==void 0&&status>=500){return"server_error"}if(message.includes("max_tokens")||message.includes("token limit")){return"max_output_tokens"}return"unknown"}__name(classifyApiError,"classifyApiError");export{classifyApiError,MAX_ACCEPTED_BACKLOG,PeerMessaging};
3
+ import{DropNoticeThrottle,DropReceiptCoalescer,getPeerControllerRegistryPath,readPeerControllerRegistrySync,resolveControllerToken,startPeerInbox}from"./chunk-RV54BGL2.js";import{InboundGate,MAX_HELD_MESSAGES,PEER_ADMISSION_LIMITS,canonicalizeMsgId,drainSendPacer,forgetSendPacerMessages,peerSenderKey,refundSendPacerMessage,refundSendPacerToken,sendDeliveryStatus,settleSentPeerMessage}from"./chunk-LJGQNGCO.js";import{formatPeerDisplay,formatPeerEnvelope}from"./chunk-Y77BXKWA.js";import{MESSAGING_SOCKET_ENV,MESSAGING_TOKEN_ENV,clearInheritedPeerMessagingEnv}from"./chunk-NPAX2UFU.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import{randomBytes}from"node:crypto";var debugLogger=createDebugLogger("PEER_MESSAGING");var MAX_ACCEPTED_BACKLOG=MAX_HELD_MESSAGES;var CLOSE_DROP_FLUSH_BOUND_MS=1e3;var MAX_UNHEARD_DROP_NOTICES=20;var RECEIVER_REFILL_MS=PEER_ADMISSION_LIMITS.bucketCapacity/PEER_ADMISSION_LIMITS.refillPerSecond*1e3;var PeerMessaging=class _PeerMessaging{static{__name(this,"PeerMessaging")}inbox=null;gate=null;updateSessionRegistryIpcPath=__name(async()=>{},"updateSessionRegistryIpcPath");getSessionId=null;ownsSessionId=null;settleSentMessage=settleSentPeerMessage;reassertSessionRecord=null;drainMirror=drainSendPacer;forgetMirror=forgetSendPacerMessages;refundMirror=refundSendPacerMessage;refundMirrorToken=refundSendPacerToken;receiptListeners=new Set;dropListeners=new Set;unheardDrops=[];dropReceipts=null;submitFn=null;buffered=[];controllerRegistryPath=null;validControllerIds=null;outstanding=[];queuedPeerCount=null;heldListeners=new Set;listedHeld=null;closed=false;constructor(){}static async start(options){if(options.getSessionId&&options.ownsSessionId){throw new Error("PeerMessaging: pass getSessionId or ownsSessionId, not both")}const messaging=new _PeerMessaging;const controllerRegistryPath=options.controllerRegistryPath??getPeerControllerRegistryPath();messaging.controllerRegistryPath=controllerRegistryPath;const dropReceipts=new DropReceiptCoalescer(({frame,reason,droppedMsgIds})=>{if(!frame.from)return;return sendDeliveryStatus(frame.from,{status:"dropped",origMsgId:frame.msgId,from:messaging.inbox?.socketPath,dropReason:reason,droppedMsgIds},frame.replyToken)},options.dropReceiptTrailMs!==void 0?{trailMs:options.dropReceiptTrailMs}:{});messaging.dropReceipts=dropReceipts;const dropNotices=new DropNoticeThrottle(notice=>messaging.emitDropped(notice));const gate=new InboundGate({getApprovalMode:options.getApprovalMode,getPolicySetting:options.getPolicySetting,...options.getHeldExpiryMs!==void 0?{getHeldExpiryMs:options.getHeldExpiryMs}:{},...options.getPolicyScope?{getPolicyScope:options.getPolicyScope}:{},isControllerValid:__name(id=>messaging.validControllerIds?.has(id)??true,"isControllerValid"),...options.admission?{admission:options.admission}:{},getSessionId:options.getSessionId,...options.ownsSessionId?{ownsSessionId:options.ownsSessionId}:{},deliver:__name((frame,origin)=>messaging.deliver(frame,origin),"deliver"),reportDropped:__name((frame,reason,origin)=>dropReceipts.note(frame,origin??{selfSent:false},reason),"reportDropped"),onDropped:__name((frame,origin,reason)=>dropNotices.note(frame,origin,reason),"onDropped"),reportStatus:__name((frame,status)=>{if(!frame.from)return;return sendDeliveryStatus(frame.from,{status,origMsgId:frame.msgId,from:messaging.inbox?.socketPath},frame.replyToken)},"reportStatus"),onHeldChange:__name(held=>messaging.emitHeldChange(held),"onHeldChange")});messaging.gate=gate;messaging.getSessionId=options.getSessionId??null;messaging.ownsSessionId=options.ownsSessionId??null;messaging.settleSentMessage=options.settleSentMessage??settleSentPeerMessage;messaging.reassertSessionRecord=options.reassertSessionRecord??null;messaging.drainMirror=options.drainMirror??drainSendPacer;messaging.forgetMirror=options.forgetMirror??forgetSendPacerMessages;messaging.refundMirror=options.refundMirror??refundSendPacerMessage;messaging.refundMirrorToken=options.refundMirrorToken??refundSendPacerToken;clearInheritedPeerMessagingEnv();const ipcToken=options.ipcToken??randomBytes(32).toString("hex");const childToken=options.childToken??randomBytes(32).toString("hex");const inbox=await startPeerInbox({...options.socketPath!==void 0?{socketPath:options.socketPath}:{},requiredToken:ipcToken,childToken,resolveController:__name(presented=>resolveControllerToken(presented,controllerRegistryPath),"resolveController"),onFrame:__name((frame,auth,controller)=>messaging.onFrame(frame,{selfSent:auth==="child",...controller?{controller}:{}}),"onFrame")});if(!inbox)return null;messaging.inbox=inbox;messaging.updateSessionRegistryIpcPath=options.updateSessionRegistryIpcPath;await messaging.updateSessionRegistryIpcPath(inbox.socketPath,ipcToken);process.env[MESSAGING_SOCKET_ENV]=inbox.socketPath;process.env[MESSAGING_TOKEN_ENV]=childToken;return messaging}get socketPath(){return this.inbox?.socketPath}setSubmitFn(fn){if(this.closed)return;this.withControllerValidity(()=>{this.submitFn=fn;while(this.buffered.length>0){const head=this.buffered[0];if(!head||!this.submit(head.frame,head.origin))break;this.buffered.shift()}})}setQueuedPeerCount(fn){this.queuedPeerCount=fn}getHeld(){return this.withControllerValidity(()=>this.gate?.getHeld()??[])}getHeldExpiryMs(sessionId){return this.gate?.getHeldExpiryMs(sessionId)??null}recordHeldListing(heldEntries){this.listedHeld=heldEntries.map(entry=>({id:entry.frame.msgId,heldAt:entry.heldAt}))}heldSetChangedSinceListing(){const listed=this.listedHeld;if(listed===null)return true;const pinned=new Map(listed.map(entry=>[entry.id,entry.heldAt]));const current=this.getHeld();if(current.some(entry=>pinned.get(entry.frame.msgId)!==entry.heldAt))return true;const liveIds=current.map(entry=>canonicalizeMsgId(entry.frame.msgId));const liveSet=new Set(liveIds);for(const id of pinned.keys()){const departed=canonicalizeMsgId(id);if(liveSet.has(departed))continue;if(liveIds.some(live=>live.startsWith(departed)))return true}return false}decide(msgId,decision){return this.withControllerValidity(()=>this.gate?.decide(msgId,decision)??"gone")}forgetController(id){return this.withControllerValidity(()=>this.gate?.forgetController(id)??0)}reevaluate(reason){return this.withControllerValidity(()=>this.gate?.reevaluate(reason)??0)}onHeldChange(listener){this.heldListeners.add(listener);try{listener(this.getHeld())}catch(error){debugLogger.debug(`held-change listener threw: ${error instanceof Error?error.message:String(error)}`)}return()=>this.heldListeners.delete(listener)}onReceipt(listener){this.receiptListeners.add(listener);return()=>this.receiptListeners.delete(listener)}onDropped(listener){const first=this.dropListeners.size===0;this.dropListeners.add(listener);if(first&&this.unheardDrops.length>0){const unheard=this.unheardDrops.splice(0,this.unheardDrops.length);for(const notice of unheard){try{listener(notice)}catch(error){debugLogger.debug(`drop listener threw on replay: ${error instanceof Error?error.message:String(error)}`)}}}return()=>this.dropListeners.delete(listener)}emitDropped(notice){if(this.dropListeners.size===0){if(this.unheardDrops.length<MAX_UNHEARD_DROP_NOTICES){this.unheardDrops.push(notice)}return}for(const listener of this.dropListeners){try{listener(notice)}catch(error){debugLogger.debug(`drop listener threw: ${error instanceof Error?error.message:String(error)}`)}}}emitReceipt(receipt){for(const listener of this.receiptListeners){try{listener(receipt)}catch(error){debugLogger.debug(`receipt listener threw: ${error instanceof Error?error.message:String(error)}`)}}}async close(){if(this.closed)return;this.closed=true;const shuttingDown=this.gate?.shutdown();await this.inbox?.close();await shuttingDown;await this.settleUnconsumed();clearInheritedPeerMessagingEnv();await this.updateSessionRegistryIpcPath(void 0);await this.dropReceipts?.flush(CLOSE_DROP_FLUSH_BOUND_MS);this.dropReceipts?.dispose()}async settleUnconsumed(){const queued=this.queuedPeerCount?.()??0;const dropped=this.outstanding.slice(Math.max(0,this.outstanding.length-this.buffered.length-queued));const receipts=dropped.filter(frame=>frame.from!==void 0).map(frame=>sendDeliveryStatus(frame.from,{status:"expired",origMsgId:frame.msgId,from:this.inbox?.socketPath},frame.replyToken));await Promise.allSettled(receipts)}onDroppedReceipt(frame){const ids=[frame.origMsgId,...frame.droppedMsgIds??[]];let first;let settledCount=0;const settledByPath=new Map;for(const id of ids){const settled=this.settleSentMessage(id,"dropped");if(!settled)continue;first??=settled;settledCount+=1;const entry=settledByPath.get(settled.ipcPath)??{ids:[],freshestAgeMs:Number.POSITIVE_INFINITY};entry.ids.push(id);entry.freshestAgeMs=Math.min(entry.freshestAgeMs,settled.ageMs);settledByPath.set(settled.ipcPath,entry)}if(!first){debugLogger.debug(`ignoring dropped receipt for ${frame.origMsgId}: unknown message or repeated receipt`);return}debugLogger.debug(`dropped receipt from ${first.address} (${frame.dropReason??"unspecified"}) settled ${settledCount} message(s)`);if(frame.dropReason==="duplicate"){for(const[ipcPath,entry]of settledByPath){for(const id of entry.ids)this.refundMirrorToken(ipcPath,id)}}else{for(const[ipcPath,entry]of settledByPath){this.forgetMirror(ipcPath,entry.ids)}}if(frame.dropReason==="rate-limited"){for(const[ipcPath,entry]of settledByPath){if(entry.freshestAgeMs<=RECEIVER_REFILL_MS)this.drainMirror(ipcPath)}}this.emitReceipt({status:"dropped",address:first.address,origMsgId:frame.origMsgId,previous:"pending",...frame.dropReason?{dropReason:frame.dropReason}:{},dropped:settledCount})}onFrame(frame,origin){if(frame.type==="control"){if(frame.status==="dropped"){this.onDroppedReceipt(frame);return}const settled=this.settleSentMessage(frame.origMsgId,frame.status);if(!settled){debugLogger.debug(`ignoring delivery status ${frame.status} for ${frame.origMsgId}: unknown message or repeated receipt`);return}debugLogger.debug(`delivery status from ${settled.address}: ${settled.previous} -> ${frame.status} for ${frame.origMsgId}`);if(frame.status!=="held"&&frame.status!=="delivered"){if(frame.status==="misaddressed"){this.refundMirror(settled.ipcPath,frame.origMsgId)}else{this.forgetMirror(settled.ipcPath,[frame.origMsgId])}}this.emitReceipt({status:frame.status,address:settled.address,origMsgId:frame.origMsgId,previous:settled.previous});return}const ownSessionId=this.getSessionId?.();const ownsSessionId=this.ownsSessionId;const misaddressed=ownsSessionId?frame.toSessionId===void 0||!ownsSessionId(frame.toSessionId):frame.toSessionId!==void 0&&ownSessionId!==void 0&&frame.toSessionId!==ownSessionId;if(misaddressed){debugLogger.debug(`refusing peer message ${frame.msgId}: addressed to session ${frame.toSessionId??"(unspecified)"}, this process does not hold it`);if(frame.from){void sendDeliveryStatus(frame.from,{status:"misaddressed",origMsgId:frame.msgId,from:this.inbox?.socketPath},frame.replyToken)}void this.reassertSessionRecord?.().catch(error=>{debugLogger.debug(`re-asserting the session record failed: ${error instanceof Error?error.message:String(error)}`)});return}this.gate?.admit(frame,origin)}deliver(frame,origin){if(!this.submitFn){if(this.buffered.length>=MAX_ACCEPTED_BACKLOG){throw new Error("accepted-message backlog is full")}this.buffered.push({frame,origin});this.trackOutstanding(frame);return}if(this.buffered.length>0){this.withControllerValidity(()=>{while(this.buffered.length>0){const head=this.buffered[0];if(!head||!this.submit(head.frame,head.origin)){throw new Error("accepted-message backlog is full")}this.buffered.shift()}})}if(!this.submit(frame,origin)){throw new Error("accepted-message backlog is full")}this.trackOutstanding(frame)}trackOutstanding(frame){this.outstanding.push(frame);while(this.outstanding.length>2*MAX_ACCEPTED_BACKLOG){this.outstanding.shift()}}withControllerValidity(action){if(this.controllerRegistryPath===null||this.validControllerIds){return action()}this.validControllerIds=new Set(readPeerControllerRegistrySync(this.controllerRegistryPath).controllers.map(controller=>controller.id));for(const delivery of this.buffered){const controller=delivery.origin.controller;if(controller&&!this.validControllerIds.has(controller.id)){delete delivery.origin.controller}}try{return action()}finally{this.validControllerIds=null}}submit(frame,origin){const from=frame.from??(origin.controller?"controller":origin.selfSent?"own process":"unknown session");const attribution={selfSent:origin.selfSent,...origin.controller?{controller:origin.controller}:{}};return this.submitFn?.(formatPeerEnvelope({from,...frame.fromName!==void 0?{fromName:frame.fromName}:{},content:frame.message.content,...attribution}),formatPeerDisplay({from,...frame.fromName!==void 0?{fromName:frame.fromName}:{},content:frame.message.content,...attribution}),{msgId:frame.msgId,admissionKey:peerSenderKey(frame,origin),...frame.from!==void 0?{from:frame.from}:{},...frame.replyToken!==void 0?{replyToken:frame.replyToken}:{},...frame.toSessionId!==void 0?{toSessionId:frame.toSessionId}:{}})??false}drainQueuedFrame(delivery){const ownSessionId=this.getSessionId?.();if(delivery?.toSessionId===void 0||ownSessionId===void 0||delivery.toSessionId===ownSessionId){return true}debugLogger.debug(`dropping queued peer message ${delivery.msgId}: addressed to session ${delivery.toSessionId}, this is ${ownSessionId}`);if(delivery.from){void sendDeliveryStatus(delivery.from,{status:"misaddressed",origMsgId:delivery.msgId,from:this.inbox?.socketPath},delivery.replyToken)}if(delivery.admissionKey!==void 0){this.gate?.forgetAdmittedMessage(delivery.admissionKey,delivery.msgId)}return false}emitHeldChange(held){for(const listener of this.heldListeners){try{listener(held)}catch(error){debugLogger.debug(`held-change listener threw: ${error instanceof Error?error.message:String(error)}`)}}}};init_esbuild_shims();function classifyApiError(error){const status=error.status;const message=error.message?.toLowerCase()??"";if(status===429||message.includes("rate limit")){return"rate_limit"}if(status===401||message.includes("unauthorized")){return"authentication_failed"}if(status===402||status===403||message.includes("billing")||message.includes("quota")){return"billing_error"}if(status===400||message.includes("invalid")){return"invalid_request"}if(status!==void 0&&status>=500){return"server_error"}if(message.includes("max_tokens")||message.includes("token limit")){return"max_output_tokens"}return"unknown"}__name(classifyApiError,"classifyApiError");export{classifyApiError,MAX_ACCEPTED_BACKLOG,PeerMessaging};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2026 Qwen
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{buildManagedAutoMemoryPrompt,createMemoryScopedAgentConfig,deriveConfig,ensureAutoMemoryScaffold,ensureUserAutoMemoryScaffold,isAllowedMemoryPath,readAutoMemoryIndex,readUserAutoMemoryIndex,rebuildManagedAutoMemoryIndex,rebuildUserAutoMemoryIndex,renderWriterKeywordVocabularySnapshot,runForkedAgent}from"./chunk-GG7RNHZW.js";import{scanAutoMemoryTopicDocuments,scanUserAutoMemoryTopicDocuments}from"./chunk-GNQGC2DJ.js";import{getAutoMemoryRoot,getUserAutoMemoryRoot}from"./chunk-37KFLBKZ.js";import{ToolNames}from"./chunk-2UNFJQ2D.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import path from"node:path";var debugLogger=createDebugLogger("AUTO_MEMORY_REMEMBER");function buildManagedRememberPrompt(fact,projectRoot,options={}){const trimmed=fact.trim();const projectDir=projectRoot?getAutoMemoryRoot(projectRoot):void 0;const userDir=getUserAutoMemoryRoot();const dirHint=projectDir===void 0?"":options.scope==="project"?` Store this memory only in PROJECT memory at \`${projectDir}\`. This explicit project target overrides the memory type's default destination; do not read or write USER memory at \`${userDir}\`.`:options.scope==="user"?` Store this memory only in USER memory at \`${userDir}\`. This explicit user target overrides the memory type's default destination; do not read or write PROJECT memory at \`${projectDir}\`.`:` Choose the destination directory by the type's \`<scope>\`: USER memory at \`${userDir}\` for cross-project facts, PROJECT memory at \`${projectDir}\` for this-project-only facts.`;const content=options.wrapUserContent?`<user-content>
3
+ import{buildManagedAutoMemoryPrompt,createMemoryScopedAgentConfig,deriveConfig,ensureAutoMemoryScaffold,ensureUserAutoMemoryScaffold,isAllowedMemoryPath,readAutoMemoryIndex,readUserAutoMemoryIndex,rebuildManagedAutoMemoryIndex,rebuildUserAutoMemoryIndex,renderWriterKeywordVocabularySnapshot,runForkedAgent}from"./chunk-IFAUFERF.js";import{scanAutoMemoryTopicDocuments,scanUserAutoMemoryTopicDocuments}from"./chunk-GNQGC2DJ.js";import{getAutoMemoryRoot,getUserAutoMemoryRoot}from"./chunk-37KFLBKZ.js";import{ToolNames}from"./chunk-2UNFJQ2D.js";import{createDebugLogger}from"./chunk-JAUJI56S.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();import path from"node:path";var debugLogger=createDebugLogger("AUTO_MEMORY_REMEMBER");function buildManagedRememberPrompt(fact,projectRoot,options={}){const trimmed=fact.trim();const projectDir=projectRoot?getAutoMemoryRoot(projectRoot):void 0;const userDir=getUserAutoMemoryRoot();const dirHint=projectDir===void 0?"":options.scope==="project"?` Store this memory only in PROJECT memory at \`${projectDir}\`. This explicit project target overrides the memory type's default destination; do not read or write USER memory at \`${userDir}\`.`:options.scope==="user"?` Store this memory only in USER memory at \`${userDir}\`. This explicit user target overrides the memory type's default destination; do not read or write PROJECT memory at \`${projectDir}\`.`:` Choose the destination directory by the type's \`<scope>\`: USER memory at \`${userDir}\` for cross-project facts, PROJECT memory at \`${projectDir}\` for this-project-only facts.`;const content=options.wrapUserContent?`<user-content>
4
4
  ${trimmed}
5
5
  </user-content>`:trimmed;return`Please save the following to your memory system.${dirHint} Choose the most appropriate memory type (user, feedback, project, or reference) based on the content:
6
6