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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (274) hide show
  1. package/chunks/{MaxSizedBox-CF4NN4Y7.js → MaxSizedBox-CGJP7S5S.js} +1 -1
  2. package/chunks/{StandaloneSessionPicker-Q23KTB6U.js → StandaloneSessionPicker-H6NONKPP.js} +1 -1
  3. package/chunks/{acp-subagent-executor-LXOLDTFY.js → acp-subagent-executor-7OCKCTA5.js} +1 -1
  4. package/chunks/{acpAgent-QRKZVQAG.js → acpAgent-VCKTBLFO.js} +3 -3
  5. package/chunks/{advisor-VZZJU7BR.js → advisor-UQJ45FLG.js} +1 -1
  6. package/chunks/{agent-LP66VBC4.js → agent-KMSCVRSG.js} +1 -1
  7. package/chunks/{agent-headless-W5P4KPX4.js → agent-headless-3FWQ5QNO.js} +1 -1
  8. package/chunks/{agent-host-client-OW4HBXRL.js → agent-host-client-PXIIFCCS.js} +1 -1
  9. package/chunks/{agent-host-connections-D7IC6WWL.js → agent-host-connections-QUYGQNJX.js} +1 -1
  10. package/chunks/{anthropicContentGenerator-6I25Q3Y6.js → anthropicContentGenerator-MDETV5LU.js} +1 -1
  11. package/chunks/{batch-7E5KJ625.js → batch-RQO2HWFV.js} +1 -1
  12. package/chunks/{bridge-BITC2AVN.js → bridge-OA3GEU2I.js} +1 -1
  13. package/chunks/{channel-settings-store-VAVG6ONF.js → channel-settings-store-YN23NP2H.js} +1 -1
  14. package/chunks/{chunk-4NCTKE4Z.js → chunk-2PQ5ZRTI.js} +1 -1
  15. package/chunks/{chunk-OJHTHXBC.js → chunk-32UFT5HU.js} +1 -1
  16. package/chunks/{chunk-2HJZ3OYW.js → chunk-3C34EMBZ.js} +1 -1
  17. package/chunks/{chunk-UXFLNZNB.js → chunk-3FPPMGVC.js} +1 -1
  18. package/chunks/{chunk-74YXI5IJ.js → chunk-445NIH5T.js} +1 -1
  19. package/chunks/{chunk-MXXYBMBZ.js → chunk-45EKBDFD.js} +1 -1
  20. package/chunks/{chunk-JV5FCFG4.js → chunk-4WFWZWR3.js} +1 -1
  21. package/chunks/{chunk-AAOAX46J.js → chunk-56NX3ASC.js} +1 -1
  22. package/chunks/{chunk-IBS4PHD2.js → chunk-5FY6TL3Z.js} +1 -1
  23. package/chunks/{chunk-UGI3XPRM.js → chunk-5GJPVNHI.js} +1 -1
  24. package/chunks/{chunk-7BZGY7AH.js → chunk-5XAVUYY6.js} +6 -6
  25. package/chunks/{chunk-V3WNU4F5.js → chunk-655XEN5H.js} +1 -1
  26. package/chunks/{chunk-APX7ODYT.js → chunk-6PHAGUA6.js} +1 -1
  27. package/chunks/{chunk-CD6C4OHZ.js → chunk-7YX6LW5H.js} +1 -1
  28. package/chunks/{chunk-C2NFZSGI.js → chunk-AAVRYR5T.js} +1 -1
  29. package/chunks/{chunk-EO35BRIG.js → chunk-ANUAITTH.js} +1 -1
  30. package/chunks/{chunk-CNQ6AOFN.js → chunk-AZ5GFEKG.js} +1 -1
  31. package/chunks/{chunk-KAEW65QP.js → chunk-B5XDGUAK.js} +1 -1
  32. package/chunks/{chunk-X6QHNKUW.js → chunk-BCNBZOGV.js} +1 -1
  33. package/chunks/{chunk-W5DIWPQB.js → chunk-BDXWLZJD.js} +1 -1
  34. package/chunks/{chunk-ZASVUARY.js → chunk-BPX4A433.js} +1 -1
  35. package/chunks/{chunk-CDSI44GJ.js → chunk-BUI6W6CU.js} +1 -1
  36. package/chunks/{chunk-ZEYCGUHI.js → chunk-BVARURDD.js} +1 -1
  37. package/chunks/{chunk-PZ5UPKIG.js → chunk-BW5CHWEJ.js} +2 -2
  38. package/chunks/{chunk-7TUP75C2.js → chunk-C4DSH4A3.js} +1 -1
  39. package/chunks/{chunk-R4KMBENY.js → chunk-CCBWBPJL.js} +1 -1
  40. package/chunks/{chunk-TU6DWKVI.js → chunk-CKJ3OUIV.js} +2 -2
  41. package/chunks/{chunk-SG5P4CK4.js → chunk-CRZ7QRFB.js} +1 -1
  42. package/chunks/{chunk-UYFL7K4Z.js → chunk-CTEBIP2S.js} +1 -1
  43. package/chunks/{chunk-WSIDVWGO.js → chunk-DBOWUORN.js} +1 -1
  44. package/chunks/{chunk-NAHKSVYI.js → chunk-DPBXGGQX.js} +1 -1
  45. package/chunks/{chunk-BMOJDKDZ.js → chunk-DSSSLNXD.js} +3 -3
  46. package/chunks/{chunk-FP2RLPWJ.js → chunk-EKGFFEH4.js} +1 -1
  47. package/chunks/{chunk-L7W3J427.js → chunk-EMEQR2LX.js} +1 -1
  48. package/chunks/{chunk-YRYMLJAC.js → chunk-ENUYA7BO.js} +1 -1
  49. package/chunks/{chunk-4CWBH6LP.js → chunk-EORORGZC.js} +1 -1
  50. package/chunks/{chunk-RBH3BOVF.js → chunk-EUK64V6Z.js} +1 -1
  51. package/chunks/{chunk-AII4DN7M.js → chunk-FBV4LUUL.js} +1 -1
  52. package/chunks/{chunk-YVEPPENZ.js → chunk-FFLFTXO7.js} +1 -1
  53. package/chunks/{chunk-2HSFO66N.js → chunk-FHXH3GSI.js} +1 -1
  54. package/chunks/{chunk-RH6PMH32.js → chunk-FVBDVZD7.js} +1 -1
  55. package/chunks/{chunk-Y2HLDUZG.js → chunk-I2D2ZUKF.js} +1 -1
  56. package/chunks/{chunk-6PUZWUMQ.js → chunk-I3FZ733S.js} +1 -1
  57. package/chunks/{chunk-GG7RNHZW.js → chunk-IFAUFERF.js} +5 -5
  58. package/chunks/{chunk-JQ7BCB3L.js → chunk-IYFUH3JB.js} +1 -1
  59. package/chunks/{chunk-VAMQAYF3.js → chunk-JB5I5QAD.js} +1 -1
  60. package/chunks/{chunk-Z3UZTCKY.js → chunk-JD3QDS7D.js} +1 -1
  61. package/chunks/{chunk-TFVPY43T.js → chunk-JG2UNQOW.js} +1 -1
  62. package/chunks/{chunk-E4MRBL4O.js → chunk-JSXHTTFE.js} +1 -1
  63. package/chunks/{chunk-QTYA6TES.js → chunk-LJLS3MDJ.js} +1 -1
  64. package/chunks/{chunk-RZISIEQL.js → chunk-MEIW5WVJ.js} +1 -1
  65. package/chunks/{chunk-ZD4U3GR4.js → chunk-MGL36H3B.js} +1 -1
  66. package/chunks/{chunk-HXA3X4PB.js → chunk-MJUFVFH3.js} +1 -1
  67. package/chunks/{chunk-SYIDPXVT.js → chunk-MSR6LYHS.js} +1 -1
  68. package/chunks/{chunk-4MJ67O5W.js → chunk-MTXJRB7G.js} +2 -2
  69. package/chunks/{chunk-F5P3BWS7.js → chunk-MXFBSMIM.js} +1 -1
  70. package/chunks/{chunk-W6TNBCKX.js → chunk-MYHJ4WUH.js} +1 -1
  71. package/chunks/{chunk-CWU5NJOB.js → chunk-NHXKNS7F.js} +1 -1
  72. package/chunks/{chunk-6OIJIF6G.js → chunk-NT74NPQT.js} +1 -1
  73. package/chunks/{chunk-O47FCWNF.js → chunk-NWXW4UNC.js} +1 -1
  74. package/chunks/{chunk-JASL4RZR.js → chunk-O77LM4EW.js} +1 -1
  75. package/chunks/{chunk-ZDNTENP2.js → chunk-OB7T2MDO.js} +1 -1
  76. package/chunks/{chunk-L7WFW57T.js → chunk-PODFLAH7.js} +1 -1
  77. package/chunks/{chunk-R3ZMQ7WR.js → chunk-Q2G675WT.js} +1 -1
  78. package/chunks/{chunk-H3QROVUO.js → chunk-QT27SK62.js} +1 -1
  79. package/chunks/{chunk-UELAXFT7.js → chunk-QZPNBV4F.js} +1 -1
  80. package/chunks/{chunk-B3L4LODR.js → chunk-RV54BGL2.js} +1 -1
  81. package/chunks/{chunk-KLXL3FSI.js → chunk-SFETIBPP.js} +1 -1
  82. package/chunks/{chunk-F3YGAXZ5.js → chunk-SGKINIQB.js} +1 -1
  83. package/chunks/{chunk-MBPT3YYO.js → chunk-SHJNP7OV.js} +1 -1
  84. package/chunks/{chunk-U3YSYIQE.js → chunk-SPFRORFN.js} +1 -1
  85. package/chunks/{chunk-S3B4TZVJ.js → chunk-SPLINFM7.js} +1 -1
  86. package/chunks/{chunk-ORIS5AVH.js → chunk-SYO5FPHL.js} +1 -1
  87. package/chunks/{chunk-AGHGPOH6.js → chunk-TEE4MM5S.js} +1 -1
  88. package/chunks/{chunk-WHF3HYZI.js → chunk-TPZTO4K3.js} +1 -1
  89. package/chunks/{chunk-KJO757RN.js → chunk-UY2CSL5W.js} +1 -1
  90. package/chunks/{chunk-VCTZRPKP.js → chunk-W7QYXFWW.js} +1 -1
  91. package/chunks/{chunk-T3ECMT6I.js → chunk-WQOZJ6V7.js} +2 -2
  92. package/chunks/{chunk-INEI2ZW2.js → chunk-WZK7RC36.js} +1 -1
  93. package/chunks/{chunk-Y5JLH3SN.js → chunk-X22435IN.js} +4 -4
  94. package/chunks/{chunk-WHNAY3QQ.js → chunk-X2KF6AUQ.js} +1 -1
  95. package/chunks/{chunk-MUEIZGTI.js → chunk-YHPHQX6M.js} +1 -1
  96. package/chunks/{chunk-5OOO3YIH.js → chunk-YL7QMYOX.js} +1 -1
  97. package/chunks/{chunk-43E3XC2W.js → chunk-YQEOEO5V.js} +1 -1
  98. package/chunks/{chunk-624P32LD.js → chunk-YZ374XTK.js} +1 -1
  99. package/chunks/{codex-subagent-executor-2MPLWNLD.js → codex-subagent-executor-MC3QB2AN.js} +1 -1
  100. package/chunks/{config-utils-MJEEBLQW.js → config-utils-FYT7PUIC.js} +1 -1
  101. package/chunks/{contextCommand-BP566QVE.js → contextCommand-DXMSMSR7.js} +1 -1
  102. package/chunks/{core-runtime-BOAIFYAZ.js → core-runtime-ZLB6QZ3Z.js} +1 -1
  103. package/chunks/{create-sub-session-HJVK7AXV.js → create-sub-session-YUI3G5AF.js} +1 -1
  104. package/chunks/{daemon-git-worktree-guard-KA2Y6FHL.js → daemon-git-worktree-guard-5PYZMC6T.js} +1 -1
  105. package/chunks/{daemon-status-provider-JGR5JT2T.js → daemon-status-provider-GC567FVE.js} +1 -1
  106. package/chunks/{daemon-trust-policy-EP4DHXOW.js → daemon-trust-policy-LLD2UMPF.js} +1 -1
  107. package/chunks/{daemon-trust-policy-monitor-W3VZRKOK.js → daemon-trust-policy-monitor-MRMB2CRJ.js} +1 -1
  108. package/chunks/{deferred-core-runtime-Q3JH7XDL.js → deferred-core-runtime-4HLTINJ6.js} +1 -1
  109. package/chunks/{edit-S7DCBMAL.js → edit-CZ6FEXDU.js} +1 -1
  110. package/chunks/{enterPlanMode-UX7B6KWX.js → enterPlanMode-O3CJ3I2J.js} +1 -1
  111. package/chunks/{environment-ZBW6HDG3.js → environment-OJWH4FYL.js} +1 -1
  112. package/chunks/{errors-7ZRLUHEB.js → errors-NWKSQVL3.js} +1 -1
  113. package/chunks/{execution-tool-R244Q3GW.js → execution-tool-7UCADALN.js} +1 -1
  114. package/chunks/{execution-worker-JR44JTC4.js → execution-worker-LWHQMPBV.js} +1 -1
  115. package/chunks/{exitPlanMode-2PTTZXGO.js → exitPlanMode-JDM6ZZWI.js} +1 -1
  116. package/chunks/{fast-path-NQQ42XUR.js → fast-path-4WHPMNMD.js} +1 -1
  117. package/chunks/{glob-4JP6RQNK.js → glob-LAU4YJ6J.js} +1 -1
  118. package/chunks/{goal-tools-MO7NIH7B.js → goal-tools-AF2FQO3H.js} +1 -1
  119. package/chunks/{handleAutoUpdate-STUVMCIU.js → handleAutoUpdate-WBWK4775.js} +1 -1
  120. package/chunks/{i18n-UTIILRKE.js → i18n-O4Q2KHOA.js} +1 -1
  121. package/chunks/{initializer-YI2WT6LZ.js → initializer-2AH3EKBL.js} +1 -1
  122. package/chunks/{installationInfo-PW2JHHJV.js → installationInfo-77WYXG4W.js} +1 -1
  123. package/chunks/{list-SAOL2OZI.js → list-RAU3ZJQS.js} +1 -1
  124. package/chunks/{llm-LMY62H6Z.js → llm-MJMQ34KB.js} +4 -4
  125. package/chunks/{llm-content-generator-6RPOZ2YR.js → llm-content-generator-MJPR2TWC.js} +1 -1
  126. package/chunks/{loadedSettingsAdapter-RNXWDDE2.js → loadedSettingsAdapter-WRWWNGHZ.js} +1 -1
  127. package/chunks/{local-execution-environment-GIWY2LO6.js → local-execution-environment-VVJ7OYBT.js} +1 -1
  128. package/chunks/{loggingContentGenerator-AOKEDXK6.js → loggingContentGenerator-722BJL7T.js} +1 -1
  129. package/chunks/{manage-memory-WKPWLYDD.js → manage-memory-GN56UQHG.js} +1 -1
  130. package/chunks/{managed-npm-update-LFFWFATA.js → managed-npm-update-5VE662JS.js} +1 -1
  131. package/chunks/{managed-runtime-attestation-worker-IV6ZNIAK.js → managed-runtime-attestation-worker-ASGGZMFM.js} +1 -1
  132. package/chunks/{managed-runtime-session-worker-3NU4FOXD.js → managed-runtime-session-worker-YUSO7WFB.js} +1 -1
  133. package/chunks/{mcp-RDDGN4JK.js → mcp-6D236MEH.js} +1 -1
  134. package/chunks/{model-call-collection-JARTJD6S.js → model-call-collection-UAE2W6VV.js} +1 -1
  135. package/chunks/{model-configuration-7H6PEOLY.js → model-configuration-VHPSBCQI.js} +1 -1
  136. package/chunks/{modelConfigUtils-Q63ZZTXY.js → modelConfigUtils-XKDXYQRJ.js} +1 -1
  137. package/chunks/{monitor-HLO366TQ.js → monitor-JIKXBXDK.js} +1 -1
  138. package/chunks/{nonInteractiveCli-JO5EG6OK.js → nonInteractiveCli-IXTK5V4Q.js} +1 -1
  139. package/chunks/{nonInteractiveToolExecutor-T7AKBX25.js → nonInteractiveToolExecutor-3MSROJV5.js} +1 -1
  140. package/chunks/{notebook-edit-XKULPMG7.js → notebook-edit-VDWBIBMG.js} +1 -1
  141. package/chunks/{omni-H3GFC6KR.js → omni-MEUE65XC.js} +1 -1
  142. package/chunks/{openaiContentGenerator-RT4S6OYR.js → openaiContentGenerator-KNZTYVNK.js} +1 -1
  143. package/chunks/{openaiResponsesContentGenerator-JD4ZBCAL.js → openaiResponsesContentGenerator-G7GRJXES.js} +1 -1
  144. package/chunks/{pidfile-JXCPPGC6.js → pidfile-HMEKKPWO.js} +1 -1
  145. package/chunks/{processUtils-FF7LHGHW.js → processUtils-KHWNT3KU.js} +1 -1
  146. package/chunks/{prompt-terminal-ledger-VLIEJ5BB.js → prompt-terminal-ledger-EY72RU3D.js} +1 -1
  147. package/chunks/{qwenContentGenerator-6SGQI4ES.js → qwenContentGenerator-A7WREYLV.js} +1 -1
  148. package/chunks/{reactive-degrade-2UJPX4AU.js → reactive-degrade-O6WBGQ5X.js} +1 -1
  149. package/chunks/{read-file-27DWTM5N.js → read-file-A4MQWC6T.js} +1 -1
  150. package/chunks/{resumeHistoryUtils-KRF2LD7T.js → resumeHistoryUtils-KNUVMH5J.js} +1 -1
  151. package/chunks/{review-IPFFTVGV.js → review-OC76PLQ4.js} +1 -1
  152. package/chunks/{ripGrep-75QL35XD.js → ripGrep-JR6DHTIW.js} +1 -1
  153. package/chunks/{run-qwen-serve-WW74NSUL.js → run-qwen-serve-NFPGPJJ2.js} +2 -2
  154. package/chunks/{runtime-Z2NIOF6Y.js → runtime-BPHFAZOP.js} +1 -1
  155. package/chunks/{sandboxConfig-WMQAKX7Q.js → sandboxConfig-KXTV3QBG.js} +1 -1
  156. package/chunks/{scheduled-tasks-LMJJ5ZM7.js → scheduled-tasks-2GNFZH4N.js} +1 -1
  157. package/chunks/{scheduler-KHWWXW6H.js → scheduler-CKLZCETX.js} +1 -1
  158. package/chunks/{search-memory-WEO3M674.js → search-memory-ICNU2EJA.js} +1 -1
  159. package/chunks/{send-message-E2EVXDU4.js → send-message-T32PFXX5.js} +1 -1
  160. package/chunks/{serve-E7ZGE7PD.js → serve-O7XBFM36.js} +1 -1
  161. package/chunks/{server-SSHP5IO4.js → server-7H2EGX7C.js} +3 -3
  162. package/chunks/{session-UWUQU3NV.js → session-SO4TKKO3.js} +1 -1
  163. package/chunks/{session-attachments-root-I35OUD7P.js → session-attachments-root-QPBJB3Y2.js} +1 -1
  164. package/chunks/{session-execution-engine-selector-S7HXLYKG.js → session-execution-engine-selector-73JQ7AG6.js} +1 -1
  165. package/chunks/{session-pr-refresh-34FLQB2Z.js → session-pr-refresh-XPDBRBQV.js} +1 -1
  166. package/chunks/{sessionService-BBC2563F.js → sessionService-DDLWVLNC.js} +1 -1
  167. package/chunks/{settings-BXCTAYMU.js → settings-TUEKBNAX.js} +1 -1
  168. package/chunks/{shell-ORZNRZKX.js → shell-SXSN7UYK.js} +1 -1
  169. package/chunks/{skill-3MJ6V2VQ.js → skill-XAYT7HGV.js} +1 -1
  170. package/chunks/{skill-settings-A7TTYJGH.js → skill-settings-X3O75XUN.js} +1 -1
  171. package/chunks/{spawnChannel-UPHPUPIJ.js → spawnChannel-3523LPUW.js} +1 -1
  172. package/chunks/{standalone-update-GGHQ54QB.js → standalone-update-T7AUODLV.js} +1 -1
  173. package/chunks/{start-opentui-ui-O6WMWLGS.js → start-opentui-ui-IKBADQQS.js} +1 -1
  174. package/chunks/{startInteractiveUI-N3ZPR2FK.js → startInteractiveUI-PV2JETB4.js} +1 -1
  175. package/chunks/{team-create-EYLFAQVU.js → team-create-ZKTBFE7Z.js} +1 -1
  176. package/chunks/{team-plan-approval-2WFSX4XE.js → team-plan-approval-SCTAN2HM.js} +1 -1
  177. package/chunks/{terminal-image-renderer-A5HEJZTW.js → terminal-image-renderer-EDBYTK3B.js} +1 -1
  178. package/chunks/{theme-manager-TQHNJSKQ.js → theme-manager-ZLXHLO2Y.js} +1 -1
  179. package/chunks/{tool-call-UBLAA45C.js → tool-call-ULUE3W3P.js} +1 -1
  180. package/chunks/{tool-result-media-53AD3EHK.js → tool-result-media-VXS7QTX7.js} +1 -1
  181. package/chunks/{tool-search-D6PSBDDZ.js → tool-search-VWM6VCVU.js} +1 -1
  182. package/chunks/{total-session-admission-CUMMWSM2.js → total-session-admission-FZDBG232.js} +1 -1
  183. package/chunks/{trustedFolders-TERXKVJ6.js → trustedFolders-VIPEDZNB.js} +1 -1
  184. package/chunks/{update-relaunch-PXCI66U2.js → update-relaunch-N6TNUHQE.js} +1 -1
  185. package/chunks/{updateCheck-2P4ANPL7.js → updateCheck-367IR3FW.js} +1 -1
  186. package/chunks/{upload-config-G2WZG4DM.js → upload-config-5W4WTLML.js} +1 -1
  187. package/chunks/{useAutoAcceptIndicator-H7I7JP34.js → useAutoAcceptIndicator-SGT7EBCJ.js} +1 -1
  188. package/chunks/{validateNonInterActiveAuth-VLRV5LCK.js → validateNonInterActiveAuth-7WEBPZ4S.js} +1 -1
  189. package/chunks/{version-AOKDKXXZ.js → version-3OKRQ6LC.js} +1 -1
  190. package/chunks/{web-fetch-OUJS56AV.js → web-fetch-BV7BK5NT.js} +1 -1
  191. package/chunks/{web-search-3S4ZIGLP.js → web-search-DFQ74G7V.js} +1 -1
  192. package/chunks/{workflow-6W4WB4L5.js → workflow-EXSCHLQK.js} +1 -1
  193. package/chunks/{workspace-agents-7GB2RLY5.js → workspace-agents-HPOPFXKJ.js} +1 -1
  194. package/chunks/{workspace-providers-status-OMD57CUW.js → workspace-providers-status-UQCSR2PB.js} +1 -1
  195. package/chunks/{workspace-registration-store-WKLFVMQ2.js → workspace-registration-store-Q5U4WD5M.js} +1 -1
  196. package/chunks/{workspace-registry-6WJOPYIS.js → workspace-registry-I2O2LXTZ.js} +1 -1
  197. package/chunks/{workspace-runtime-coordinator-XG7G7DG3.js → workspace-runtime-coordinator-MVVDZYYX.js} +1 -1
  198. package/chunks/{workspace-service-YLX46RJM.js → workspace-service-CFJ2EUB7.js} +1 -1
  199. package/chunks/{workspace-skills-status-JZZR7QHN.js → workspace-skills-status-LLNIK3NS.js} +1 -1
  200. package/chunks/{workspace-trust-reconciler-AO3I5KYO.js → workspace-trust-reconciler-VLGJXLCZ.js} +1 -1
  201. package/chunks/{write-file-MGYLC32T.js → write-file-RG7HHIYP.js} +1 -1
  202. package/chunks/{zoom-image-TZ527ASZ.js → zoom-image-AKW6CA4K.js} +1 -1
  203. package/cli.js +2 -2
  204. package/execution-worker.js +1 -1
  205. package/export-transcript-document.js +1 -1
  206. package/package.json +3 -3
  207. package/web-shell/assets/{PierreFilePreview-Cq9imG0c.js → PierreFilePreview-Cij36lF-.js} +1 -1
  208. package/web-shell/assets/{SpreadsheetPreview-Blho0kkO.js → SpreadsheetPreview-kDlHrK21.js} +1 -1
  209. package/web-shell/assets/{WorkspaceFileBrowser-DjeX-ArR.js → WorkspaceFileBrowser-DBXW9l-s.js} +1 -1
  210. package/web-shell/assets/{abnfDiagram-VCTEODGH-mEfLgGao.js → abnfDiagram-VCTEODGH-DBrfOx4O.js} +1 -1
  211. package/web-shell/assets/{agents-route-Bg4_tLdL.js → agents-route-6E_3XRjk.js} +1 -1
  212. package/web-shell/assets/{arc-DEVpMJqB.js → arc-RwrvKU6y.js} +1 -1
  213. package/web-shell/assets/{architectureDiagram-5GKGNRK7-CGhqKvd1.js → architectureDiagram-5GKGNRK7-B2_hfNn6.js} +1 -1
  214. package/web-shell/assets/{blockDiagram-NRAW4CY4-DxpWdCdl.js → blockDiagram-NRAW4CY4-C755qTFO.js} +1 -1
  215. package/web-shell/assets/{c4Diagram-UCG6FXSJ-CE1W0_yu.js → c4Diagram-UCG6FXSJ-CARC2uHQ.js} +1 -1
  216. package/web-shell/assets/channel-U9JRrjem.js +1 -0
  217. package/web-shell/assets/{chunk-2Q5K7J3B-ibHTXjoH.js → chunk-2Q5K7J3B-BS1ldEp9.js} +1 -1
  218. package/web-shell/assets/{chunk-5VM5RSS4-BEZ2-gCE.js → chunk-5VM5RSS4-DckOEd3N.js} +1 -1
  219. package/web-shell/assets/{chunk-F27PBJKO-CKyPZ7Jh.js → chunk-F27PBJKO-fZstOLLL.js} +1 -1
  220. package/web-shell/assets/{chunk-G27WJ6UU-WHNRb7iQ.js → chunk-G27WJ6UU-Bf4QkrJ7.js} +1 -1
  221. package/web-shell/assets/{chunk-JWPE2WC7-Dm4G-fLP.js → chunk-JWPE2WC7-uBW51XO_.js} +1 -1
  222. package/web-shell/assets/{chunk-LCL6LL3I-BvTm39E-.js → chunk-LCL6LL3I-D2MYZdE_.js} +1 -1
  223. package/web-shell/assets/{chunk-POPQ4Y6H-C0zAbzIo.js → chunk-POPQ4Y6H-CzTHTST7.js} +1 -1
  224. package/web-shell/assets/{chunk-SVP7TREG-B36K-VPq.js → chunk-SVP7TREG-fL48tjL5.js} +1 -1
  225. package/web-shell/assets/{chunk-XXDRQBXY-D1opdtZ1.js → chunk-XXDRQBXY-R1jjDz-e.js} +1 -1
  226. package/web-shell/assets/classDiagram-DTDB5LWJ-r255RW6f.js +1 -0
  227. package/web-shell/assets/classDiagram-v2-JRS7N3AN-r255RW6f.js +1 -0
  228. package/web-shell/assets/{cose-bilkent-JH36ORCC-S_IO4ZW5.js → cose-bilkent-JH36ORCC-DTK6Alrt.js} +1 -1
  229. package/web-shell/assets/{cynefin-OW5HDTMX-CGUKfurr.js → cynefin-OW5HDTMX-C1JYDjN4.js} +1 -1
  230. package/web-shell/assets/{cynefinDiagram-5FMLGOSQ-BqUpO_VD.js → cynefinDiagram-5FMLGOSQ-C3bR18IM.js} +1 -1
  231. package/web-shell/assets/{dagre-3AP2YEHR-CiKqZpUi.js → dagre-3AP2YEHR-D4oUlW7g.js} +1 -1
  232. package/web-shell/assets/{diagram-S7CK7UJ4-B3CQED4o.js → diagram-S7CK7UJ4-m-a-vk_2.js} +1 -1
  233. package/web-shell/assets/{diagram-UQ7AKVKN-BewunX5H.js → diagram-UQ7AKVKN-CVGSVvpJ.js} +1 -1
  234. package/web-shell/assets/{diagram-VSXAHHWV-C5j1hiVn.js → diagram-VSXAHHWV-DcLovKfd.js} +1 -1
  235. package/web-shell/assets/{diagram-VX7I27RA-CWDIIA61.js → diagram-VX7I27RA-DAwY09qQ.js} +1 -1
  236. package/web-shell/assets/{diagram-Z3DM3KII-COa1V8UD.js → diagram-Z3DM3KII-D4BWV8Yb.js} +1 -1
  237. package/web-shell/assets/{ebnfDiagram-PWID7BFC-CP33EIO8.js → ebnfDiagram-PWID7BFC-AhqQLlAR.js} +1 -1
  238. package/web-shell/assets/{erDiagram-SSCWMZ5O-V2pL2JAp.js → erDiagram-SSCWMZ5O-DcIpsPuK.js} +1 -1
  239. package/web-shell/assets/{flowDiagram-A5DVABFB-CF-YQlR_.js → flowDiagram-A5DVABFB-Cdu3v56D.js} +1 -1
  240. package/web-shell/assets/{ganttDiagram-EL5Y4UJY-TXUid-Q2.js → ganttDiagram-EL5Y4UJY-D8o98Muo.js} +1 -1
  241. package/web-shell/assets/{gitGraphDiagram-WWUBYQGX-QNcIYsgn.js → gitGraphDiagram-WWUBYQGX-fIAd56jC.js} +1 -1
  242. package/web-shell/assets/{index-CKa6aZMZ.js → index-CJmvuO8Q.js} +1 -1
  243. package/web-shell/assets/{index-N9F4X44H.js → index-DSh5Yfsf.js} +5 -5
  244. package/web-shell/assets/{infoDiagram-RXCK75RN-Dn1biwuc.js → infoDiagram-RXCK75RN-dPnP0Koe.js} +1 -1
  245. package/web-shell/assets/{ishikawaDiagram-5VMMS53U-iBYO7WCt.js → ishikawaDiagram-5VMMS53U-f9Oq8YH7.js} +1 -1
  246. package/web-shell/assets/{journeyDiagram-EYS64GPL-D98LzO4k.js → journeyDiagram-EYS64GPL-CqwSlUQ1.js} +1 -1
  247. package/web-shell/assets/{kanban-definition-3QL26DDD-lQMIgDSM.js → kanban-definition-3QL26DDD-Bh_KTp2S.js} +1 -1
  248. package/web-shell/assets/{layout-BgOy6tFo.js → layout-0e-hGnuM.js} +1 -1
  249. package/web-shell/assets/{linear-En8RXsBs.js → linear-BtxWFISv.js} +1 -1
  250. package/web-shell/assets/{mermaid.core-BneKXyZr.js → mermaid.core-Dik4l-jM.js} +6 -6
  251. package/web-shell/assets/{mindmap-definition-FBJOCRG2-NkP_9BC4.js → mindmap-definition-FBJOCRG2-B7gext3e.js} +1 -1
  252. package/web-shell/assets/{pegDiagram-XKGWAZYB-B0ie-nkt.js → pegDiagram-XKGWAZYB-BfyKzGY0.js} +1 -1
  253. package/web-shell/assets/{pieDiagram-E7YTZNPT-Qa86cFZc.js → pieDiagram-E7YTZNPT-vfeVyHgh.js} +1 -1
  254. package/web-shell/assets/{quadrantDiagram-AXDQQJYC-CkjUzR0e.js → quadrantDiagram-AXDQQJYC-DGAZmngq.js} +1 -1
  255. package/web-shell/assets/{railroadDiagram-O6MQD6OU-mN7KpgJG.js → railroadDiagram-O6MQD6OU-Dgxiy8W5.js} +1 -1
  256. package/web-shell/assets/{requirementDiagram-EFPCY7ZU-Bmn2z6x2.js → requirementDiagram-EFPCY7ZU-D7TFokdR.js} +1 -1
  257. package/web-shell/assets/{sankeyDiagram-P5KCCOFB-CYWnwpoW.js → sankeyDiagram-P5KCCOFB-BZU_UYd-.js} +1 -1
  258. package/web-shell/assets/{sequenceDiagram-WJ2MYXX4-BFyWlR1P.js → sequenceDiagram-WJ2MYXX4-Bz94qtvq.js} +1 -1
  259. package/web-shell/assets/{sizeCapture-X5ZJPWSS-BwCPrn2w.js → sizeCapture-X5ZJPWSS-DVlzIShY.js} +1 -1
  260. package/web-shell/assets/{stateDiagram-HBIQ2CUA-oqL3E0Ws.js → stateDiagram-HBIQ2CUA-CE9Il33j.js} +1 -1
  261. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-BVL1rIGD.js +1 -0
  262. package/web-shell/assets/{swimlanes-XN3QIQJK-C3FAVL8g.js → swimlanes-XN3QIQJK-Cr2CyF9L.js} +1 -1
  263. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-BeWJAUmf.js +8 -0
  264. package/web-shell/assets/{timeline-definition-24CTP7MA-BdwxFsPJ.js → timeline-definition-24CTP7MA-DWbRlUDe.js} +1 -1
  265. package/web-shell/assets/{vennDiagram-4TSXK5OY-j_G2AbSj.js → vennDiagram-4TSXK5OY-Bp5BiaRL.js} +1 -1
  266. package/web-shell/assets/{wardleyDiagram-VM6X3IG4-Dy_fHHBq.js → wardleyDiagram-VM6X3IG4-DoQIUrT8.js} +1 -1
  267. package/web-shell/assets/{xychartDiagram-S5SC5T6Z-CnLgG50x.js → xychartDiagram-S5SC5T6Z-BTO308Vv.js} +1 -1
  268. package/web-shell/index.html +1 -1
  269. package/web-shell/sw.js +1 -1
  270. package/web-shell/assets/channel-CHCXOu89.js +0 -1
  271. package/web-shell/assets/classDiagram-DTDB5LWJ-DXIqcod_.js +0 -1
  272. package/web-shell/assets/classDiagram-v2-JRS7N3AN-DXIqcod_.js +0 -1
  273. package/web-shell/assets/stateDiagram-v2-4QOOHH4V-Cmho6gw2.js +0 -1
  274. package/web-shell/assets/swimlanesDiagram-VK2B7HYN-D9Sfkn7b.js +0 -8
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{captureEnvironmentBeforeLoad,publishPendingCompileCache,resetEnvironmentSnapshotForTesting}from"./chunk-PKK2D2W4.js";import{DEFAULT_EXCLUDED_ENV_VARS,HOME_ENV_BOOTSTRAP_KEYS,PRIVATE_RELAUNCH_ENV_PROVENANCE,PROJECT_ENV_HARDCODED_EXCLUSIONS,isHardcodedProjectEnvExclusion,isLoaderEnvKey,isPrivateProvenanceEnvKey,reportRejectedLoaderKeys,resetLoaderKeyRejectionReportingForTesting}from"./chunk-CVMMNPLX.js";import{isWorkspaceTrusted}from"./chunk-ORIS5AVH.js";import{require_main}from"./chunk-OGI5HG6N.js";import{writeStderrLineSafe}from"./chunk-SLPJ4OII.js";import{Storage}from"./chunk-EPODBRBP.js";import{QWEN_DIR}from"./chunk-OKN3Z5C5.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();var dotenv=__toESM(require_main(),1);import*as fs from"node:fs";import*as path from"node:path";import*as os from"node:os";var SETTINGS_DIRECTORY_NAME=QWEN_DIR;var RELOAD_EXCLUDED_KEYS=new Set([...PROJECT_ENV_HARDCODED_EXCLUSIONS,"QWEN_SERVER_TOKEN","LD_LIBRARY_PATH","DYLD_LIBRARY_PATH","ENV","PATH","HOME"]);var RELOAD_EXCLUDED_KEYS_CASEFOLDED=new Set([...RELOAD_EXCLUDED_KEYS].map(key=>key.toLowerCase()));function isReloadExcludedKey(key){return RELOAD_EXCLUDED_KEYS_CASEFOLDED.has(key.toLowerCase())||isHardcodedProjectEnvExclusion(key)}__name(isReloadExcludedKey,"isReloadExcludedKey");var dotEnvSourcedKeys=new Set;var settingsEnvSourcedKeys=new Set;var inheritedDotEnvKeys=new Set;var inheritedSettingsEnvKeys=new Set;var inheritedProvenance=process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];if(inheritedProvenance){const sources=JSON.parse(inheritedProvenance);if(!sources||typeof sources!=="object"||!("dotEnv"in sources)||!("settingsEnv"in sources)||!Array.isArray(sources.dotEnv)||!Array.isArray(sources.settingsEnv)||!sources.dotEnv.every(key=>typeof key==="string")||!sources.settingsEnv.every(key=>typeof key==="string")){throw new Error("Invalid inherited environment provenance.")}for(const key of sources.dotEnv)inheritedDotEnvKeys.add(key);for(const key of sources.settingsEnv)inheritedSettingsEnvKeys.add(key);Object.assign(process.env,getRelaunchEnvProvenance())}var DOCUMENTED_MODEL_ENV_KEYS=["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_MODEL","QWEN_MODEL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_MODEL","GEMINI_API_KEY","GEMINI_MODEL","GOOGLE_API_KEY","GOOGLE_MODEL"];var requestTimeEnvKeys=new Set;function rememberRequestTimeEnvKeys(settings){requestTimeEnvKeys.clear();for(const key of DOCUMENTED_MODEL_ENV_KEYS)requestTimeEnvKeys.add(key);for(const models of Object.values(settings.modelProviders??{})){if(!Array.isArray(models))continue;for(const model of models){const envKey=model?.envKey;if(typeof envKey==="string"&&envKey&&!isHardcodedProjectEnvExclusion(envKey)&&!isLoaderEnvKey(envKey)){requestTimeEnvKeys.add(envKey)}}}}__name(rememberRequestTimeEnvKeys,"rememberRequestTimeEnvKeys");function hasLoadedEnvironmentValues(){for(const keys of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of keys){if(!requestTimeEnvKeys.has(key))return true}}return false}__name(hasLoadedEnvironmentValues,"hasLoadedEnvironmentValues");function getRelaunchEnvProvenance(){return{[PRIVATE_RELAUNCH_ENV_PROVENANCE]:JSON.stringify({dotEnv:[...new Set([...inheritedDotEnvKeys,...dotEnvSourcedKeys])],settingsEnv:[...new Set([...inheritedSettingsEnvKeys,...settingsEnvSourcedKeys])]})}}__name(getRelaunchEnvProvenance,"getRelaunchEnvProvenance");var lastReloadSnapshot=new Map;var lastReloadSnapshotSeeded=false;function getUserLevelEnvPaths(){const homeDir=os.homedir();const globalQwenDir=Storage.getGlobalQwenDir();const paths=new Set([path.normalize(path.join(homeDir,".env")),path.normalize(path.join(globalQwenDir,".env"))]);const legacyQwenEnv=path.normalize(path.join(homeDir,QWEN_DIR,".env"));paths.add(legacyQwenEnv);return paths}__name(getUserLevelEnvPaths,"getUserLevelEnvPaths");var homeEnvBootstrapped=false;function preResolveHomeEnvOverrides(){if(homeEnvBootstrapped){return}homeEnvBootstrapped=true;if(HOME_ENV_BOOTSTRAP_KEYS.every(key=>process.env[key])){return}const initialQwenHome=process.env["QWEN_HOME"];const initialQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(initialQwenDir,".env")];if(!initialQwenHome){candidates.push(path.join(path.dirname(initialQwenDir),".env"))}for(const candidate of candidates){readHomeEnvInto(candidate)}const discoveredQwenHome=process.env["QWEN_HOME"];if(discoveredQwenHome&&discoveredQwenHome!==initialQwenHome){const discoveredDir=Storage.getGlobalQwenDir();if(discoveredDir!==initialQwenDir){readHomeEnvInto(path.join(discoveredDir,".env"))}}}__name(preResolveHomeEnvOverrides,"preResolveHomeEnvOverrides");function readHomeEnvInto(file){if(!fs.existsSync(file)){return}try{const parsed=dotenv.parse(fs.readFileSync(file,"utf-8"));for(const key of HOME_ENV_BOOTSTRAP_KEYS){if(parsed[key]&&!Object.hasOwn(process.env,key)){process.env[key]=parsed[key]}}}catch(_e){}}__name(readHomeEnvInto,"readHomeEnvInto");function resetHomeEnvBootstrapForTesting(){homeEnvBootstrapped=false}__name(resetHomeEnvBootstrapForTesting,"resetHomeEnvBootstrapForTesting");function resetEnvironmentTrackingForTesting(){resetLoaderKeyRejectionReportingForTesting();resetEnvironmentSnapshotForTesting();dotEnvSourcedKeys.clear();settingsEnvSourcedKeys.clear();inheritedDotEnvKeys.clear();inheritedSettingsEnvKeys.clear();requestTimeEnvKeys.clear();delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];lastReloadSnapshot.clear();lastReloadSnapshotSeeded=false}__name(resetEnvironmentTrackingForTesting,"resetEnvironmentTrackingForTesting");function isFileSourcedEnvKey(key){const sources=[dotEnvSourcedKeys,settingsEnvSourcedKeys,inheritedDotEnvKeys,inheritedSettingsEnvKeys];if(sources.some(keys=>keys.has(key))){return true}if(process.platform!=="win32")return false;const lower=key.toLowerCase();for(const keys of sources){for(const tracked of keys){if(tracked.toLowerCase()===lower)return true}}return false}__name(isFileSourcedEnvKey,"isFileSourcedEnvKey");function getHomeEnvFallbackVars(onReadError){const globalQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(globalQwenDir,".env")];if(!process.env["QWEN_HOME"]){candidates.push(path.join(path.dirname(globalQwenDir),".env"))}const result={};for(const candidate of candidates){if(!fs.existsSync(candidate)){continue}try{const parsed=dotenv.parse(fs.readFileSync(candidate,"utf-8"));for(const key in parsed){if(Object.hasOwn(parsed,key)&&!Object.hasOwn(process.env,key)){result[key]??=parsed[key]}}}catch(e){onReadError?.(`Failed to read home .env candidate ${candidate}: ${getErrorMessage(e)}`)}}return result}__name(getHomeEnvFallbackVars,"getHomeEnvFallbackVars");function findEnvFiles(settings,startDir,userLevelPaths=getUserLevelEnvPaths(),workspaceTrusted){const homeDir=os.homedir();let realStartDir=path.resolve(startDir);try{realStartDir=fs.realpathSync(realStartDir)}catch{}const globalQwenDir=Storage.getGlobalQwenDir();const legacyQwenDir=path.normalize(path.join(homeDir,QWEN_DIR));const hasCustomConfigDir=path.normalize(globalQwenDir)!==legacyQwenDir;const found=[];const seen=new Set;const workspaceIsTrusted=workspaceTrusted??isWorkspaceTrusted(settings,void 0,realStartDir).isTrusted===true;const canUseEnvFile=__name(filePath=>{const normalized=path.normalize(filePath);if(userLevelPaths.has(normalized))return true;if(!workspaceIsTrusted)return false;const dirPath=path.dirname(normalized);const workspaceDir=path.basename(dirPath)===SETTINGS_DIRECTORY_NAME?path.dirname(dirPath):dirPath;if(workspaceDir===realStartDir)return true;return isWorkspaceTrusted(settings,void 0,workspaceDir).isTrusted!==false},"canUseEnvFile");const pushCandidate=__name(filePath=>{const normalized=path.normalize(filePath);if(!seen.has(normalized)&&fs.existsSync(filePath)&&canUseEnvFile(filePath)){seen.add(normalized);found.push(filePath);return true}return false},"pushCandidate");const pushHomeCandidates=__name(()=>{const candidates=[path.join(globalQwenDir,".env")];if(hasCustomConfigDir){candidates.push(path.join(legacyQwenDir,".env"))}candidates.push(path.join(homeDir,".env"));for(const candidate of candidates){pushCandidate(candidate)}},"pushHomeCandidates");if(path.resolve(startDir)===path.resolve(homeDir)){pushHomeCandidates();return found}let currentDir=realStartDir;let visitedHomeDir=false;while(true){if(currentDir===homeDir){visitedHomeDir=true;pushHomeCandidates();return found}else{const geminiEnvPath=path.join(currentDir,QWEN_DIR,".env");if(pushCandidate(geminiEnvPath)){pushHomeCandidates();return found}const envPath=path.join(currentDir,".env");if(pushCandidate(envPath)){pushHomeCandidates();return found}}const parentDir=path.dirname(currentDir);if(parentDir===currentDir||!parentDir){if(!visitedHomeDir){pushHomeCandidates()}return found}currentDir=parentDir}}__name(findEnvFiles,"findEnvFiles");function setUpCloudShellEnvironment(envFilePath){if(envFilePath&&fs.existsSync(envFilePath)){const envFileContent=fs.readFileSync(envFilePath);const parsedEnv=dotenv.parse(envFileContent);if(parsedEnv["GOOGLE_CLOUD_PROJECT"]){process.env["GOOGLE_CLOUD_PROJECT"]=parsedEnv["GOOGLE_CLOUD_PROJECT"]}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}__name(setUpCloudShellEnvironment,"setUpCloudShellEnvironment");function setUpCloudShellEnvironmentInEnv(env,envFiles){for(const envFile of envFiles){if(envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"]){env["GOOGLE_CLOUD_PROJECT"]=envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"];return}}env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}__name(setUpCloudShellEnvironmentInEnv,"setUpCloudShellEnvironmentInEnv");function parseEnvFiles(envFilePaths,userLevelPaths){const files=[];const readFailures=[];for(const envFilePath of envFilePaths){try{const envFileContent=fs.readFileSync(envFilePath,"utf-8");const parsedEnv=dotenv.parse(envFileContent);const normalizedEnvFilePath=path.normalize(envFilePath);const isHomeScopedEnvFile=userLevelPaths.has(normalizedEnvFilePath);const isQwenScopedEnvFile=isHomeScopedEnvFile||path.basename(path.dirname(normalizedEnvFilePath))===QWEN_DIR;files.push({path:envFilePath,parsedEnv,isHomeScopedEnvFile,isQwenScopedEnvFile})}catch(err){readFailures.push({path:envFilePath,error:getErrorMessage(err)})}}return{files,readFailed:readFailures.length>0,readFailures}}__name(parseEnvFiles,"parseEnvFiles");function canApplyParsedEnvKey(envFile,key,excludedVars,options={}){if(!Object.hasOwn(envFile.parsedEnv,key))return false;if(isLoaderEnvKey(key))return false;if(isPrivateProvenanceEnvKey(key))return false;if(options.reload&&isReloadExcludedKey(key))return false;if(!envFile.isHomeScopedEnvFile&&isHardcodedProjectEnvExclusion(key)){return false}return envFile.isQwenScopedEnvFile||!excludedVars.includes(key)}__name(canApplyParsedEnvKey,"canApplyParsedEnvKey");function isEffectivelyUnset(env,key){const existingValue=env[key];return!Object.hasOwn(env,key)||existingValue===""}__name(isEffectivelyUnset,"isEffectivelyUnset");function setRuntimeEnvIfUnset(env,key,value){if(isEffectivelyUnset(env,key)){env[key]=value}}__name(setRuntimeEnvIfUnset,"setRuntimeEnvIfUnset");function reportRejectedSettingsEnv(env,startDir){const source=`settings.env (${startDir})`;reportRejectedLoaderKeys(source,Object.keys(env));if(Object.entries(env).some(([key,value])=>key.toUpperCase()==="QWEN_AGENT_EXECUTION_BACKEND"&&typeof value==="string"&&value.trim()!=="")){writeStderrLineSafe(`qwen: ${source} cannot set QWEN_AGENT_EXECUTION_BACKEND; ignored. Export it in the launch environment instead.`)}}__name(reportRejectedSettingsEnv,"reportRejectedSettingsEnv");function buildRuntimeEnvironment(settings,startDir=process.cwd(),baseEnv=process.env,workspaceTrusted){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);const effectiveEnv={...baseEnv};if(baseEnv["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(effectiveEnv,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}setRuntimeEnvIfUnset(effectiveEnv,key,envFile.parsedEnv[key])}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(excludedVars.includes(key))continue;if(typeof value!=="string")continue;setRuntimeEnvIfUnset(effectiveEnv,key,value)}reportRejectedSettingsEnv(settings.env,startDir)}const overlayKeys=Object.keys(effectiveEnv).filter(key=>effectiveEnv[key]!==baseEnv[key]).sort();return{effectiveEnv:Object.freeze({...effectiveEnv}),overlayKeys:Object.freeze(overlayKeys),envFilePaths:Object.freeze([...envFilePaths]),envFileReadFailed:parsedEnvFiles.readFailed,envFileReadFailures:Object.freeze([...parsedEnvFiles.readFailures])}}__name(buildRuntimeEnvironment,"buildRuntimeEnvironment");function loadEnvironment(settings,startDir=process.cwd()){captureEnvironmentBeforeLoad();rememberRequestTimeEnvKeys(settings);const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars))continue;const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2){process.env[key]=envFile.parsedEnv[key];dotEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key)){continue}if(isReloadExcludedKey(key)){continue}if(isHardcodedProjectEnvExclusion(key)){continue}const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2&&typeof value==="string"){process.env[key]=value;settingsEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&typeof value==="string"&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,value)}}reportRejectedSettingsEnv(settings.env,startDir)}lastReloadSnapshotSeeded=true;Object.assign(process.env,getRelaunchEnvProvenance());publishPendingCompileCache()}__name(loadEnvironment,"loadEnvironment");function reloadEnvironment(settings,workspaceCwd,workspaceTrusted,options={}){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,workspaceCwd,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(parsedEnvFiles.readFailed&&options.failClosedOnEnvFileReadError){return{updatedKeys:[],removedKeys:[],envFileReadFailed:true}}if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}const dotEnvReadFailed=parsedEnvFiles.readFailed;const newDotEnvKeys=new Map;const newSettingsEnvKeys=new Map;for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}if(!newDotEnvKeys.has(key)){newDotEnvKeys.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(typeof value!=="string")continue;const dotEnvValue=newDotEnvKeys.get(key);if(dotEnvValue!==void 0&&dotEnvValue!=="")continue;if(dotEnvReadFailed&&lastReloadSnapshot.has(key))continue;newSettingsEnvKeys.set(key,value)}reportRejectedSettingsEnv(settings.env,workspaceCwd)}const allNewKeys=new Set([...newDotEnvKeys.keys(),...newSettingsEnvKeys.keys()]);const updatedKeys=[];const removedKeys=[];if(!dotEnvReadFailed){const previouslyKnown=new Set([...lastReloadSnapshot.keys(),...dotEnvSourcedKeys,...settingsEnvSourcedKeys]);for(const key of previouslyKnown){if(!allNewKeys.has(key)&&!isReloadExcludedKey(key)){delete process.env[key];inheritedDotEnvKeys.delete(key);inheritedSettingsEnvKeys.delete(key);removedKeys.push(key)}}}for(const[key,value]of newDotEnvKeys){if(value===""&&newSettingsEnvKeys.has(key))continue;if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}for(const[key,value]of newSettingsEnvKeys){if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}if(!dotEnvReadFailed){for(const sources of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of sources){if(!isReloadExcludedKey(key))sources.delete(key)}}lastReloadSnapshot.clear();for(const[key,value]of newDotEnvKeys){lastReloadSnapshot.set(key,value)}for(const[key,value]of newSettingsEnvKeys){lastReloadSnapshot.set(key,value)}}for(const key of newDotEnvKeys.keys()){dotEnvSourcedKeys.add(key)}for(const key of newSettingsEnvKeys.keys()){settingsEnvSourcedKeys.add(key)}Object.assign(process.env,getRelaunchEnvProvenance());return{updatedKeys,removedKeys,...dotEnvReadFailed?{envFileReadFailed:true}:{}}}__name(reloadEnvironment,"reloadEnvironment");export{SETTINGS_DIRECTORY_NAME,hasLoadedEnvironmentValues,getRelaunchEnvProvenance,preResolveHomeEnvOverrides,resetHomeEnvBootstrapForTesting,resetEnvironmentTrackingForTesting,isFileSourcedEnvKey,getHomeEnvFallbackVars,findEnvFiles,setUpCloudShellEnvironment,buildRuntimeEnvironment,loadEnvironment,reloadEnvironment};
3
+ import{captureEnvironmentBeforeLoad,publishPendingCompileCache,resetEnvironmentSnapshotForTesting}from"./chunk-PKK2D2W4.js";import{DEFAULT_EXCLUDED_ENV_VARS,HOME_ENV_BOOTSTRAP_KEYS,PRIVATE_RELAUNCH_ENV_PROVENANCE,PROJECT_ENV_HARDCODED_EXCLUSIONS,isHardcodedProjectEnvExclusion,isLoaderEnvKey,isPrivateProvenanceEnvKey,reportRejectedLoaderKeys,resetLoaderKeyRejectionReportingForTesting}from"./chunk-CVMMNPLX.js";import{isWorkspaceTrusted}from"./chunk-SYO5FPHL.js";import{require_main}from"./chunk-OGI5HG6N.js";import{writeStderrLineSafe}from"./chunk-SLPJ4OII.js";import{Storage}from"./chunk-EPODBRBP.js";import{QWEN_DIR}from"./chunk-OKN3Z5C5.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();var dotenv=__toESM(require_main(),1);import*as fs from"node:fs";import*as path from"node:path";import*as os from"node:os";var SETTINGS_DIRECTORY_NAME=QWEN_DIR;var RELOAD_EXCLUDED_KEYS=new Set([...PROJECT_ENV_HARDCODED_EXCLUSIONS,"QWEN_SERVER_TOKEN","LD_LIBRARY_PATH","DYLD_LIBRARY_PATH","ENV","PATH","HOME"]);var RELOAD_EXCLUDED_KEYS_CASEFOLDED=new Set([...RELOAD_EXCLUDED_KEYS].map(key=>key.toLowerCase()));function isReloadExcludedKey(key){return RELOAD_EXCLUDED_KEYS_CASEFOLDED.has(key.toLowerCase())||isHardcodedProjectEnvExclusion(key)}__name(isReloadExcludedKey,"isReloadExcludedKey");var dotEnvSourcedKeys=new Set;var settingsEnvSourcedKeys=new Set;var inheritedDotEnvKeys=new Set;var inheritedSettingsEnvKeys=new Set;var inheritedProvenance=process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];if(inheritedProvenance){const sources=JSON.parse(inheritedProvenance);if(!sources||typeof sources!=="object"||!("dotEnv"in sources)||!("settingsEnv"in sources)||!Array.isArray(sources.dotEnv)||!Array.isArray(sources.settingsEnv)||!sources.dotEnv.every(key=>typeof key==="string")||!sources.settingsEnv.every(key=>typeof key==="string")){throw new Error("Invalid inherited environment provenance.")}for(const key of sources.dotEnv)inheritedDotEnvKeys.add(key);for(const key of sources.settingsEnv)inheritedSettingsEnvKeys.add(key);Object.assign(process.env,getRelaunchEnvProvenance())}var DOCUMENTED_MODEL_ENV_KEYS=["OPENAI_API_KEY","OPENAI_BASE_URL","OPENAI_MODEL","QWEN_MODEL","ANTHROPIC_API_KEY","ANTHROPIC_BASE_URL","ANTHROPIC_MODEL","GEMINI_API_KEY","GEMINI_MODEL","GOOGLE_API_KEY","GOOGLE_MODEL"];var requestTimeEnvKeys=new Set;function rememberRequestTimeEnvKeys(settings){requestTimeEnvKeys.clear();for(const key of DOCUMENTED_MODEL_ENV_KEYS)requestTimeEnvKeys.add(key);for(const models of Object.values(settings.modelProviders??{})){if(!Array.isArray(models))continue;for(const model of models){const envKey=model?.envKey;if(typeof envKey==="string"&&envKey&&!isHardcodedProjectEnvExclusion(envKey)&&!isLoaderEnvKey(envKey)){requestTimeEnvKeys.add(envKey)}}}}__name(rememberRequestTimeEnvKeys,"rememberRequestTimeEnvKeys");function hasLoadedEnvironmentValues(){for(const keys of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of keys){if(!requestTimeEnvKeys.has(key))return true}}return false}__name(hasLoadedEnvironmentValues,"hasLoadedEnvironmentValues");function getRelaunchEnvProvenance(){return{[PRIVATE_RELAUNCH_ENV_PROVENANCE]:JSON.stringify({dotEnv:[...new Set([...inheritedDotEnvKeys,...dotEnvSourcedKeys])],settingsEnv:[...new Set([...inheritedSettingsEnvKeys,...settingsEnvSourcedKeys])]})}}__name(getRelaunchEnvProvenance,"getRelaunchEnvProvenance");var lastReloadSnapshot=new Map;var lastReloadSnapshotSeeded=false;function getUserLevelEnvPaths(){const homeDir=os.homedir();const globalQwenDir=Storage.getGlobalQwenDir();const paths=new Set([path.normalize(path.join(homeDir,".env")),path.normalize(path.join(globalQwenDir,".env"))]);const legacyQwenEnv=path.normalize(path.join(homeDir,QWEN_DIR,".env"));paths.add(legacyQwenEnv);return paths}__name(getUserLevelEnvPaths,"getUserLevelEnvPaths");var homeEnvBootstrapped=false;function preResolveHomeEnvOverrides(){if(homeEnvBootstrapped){return}homeEnvBootstrapped=true;if(HOME_ENV_BOOTSTRAP_KEYS.every(key=>process.env[key])){return}const initialQwenHome=process.env["QWEN_HOME"];const initialQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(initialQwenDir,".env")];if(!initialQwenHome){candidates.push(path.join(path.dirname(initialQwenDir),".env"))}for(const candidate of candidates){readHomeEnvInto(candidate)}const discoveredQwenHome=process.env["QWEN_HOME"];if(discoveredQwenHome&&discoveredQwenHome!==initialQwenHome){const discoveredDir=Storage.getGlobalQwenDir();if(discoveredDir!==initialQwenDir){readHomeEnvInto(path.join(discoveredDir,".env"))}}}__name(preResolveHomeEnvOverrides,"preResolveHomeEnvOverrides");function readHomeEnvInto(file){if(!fs.existsSync(file)){return}try{const parsed=dotenv.parse(fs.readFileSync(file,"utf-8"));for(const key of HOME_ENV_BOOTSTRAP_KEYS){if(parsed[key]&&!Object.hasOwn(process.env,key)){process.env[key]=parsed[key]}}}catch(_e){}}__name(readHomeEnvInto,"readHomeEnvInto");function resetHomeEnvBootstrapForTesting(){homeEnvBootstrapped=false}__name(resetHomeEnvBootstrapForTesting,"resetHomeEnvBootstrapForTesting");function resetEnvironmentTrackingForTesting(){resetLoaderKeyRejectionReportingForTesting();resetEnvironmentSnapshotForTesting();dotEnvSourcedKeys.clear();settingsEnvSourcedKeys.clear();inheritedDotEnvKeys.clear();inheritedSettingsEnvKeys.clear();requestTimeEnvKeys.clear();delete process.env[PRIVATE_RELAUNCH_ENV_PROVENANCE];lastReloadSnapshot.clear();lastReloadSnapshotSeeded=false}__name(resetEnvironmentTrackingForTesting,"resetEnvironmentTrackingForTesting");function isFileSourcedEnvKey(key){const sources=[dotEnvSourcedKeys,settingsEnvSourcedKeys,inheritedDotEnvKeys,inheritedSettingsEnvKeys];if(sources.some(keys=>keys.has(key))){return true}if(process.platform!=="win32")return false;const lower=key.toLowerCase();for(const keys of sources){for(const tracked of keys){if(tracked.toLowerCase()===lower)return true}}return false}__name(isFileSourcedEnvKey,"isFileSourcedEnvKey");function getHomeEnvFallbackVars(onReadError){const globalQwenDir=Storage.getGlobalQwenDir();const candidates=[path.join(globalQwenDir,".env")];if(!process.env["QWEN_HOME"]){candidates.push(path.join(path.dirname(globalQwenDir),".env"))}const result={};for(const candidate of candidates){if(!fs.existsSync(candidate)){continue}try{const parsed=dotenv.parse(fs.readFileSync(candidate,"utf-8"));for(const key in parsed){if(Object.hasOwn(parsed,key)&&!Object.hasOwn(process.env,key)){result[key]??=parsed[key]}}}catch(e){onReadError?.(`Failed to read home .env candidate ${candidate}: ${getErrorMessage(e)}`)}}return result}__name(getHomeEnvFallbackVars,"getHomeEnvFallbackVars");function findEnvFiles(settings,startDir,userLevelPaths=getUserLevelEnvPaths(),workspaceTrusted){const homeDir=os.homedir();let realStartDir=path.resolve(startDir);try{realStartDir=fs.realpathSync(realStartDir)}catch{}const globalQwenDir=Storage.getGlobalQwenDir();const legacyQwenDir=path.normalize(path.join(homeDir,QWEN_DIR));const hasCustomConfigDir=path.normalize(globalQwenDir)!==legacyQwenDir;const found=[];const seen=new Set;const workspaceIsTrusted=workspaceTrusted??isWorkspaceTrusted(settings,void 0,realStartDir).isTrusted===true;const canUseEnvFile=__name(filePath=>{const normalized=path.normalize(filePath);if(userLevelPaths.has(normalized))return true;if(!workspaceIsTrusted)return false;const dirPath=path.dirname(normalized);const workspaceDir=path.basename(dirPath)===SETTINGS_DIRECTORY_NAME?path.dirname(dirPath):dirPath;if(workspaceDir===realStartDir)return true;return isWorkspaceTrusted(settings,void 0,workspaceDir).isTrusted!==false},"canUseEnvFile");const pushCandidate=__name(filePath=>{const normalized=path.normalize(filePath);if(!seen.has(normalized)&&fs.existsSync(filePath)&&canUseEnvFile(filePath)){seen.add(normalized);found.push(filePath);return true}return false},"pushCandidate");const pushHomeCandidates=__name(()=>{const candidates=[path.join(globalQwenDir,".env")];if(hasCustomConfigDir){candidates.push(path.join(legacyQwenDir,".env"))}candidates.push(path.join(homeDir,".env"));for(const candidate of candidates){pushCandidate(candidate)}},"pushHomeCandidates");if(path.resolve(startDir)===path.resolve(homeDir)){pushHomeCandidates();return found}let currentDir=realStartDir;let visitedHomeDir=false;while(true){if(currentDir===homeDir){visitedHomeDir=true;pushHomeCandidates();return found}else{const geminiEnvPath=path.join(currentDir,QWEN_DIR,".env");if(pushCandidate(geminiEnvPath)){pushHomeCandidates();return found}const envPath=path.join(currentDir,".env");if(pushCandidate(envPath)){pushHomeCandidates();return found}}const parentDir=path.dirname(currentDir);if(parentDir===currentDir||!parentDir){if(!visitedHomeDir){pushHomeCandidates()}return found}currentDir=parentDir}}__name(findEnvFiles,"findEnvFiles");function setUpCloudShellEnvironment(envFilePath){if(envFilePath&&fs.existsSync(envFilePath)){const envFileContent=fs.readFileSync(envFilePath);const parsedEnv=dotenv.parse(envFileContent);if(parsedEnv["GOOGLE_CLOUD_PROJECT"]){process.env["GOOGLE_CLOUD_PROJECT"]=parsedEnv["GOOGLE_CLOUD_PROJECT"]}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}else{process.env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}}__name(setUpCloudShellEnvironment,"setUpCloudShellEnvironment");function setUpCloudShellEnvironmentInEnv(env,envFiles){for(const envFile of envFiles){if(envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"]){env["GOOGLE_CLOUD_PROJECT"]=envFile.parsedEnv["GOOGLE_CLOUD_PROJECT"];return}}env["GOOGLE_CLOUD_PROJECT"]="cloudshell-gca"}__name(setUpCloudShellEnvironmentInEnv,"setUpCloudShellEnvironmentInEnv");function parseEnvFiles(envFilePaths,userLevelPaths){const files=[];const readFailures=[];for(const envFilePath of envFilePaths){try{const envFileContent=fs.readFileSync(envFilePath,"utf-8");const parsedEnv=dotenv.parse(envFileContent);const normalizedEnvFilePath=path.normalize(envFilePath);const isHomeScopedEnvFile=userLevelPaths.has(normalizedEnvFilePath);const isQwenScopedEnvFile=isHomeScopedEnvFile||path.basename(path.dirname(normalizedEnvFilePath))===QWEN_DIR;files.push({path:envFilePath,parsedEnv,isHomeScopedEnvFile,isQwenScopedEnvFile})}catch(err){readFailures.push({path:envFilePath,error:getErrorMessage(err)})}}return{files,readFailed:readFailures.length>0,readFailures}}__name(parseEnvFiles,"parseEnvFiles");function canApplyParsedEnvKey(envFile,key,excludedVars,options={}){if(!Object.hasOwn(envFile.parsedEnv,key))return false;if(isLoaderEnvKey(key))return false;if(isPrivateProvenanceEnvKey(key))return false;if(options.reload&&isReloadExcludedKey(key))return false;if(!envFile.isHomeScopedEnvFile&&isHardcodedProjectEnvExclusion(key)){return false}return envFile.isQwenScopedEnvFile||!excludedVars.includes(key)}__name(canApplyParsedEnvKey,"canApplyParsedEnvKey");function isEffectivelyUnset(env,key){const existingValue=env[key];return!Object.hasOwn(env,key)||existingValue===""}__name(isEffectivelyUnset,"isEffectivelyUnset");function setRuntimeEnvIfUnset(env,key,value){if(isEffectivelyUnset(env,key)){env[key]=value}}__name(setRuntimeEnvIfUnset,"setRuntimeEnvIfUnset");function reportRejectedSettingsEnv(env,startDir){const source=`settings.env (${startDir})`;reportRejectedLoaderKeys(source,Object.keys(env));if(Object.entries(env).some(([key,value])=>key.toUpperCase()==="QWEN_AGENT_EXECUTION_BACKEND"&&typeof value==="string"&&value.trim()!=="")){writeStderrLineSafe(`qwen: ${source} cannot set QWEN_AGENT_EXECUTION_BACKEND; ignored. Export it in the launch environment instead.`)}}__name(reportRejectedSettingsEnv,"reportRejectedSettingsEnv");function buildRuntimeEnvironment(settings,startDir=process.cwd(),baseEnv=process.env,workspaceTrusted){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);const effectiveEnv={...baseEnv};if(baseEnv["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(effectiveEnv,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}setRuntimeEnvIfUnset(effectiveEnv,key,envFile.parsedEnv[key])}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(excludedVars.includes(key))continue;if(typeof value!=="string")continue;setRuntimeEnvIfUnset(effectiveEnv,key,value)}reportRejectedSettingsEnv(settings.env,startDir)}const overlayKeys=Object.keys(effectiveEnv).filter(key=>effectiveEnv[key]!==baseEnv[key]).sort();return{effectiveEnv:Object.freeze({...effectiveEnv}),overlayKeys:Object.freeze(overlayKeys),envFilePaths:Object.freeze([...envFilePaths]),envFileReadFailed:parsedEnvFiles.readFailed,envFileReadFailures:Object.freeze([...parsedEnvFiles.readFailures])}}__name(buildRuntimeEnvironment,"buildRuntimeEnvironment");function loadEnvironment(settings,startDir=process.cwd()){captureEnvironmentBeforeLoad();rememberRequestTimeEnvKeys(settings);const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,startDir,userLevelPaths);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars))continue;const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2){process.env[key]=envFile.parsedEnv[key];dotEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key)){continue}if(isReloadExcludedKey(key)){continue}if(isHardcodedProjectEnvExclusion(key)){continue}const existingValue=process.env[key];const isEffectivelyUnset2=!Object.hasOwn(process.env,key)||existingValue==="";if(isEffectivelyUnset2&&typeof value==="string"){process.env[key]=value;settingsEnvSourcedKeys.add(key)}if(!lastReloadSnapshotSeeded&&typeof value==="string"&&!lastReloadSnapshot.has(key)){lastReloadSnapshot.set(key,value)}}reportRejectedSettingsEnv(settings.env,startDir)}lastReloadSnapshotSeeded=true;Object.assign(process.env,getRelaunchEnvProvenance());publishPendingCompileCache()}__name(loadEnvironment,"loadEnvironment");function reloadEnvironment(settings,workspaceCwd,workspaceTrusted,options={}){const userLevelPaths=getUserLevelEnvPaths();const envFilePaths=findEnvFiles(settings,workspaceCwd,userLevelPaths,workspaceTrusted);const parsedEnvFiles=parseEnvFiles(envFilePaths,userLevelPaths);if(parsedEnvFiles.readFailed&&options.failClosedOnEnvFileReadError){return{updatedKeys:[],removedKeys:[],envFileReadFailed:true}}if(process.env["CLOUD_SHELL"]==="true"){setUpCloudShellEnvironmentInEnv(process.env,parsedEnvFiles.files)}const dotEnvReadFailed=parsedEnvFiles.readFailed;const newDotEnvKeys=new Map;const newSettingsEnvKeys=new Map;for(const envFile of parsedEnvFiles.files){const excludedVars=settings?.advanced?.excludedEnvVars||DEFAULT_EXCLUDED_ENV_VARS;for(const key in envFile.parsedEnv){if(!canApplyParsedEnvKey(envFile,key,excludedVars,{reload:true})){continue}if(!newDotEnvKeys.has(key)){newDotEnvKeys.set(key,envFile.parsedEnv[key])}}reportRejectedLoaderKeys(`.env file ${envFile.path}`,Object.keys(envFile.parsedEnv))}if(settings.env){for(const[key,value]of Object.entries(settings.env)){if(isLoaderEnvKey(key))continue;if(isReloadExcludedKey(key))continue;if(isHardcodedProjectEnvExclusion(key))continue;if(typeof value!=="string")continue;const dotEnvValue=newDotEnvKeys.get(key);if(dotEnvValue!==void 0&&dotEnvValue!=="")continue;if(dotEnvReadFailed&&lastReloadSnapshot.has(key))continue;newSettingsEnvKeys.set(key,value)}reportRejectedSettingsEnv(settings.env,workspaceCwd)}const allNewKeys=new Set([...newDotEnvKeys.keys(),...newSettingsEnvKeys.keys()]);const updatedKeys=[];const removedKeys=[];if(!dotEnvReadFailed){const previouslyKnown=new Set([...lastReloadSnapshot.keys(),...dotEnvSourcedKeys,...settingsEnvSourcedKeys]);for(const key of previouslyKnown){if(!allNewKeys.has(key)&&!isReloadExcludedKey(key)){delete process.env[key];inheritedDotEnvKeys.delete(key);inheritedSettingsEnvKeys.delete(key);removedKeys.push(key)}}}for(const[key,value]of newDotEnvKeys){if(value===""&&newSettingsEnvKeys.has(key))continue;if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}for(const[key,value]of newSettingsEnvKeys){if(process.env[key]!==value){updatedKeys.push(key)}process.env[key]=value}if(!dotEnvReadFailed){for(const sources of[dotEnvSourcedKeys,settingsEnvSourcedKeys]){for(const key of sources){if(!isReloadExcludedKey(key))sources.delete(key)}}lastReloadSnapshot.clear();for(const[key,value]of newDotEnvKeys){lastReloadSnapshot.set(key,value)}for(const[key,value]of newSettingsEnvKeys){lastReloadSnapshot.set(key,value)}}for(const key of newDotEnvKeys.keys()){dotEnvSourcedKeys.add(key)}for(const key of newSettingsEnvKeys.keys()){settingsEnvSourcedKeys.add(key)}Object.assign(process.env,getRelaunchEnvProvenance());return{updatedKeys,removedKeys,...dotEnvReadFailed?{envFileReadFailed:true}:{}}}__name(reloadEnvironment,"reloadEnvironment");export{SETTINGS_DIRECTORY_NAME,hasLoadedEnvironmentValues,getRelaunchEnvProvenance,preResolveHomeEnvOverrides,resetHomeEnvBootstrapForTesting,resetEnvironmentTrackingForTesting,isFileSourcedEnvKey,getHomeEnvFallbackVars,findEnvFiles,setUpCloudShellEnvironment,buildRuntimeEnvironment,loadEnvironment,reloadEnvironment};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen Team
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{ProcessRegistry}from"./chunk-ESSOEHTE.js";import{createStderrForwarder}from"./chunk-67JO7MT3.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError,ndJsonStream}from"./chunk-WSOEJTOC.js";import{AgentEventEmitter,renderSubagentSystemPrompt}from"./chunk-GG7RNHZW.js";import{sanitizeChildEnv}from"./chunk-LFKUPU57.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{spawn}from"node:child_process";import{Readable,Writable}from"node:stream";init_esbuild_shims();var INIT_TIMEOUT_MS=1e4;var debugLogger=createDebugLogger("EXTERNAL_AGENT");function externalModelLabel(command){return`external-acp:${command.split(/[\\/]/).pop()??command}`}__name(externalModelLabel,"externalModelLabel");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var EXTERNAL_ACTION_PROMPT_MAX=300;function stripControlChars(value){let out="";for(const ch of value){const code=ch.codePointAt(0)??0;out+=code>=32&&code!==127&&!(code>=128&&code<=159)?ch:" "}return out}__name(stripControlChars,"stripControlChars");function describeExternalAction(toolCall){const title=stripControlChars(toolCall.title??toolCall.kind??"External action");const raw=toolCall.rawInput;if(!isRecord(raw))return title;const detail=stripControlChars(JSON.stringify(raw));const rendered=`${title}: ${detail}`;return rendered.length>EXTERNAL_ACTION_PROMPT_MAX?`${rendered.slice(0,EXTERNAL_ACTION_PROMPT_MAX)}\u2026`:rendered}__name(describeExternalAction,"describeExternalAction");function assertExternalAgentSpawnPlatformSupported(platform=process.platform){if(platform==="win32"){throw new Error("External agents are not supported on Windows in this release: the executor spawn is POSIX-only. An npm-installed adapter resolves to a `.cmd` launcher that cannot be spawned without a shell, and the process-tree reaping is POSIX-specific. Run the external agent on macOS/Linux (or WSL). Windows support is a tracked follow-up.")}}__name(assertExternalAgentSpawnPlatformSupported,"assertExternalAgentSpawnPlatformSupported");function resolvePermissionMode(permissionMode,approvalMode){switch((approvalMode??permissionMode??"").trim().toLowerCase()){case"auto":case"acceptedits":case"auto-edit":return"acceptEdits";case"plan":return"plan";case"bypasspermissions":case"bypass":case"yolo":return"bypass";default:return"default"}}__name(resolvePermissionMode,"resolvePermissionMode");var POLICY_MODE_ALIASES={bypass:["bypassPermissions","yolo"],acceptEdits:["acceptEdits","auto-edit","auto"],plan:["plan"],default:["default"]};function selectPeerModeId(policy,availableModeIds){return POLICY_MODE_ALIASES[policy].find(id=>availableModeIds.includes(id))}__name(selectPeerModeId,"selectPeerModeId");function optionKindForOutcome(outcome){switch(outcome){case"proceed_once":case"proceed_once_and_switch_to_default":return"allow_once";case"proceed_always":case"proceed_always_server":case"proceed_always_tool":case"proceed_always_project":case"proceed_always_user":return"allow_always";case"modify_with_editor":case"cancel":case"restore_previous":return"reject_once";default:{const exhaustive=outcome;void exhaustive;return"reject_once"}}}__name(optionKindForOutcome,"optionKindForOutcome");function selectPermissionOption(options,outcome){if(outcome==="cancel")return void 0;if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}const kind=optionKindForOutcome(outcome);return(options.find(option=>option.kind===kind)??(kind==="allow_always"?options.find(option=>option.kind==="allow_once"):void 0)??options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectPermissionOption,"selectPermissionOption");function selectRejectOption(options){if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}return(options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectRejectOption,"selectRejectOption");function isExpectedExternalAgentCleanupExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited uncleanly during shutdown \(code=[^,]+, signal=[^)]+\)$/.test(error.message)}__name(isExpectedExternalAgentCleanupExit,"isExpectedExternalAgentCleanupExit");function isUnprovenExternalAgentTreeExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited before its initial process-tree snapshot completed$/.test(error.message)}__name(isUnprovenExternalAgentTreeExit,"isUnprovenExternalAgentTreeExit");var ExternalAgentTimeoutError=class extends Error{static{__name(this,"ExternalAgentTimeoutError")}constructor(timeoutMs){super(`External ACP operation timed out after ${timeoutMs}ms`);this.name="ExternalAgentTimeoutError"}};var AcpSubagentExecutor=class _AcpSubagentExecutor{constructor(params,child,emitter){this.params=params;this.child=child;this.emitter=emitter;this.coreView={getEventEmitter:__name(()=>emitter,"getEventEmitter"),modelConfig:{...params.modelConfig,model:externalModelLabel(params.spec.command)}};void child.exited.then(()=>this.fail(new Error(`external agent "${params.name}" exited`)),error=>this.fail(error))}static{__name(this,"AcpSubagentExecutor")}connection;sessionId="";finalText="";thoughtText="";terminateMode="ERROR";round=0;durationMs=0;turnStartedAt=0;toolCalls=0;toolSucceeded=0;toolFailed=0;executing=false;started=false;disposed=false;cancelled=false;disposePromise;provider;pendingPermissions=new Map;tools=new Map;toolNames=new Map;finishedTools=new Set;failure=new AbortController;coreView;static async create(params){assertExternalAgentSpawnPlatformSupported();if(params.runConfig.max_turns!==void 0){throw new Error("External ACP agents cannot enforce max_turns.")}const minutes=params.runConfig.max_time_minutes;if(minutes!==void 0&&(!Number.isFinite(minutes)||minutes<=0||minutes*6e4>2147483647)){throw new Error("External ACP max_time_minutes must be positive, finite, and within the Node timer range.")}const child=spawn(params.spec.command,params.spec.args??[],{cwd:params.runtimeContext.getTargetDir(),stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:true,env:sanitizeChildEnv(process.env)});const tracked=new ProcessRegistry().reserve().attach(child,{ownsProcessTree:true});const executor=new _AcpSubagentExecutor(params,tracked,params.eventEmitter??new AgentEventEmitter);child.on("error",error=>executor.fail(error));child.stdin.on("error",error=>executor.fail(error));child.stdout.on("error",error=>executor.fail(error));const forwarder=createStderrForwarder({prefix:`[external-agent ${params.name}] `});child.stderr.setEncoding("utf8");child.stderr.on("data",forwarder.onData);child.stderr.on("end",forwarder.onEnd);child.stderr.on("error",()=>{});try{executor.connection=new ClientSideConnection(()=>executor.buildClient(),ndJsonStream(Writable.toWeb(child.stdin),Readable.toWeb(child.stdout)));void executor.connection.closed.then(()=>executor.fail(new Error("External ACP connection closed")));await executor.wait(executor.connect(),INIT_TIMEOUT_MS);return executor}catch(error){await executor.dispose();throw error}}buildClient(){return{sessionUpdate:__name(async params=>this.onSessionUpdate(params),"sessionUpdate"),requestPermission:__name(params=>this.onRequestPermission(params),"requestPermission"),readTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/read_text_file")},"readTextFile"),writeTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/write_text_file")},"writeTextFile"),extMethod:__name(async method=>{throw RequestError.methodNotFound(method)},"extMethod"),extNotification:__name(async()=>{},"extNotification")}}async connect(){const initialized=await this.connection.initialize({protocolVersion:PROTOCOL_VERSION,clientCapabilities:{fs:{readTextFile:false,writeTextFile:false}}});if(initialized.protocolVersion!==PROTOCOL_VERSION){throw new Error("Unsupported external ACP protocol version")}const session=await this.connection.newSession({cwd:this.params.runtimeContext.getTargetDir(),mcpServers:[]});if(!session.sessionId)throw new Error("External ACP agent returned no sessionId");this.sessionId=session.sessionId;const policy=resolvePermissionMode(this.params.permissionMode,this.params.approvalMode);const availableIds=session.modes?.availableModes.map(mode=>mode.id)??[];const modeId=selectPeerModeId(policy,availableIds);if(!modeId){throw new Error(`External ACP agent does not advertise any mode for the host's ${policy} approval policy (advertised: ${availableIds.join(", ")||"none"})`)}await this.connection.setSessionMode({sessionId:this.sessionId,modeId})}fail(error){this.failure.abort(error);this.drainPermissions()}async wait(operation,timeoutMs,signal){let timer;let onFailure=__name(()=>{},"onFailure");let onAbort=__name(()=>{},"onAbort");const stopped=new Promise((_resolve,reject)=>{onFailure=__name(()=>reject(this.failure.signal.reason),"onFailure");onAbort=__name(()=>reject(signal?.reason??new Error("External agent cancelled")),"onAbort");this.failure.signal.addEventListener("abort",onFailure,{once:true});signal?.addEventListener("abort",onAbort,{once:true});if(this.failure.signal.aborted)onFailure();if(signal?.aborted)onAbort();if(timeoutMs!==void 0){timer=setTimeout(()=>reject(new ExternalAgentTimeoutError(timeoutMs)),timeoutMs)}});try{return await Promise.race([operation,stopped])}finally{clearTimeout(timer);this.failure.signal.removeEventListener("abort",onFailure);signal?.removeEventListener("abort",onAbort)}}async execute(context,signal,options={}){if(context.get("initial_messages_override")!==void 0){throw new Error("External ACP agents cannot import in-process conversation history")}const continuation=this.started;const system=continuation?"":renderSubagentSystemPrompt(this.params.promptConfig,context,this.params.runtimeContext);const task=String(context.get("task_prompt")??"Get Started!");const catalog=system?this.params.runtimeContext.getAutoMemoryContext():"";await this.runTurn([...system?[{type:"text",text:system}]:[],{type:"text",text:task},...catalog?[{type:"text",text:catalog}]:[]],signal,options,continuation?[task]:void 0)}async executeExternalInputs(inputs,signal,options={}){if(inputs.length===0)return;await this.runTurn(this.inputPrompt(inputs),signal,options,inputs)}inputPrompt(inputs){return inputs.map(input=>({type:"text",text:typeof input==="string"?input:input.text}))}emitInputs(inputs){for(const input of inputs){this.emitter.emit("external_message",{subagentId:this.id,kind:typeof input==="string"?"message":input.kind,text:typeof input==="string"?input:input.text,timestamp:Date.now()})}}async runTurn(prompt,signal,options={},inputs){if(this.executing)throw new Error("External ACP agents do not support concurrent turns");if(this.disposed||this.failure.signal.aborted)throw new Error("External ACP agent is closed");this.executing=true;this.started=true;this.cancelled=false;this.finalText="";this.thoughtText="";this.terminateMode="ERROR";if(options.resetStats!==false){this.round=this.durationMs=this.toolCalls=this.toolSucceeded=this.toolFailed=0}this.tools.clear();this.toolNames.clear();this.finishedTools.clear();this.turnStartedAt=Date.now();const timeoutMs=this.params.runConfig.max_time_minutes===void 0?void 0:this.params.runConfig.max_time_minutes*6e4;const cancel=__name(()=>{this.cancelled=true;this.drainPermissions();void this.connection.cancel({sessionId:this.sessionId}).catch(()=>{})},"cancel");signal?.addEventListener("abort",cancel,{once:true});let timedOut=false;try{this.emitter.emit("start",{subagentId:this.id,name:this.params.name,model:this.coreView.modelConfig.model,tools:[],timestamp:Date.now()});if(signal?.aborted){this.terminateMode="CANCELLED";return}const entryRound=this.round;let next=prompt;do{this.round++;const remaining=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remaining!==void 0&&remaining<=0){this.terminateMode="TIMEOUT";break}if(inputs&&this.round===entryRound+1)this.emitInputs(inputs);const result=await this.wait(this.connection.prompt({sessionId:this.sessionId,prompt:next}),remaining,signal);this.terminateMode=this.stopMode(result.stopReason);if(this.terminateMode!=="GOAL")break;if(signal?.aborted){this.terminateMode="CANCELLED";break}const remainingNext=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remainingNext!==void 0&&remainingNext<=0){this.terminateMode="TIMEOUT";break}const queued=this.provider?.()??[];if(queued.length===0)break;this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.finalText="";this.thoughtText="";this.emitInputs(queued);next=this.inputPrompt(queued)}while(!signal?.aborted);if(signal?.aborted)this.terminateMode="CANCELLED"}catch(error){timedOut=error instanceof ExternalAgentTimeoutError;this.terminateMode=signal?.aborted?"CANCELLED":timedOut?"TIMEOUT":"ERROR";if(this.emitter.rawListeners("error").length>0&&!signal?.aborted){this.emitter.emit("error",{subagentId:this.id,error:error instanceof Error?error.message:String(error),timestamp:Date.now()})}await this.dispose();if(!signal?.aborted&&!timedOut)throw error}finally{signal?.removeEventListener("abort",cancel);this.durationMs+=Date.now()-this.turnStartedAt;this.executing=false;this.drainPermissions();this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.flushOpenTools();this.emitter.emit("finish",{subagentId:this.id,terminateReason:this.terminateMode,rounds:this.round,totalDurationMs:this.durationMs,totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,timestamp:Date.now()})}}stopMode(reason){switch(reason){case"end_turn":return"GOAL";case"max_turn_requests":return"MAX_TURNS";case"cancelled":return"CANCELLED";case"refusal":return"ERROR";default:return"ERROR"}}get id(){return this.params.subagentId??this.params.name}getFinalText(){return this.finalText}getTerminateMode(){return this.terminateMode}getCore(){return this.coreView}setExternalMessageProvider(provider){this.provider=provider}getExecutionSummary(){return{rounds:this.round,totalDurationMs:this.durationMs+(this.executing?Date.now()-this.turnStartedAt:0),totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,successRate:this.toolCalls?this.toolSucceeded/this.toolCalls*100:0,inputTokens:0,outputTokens:0,thoughtTokens:0,cachedTokens:0,totalTokens:0,toolUsage:[]}}dispose(){this.disposed=true;this.fail(new Error("External ACP agent disposed"));return this.disposePromise??=this.child.terminate().catch(error=>{if(isUnprovenExternalAgentTreeExit(error)){const detail=error instanceof Error?error.message:String(error);debugLogger.warn(`External ACP agent process tree was not proven gone after disposal: ${detail}`);if(this.emitter.rawListeners("error").length>0){this.emitter.emit("error",{subagentId:this.id,error:`External agent process tree not proven gone after disposal: ${detail}`,timestamp:Date.now()})}return}if(!isExpectedExternalAgentCleanupExit(error))throw error})}drainPermissions(){for(const cancel of this.pendingPermissions.values())cancel();this.pendingPermissions.clear()}onSessionUpdate({sessionId,update}){if(sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted)return;switch(update.sessionUpdate){case"agent_message_chunk":case"agent_thought_chunk":{const thought=update.sessionUpdate==="agent_thought_chunk";const text=update.content.type==="text"?update.content.text:JSON.stringify(update.content);if(thought)this.thoughtText+=text;else this.finalText+=text;this.emitter.emit("stream_text",{subagentId:this.id,round:this.round,text,thought,timestamp:Date.now()});break}case"tool_call":this.updateTool(update);break;case"tool_call_update":this.updateTool(update);break;default:break}}updateTool(update){if(update._meta?.["toolLifecycle"]!==void 0&&update.status===void 0&&update.content===void 0)return;const callId=update.toolCallId;if(this.finishedTools.has(callId))return;const previous=this.tools.get(callId);const tool={toolCallId:callId,title:previous?.title??"External tool",...previous,...Object.fromEntries(Object.entries(update).filter(([,value])=>value!==null&&value!==void 0))};this.tools.set(callId,tool);const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;if(!previous){this.toolNames.set(callId,name);this.toolCalls++;this.emitter.emit("tool_call",{subagentId:this.id,round:this.round,callId,name,args:isRecord(tool.rawInput)?tool.rawInput:{input:tool.rawInput},description:tool.title,timestamp:Date.now()})}if(tool.status!=="completed"&&tool.status!=="failed")return;this.finishedTools.add(callId);this.tools.delete(callId);const success=tool.status==="completed";if(success)this.toolSucceeded++;else this.toolFailed++;this.toolNames.delete(callId);const response={input:tool.rawInput??null,toolName:reportedName,output:tool.rawOutput??null,content:tool.content??null,status:tool.status};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success,responseParts,resultDisplay:JSON.stringify(tool.rawOutput??tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}flushOpenTools(){for(const[callId,tool]of this.tools){const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;this.toolFailed++;const response={input:tool.rawInput??null,toolName:reportedName,output:null,content:tool.content??null,status:"failed"};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success:false,responseParts,resultDisplay:JSON.stringify(tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}this.tools.clear();this.toolNames.clear()}async onRequestPermission(params){const cancelled={outcome:{outcome:"cancelled"}};const runtime=this.params.runtimeContext;const callId=params.toolCall.toolCallId;const meta=params.toolCall._meta?.["claudeCode"];const name=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:params.toolCall.kind??"external_tool";if(params.sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted||this.pendingPermissions.has(callId)||params.options.length===0||new Set(params.options.map(option=>option.optionId)).size!==params.options.length)return cancelled;if(name.replaceAll("_","").toLowerCase()==="askuserquestion"||runtime.getShouldAvoidPermissionPrompts()||!runtime.isInteractive()&&!runtime.getExperimentalZedIntegration()&&runtime.getInputFormat()!=="stream-json"||this.emitter.rawListeners("tool_waiting_approval").length===0){const rejectOptionId=selectRejectOption(params.options);return rejectOptionId?{outcome:{outcome:"selected",optionId:rejectOptionId}}:cancelled}return new Promise(resolve=>{const finish=__name(optionId=>{if(this.pendingPermissions.get(callId)!==deny)return;this.pendingPermissions.delete(callId);resolve(optionId?{outcome:{outcome:"selected",optionId}}:cancelled)},"finish");const deny=__name(()=>finish(),"deny");this.pendingPermissions.set(callId,deny);try{this.emitter.emit("tool_waiting_approval",{subagentId:this.id,round:this.round,callId,name,args:isRecord(params.toolCall.rawInput)?params.toolCall.rawInput:{},description:params.toolCall.title??"External action",confirmationDetails:{type:"info",title:params.toolCall.title??"External action",prompt:describeExternalAction(params.toolCall),renderPromptAsPlainText:true,hideAlwaysAllow:true},respond:__name(async outcome=>finish(selectPermissionOption(params.options,outcome)??(outcome==="cancel"?selectRejectOption(params.options):void 0)),"respond"),timestamp:Date.now()})}catch{deny()}})}};var acpExternalAgentExecutor={create:__name(params=>AcpSubagentExecutor.create(params),"create")};export{externalModelLabel,describeExternalAction,assertExternalAgentSpawnPlatformSupported,resolvePermissionMode,selectPeerModeId,optionKindForOutcome,selectPermissionOption,selectRejectOption,isExpectedExternalAgentCleanupExit,isUnprovenExternalAgentTreeExit,acpExternalAgentExecutor};
3
+ import{ProcessRegistry}from"./chunk-ESSOEHTE.js";import{createStderrForwarder}from"./chunk-67JO7MT3.js";import{ClientSideConnection,PROTOCOL_VERSION,RequestError,ndJsonStream}from"./chunk-WSOEJTOC.js";import{AgentEventEmitter,renderSubagentSystemPrompt}from"./chunk-IFAUFERF.js";import{sanitizeChildEnv}from"./chunk-LFKUPU57.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{spawn}from"node:child_process";import{Readable,Writable}from"node:stream";init_esbuild_shims();var INIT_TIMEOUT_MS=1e4;var debugLogger=createDebugLogger("EXTERNAL_AGENT");function externalModelLabel(command){return`external-acp:${command.split(/[\\/]/).pop()??command}`}__name(externalModelLabel,"externalModelLabel");function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}__name(isRecord,"isRecord");var EXTERNAL_ACTION_PROMPT_MAX=300;function stripControlChars(value){let out="";for(const ch of value){const code=ch.codePointAt(0)??0;out+=code>=32&&code!==127&&!(code>=128&&code<=159)?ch:" "}return out}__name(stripControlChars,"stripControlChars");function describeExternalAction(toolCall){const title=stripControlChars(toolCall.title??toolCall.kind??"External action");const raw=toolCall.rawInput;if(!isRecord(raw))return title;const detail=stripControlChars(JSON.stringify(raw));const rendered=`${title}: ${detail}`;return rendered.length>EXTERNAL_ACTION_PROMPT_MAX?`${rendered.slice(0,EXTERNAL_ACTION_PROMPT_MAX)}\u2026`:rendered}__name(describeExternalAction,"describeExternalAction");function assertExternalAgentSpawnPlatformSupported(platform=process.platform){if(platform==="win32"){throw new Error("External agents are not supported on Windows in this release: the executor spawn is POSIX-only. An npm-installed adapter resolves to a `.cmd` launcher that cannot be spawned without a shell, and the process-tree reaping is POSIX-specific. Run the external agent on macOS/Linux (or WSL). Windows support is a tracked follow-up.")}}__name(assertExternalAgentSpawnPlatformSupported,"assertExternalAgentSpawnPlatformSupported");function resolvePermissionMode(permissionMode,approvalMode){switch((approvalMode??permissionMode??"").trim().toLowerCase()){case"auto":case"acceptedits":case"auto-edit":return"acceptEdits";case"plan":return"plan";case"bypasspermissions":case"bypass":case"yolo":return"bypass";default:return"default"}}__name(resolvePermissionMode,"resolvePermissionMode");var POLICY_MODE_ALIASES={bypass:["bypassPermissions","yolo"],acceptEdits:["acceptEdits","auto-edit","auto"],plan:["plan"],default:["default"]};function selectPeerModeId(policy,availableModeIds){return POLICY_MODE_ALIASES[policy].find(id=>availableModeIds.includes(id))}__name(selectPeerModeId,"selectPeerModeId");function optionKindForOutcome(outcome){switch(outcome){case"proceed_once":case"proceed_once_and_switch_to_default":return"allow_once";case"proceed_always":case"proceed_always_server":case"proceed_always_tool":case"proceed_always_project":case"proceed_always_user":return"allow_always";case"modify_with_editor":case"cancel":case"restore_previous":return"reject_once";default:{const exhaustive=outcome;void exhaustive;return"reject_once"}}}__name(optionKindForOutcome,"optionKindForOutcome");function selectPermissionOption(options,outcome){if(outcome==="cancel")return void 0;if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}const kind=optionKindForOutcome(outcome);return(options.find(option=>option.kind===kind)??(kind==="allow_always"?options.find(option=>option.kind==="allow_once"):void 0)??options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectPermissionOption,"selectPermissionOption");function selectRejectOption(options){if(new Set(options.map(option=>option.optionId)).size!==options.length){return void 0}return(options.find(option=>option.kind==="reject_once")??options.find(option=>option.kind==="reject_always"))?.optionId}__name(selectRejectOption,"selectRejectOption");function isExpectedExternalAgentCleanupExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited uncleanly during shutdown \(code=[^,]+, signal=[^)]+\)$/.test(error.message)}__name(isExpectedExternalAgentCleanupExit,"isExpectedExternalAgentCleanupExit");function isUnprovenExternalAgentTreeExit(error){return error instanceof Error&&/^ACP child pid=\d+ exited before its initial process-tree snapshot completed$/.test(error.message)}__name(isUnprovenExternalAgentTreeExit,"isUnprovenExternalAgentTreeExit");var ExternalAgentTimeoutError=class extends Error{static{__name(this,"ExternalAgentTimeoutError")}constructor(timeoutMs){super(`External ACP operation timed out after ${timeoutMs}ms`);this.name="ExternalAgentTimeoutError"}};var AcpSubagentExecutor=class _AcpSubagentExecutor{constructor(params,child,emitter){this.params=params;this.child=child;this.emitter=emitter;this.coreView={getEventEmitter:__name(()=>emitter,"getEventEmitter"),modelConfig:{...params.modelConfig,model:externalModelLabel(params.spec.command)}};void child.exited.then(()=>this.fail(new Error(`external agent "${params.name}" exited`)),error=>this.fail(error))}static{__name(this,"AcpSubagentExecutor")}connection;sessionId="";finalText="";thoughtText="";terminateMode="ERROR";round=0;durationMs=0;turnStartedAt=0;toolCalls=0;toolSucceeded=0;toolFailed=0;executing=false;started=false;disposed=false;cancelled=false;disposePromise;provider;pendingPermissions=new Map;tools=new Map;toolNames=new Map;finishedTools=new Set;failure=new AbortController;coreView;static async create(params){assertExternalAgentSpawnPlatformSupported();if(params.runConfig.max_turns!==void 0){throw new Error("External ACP agents cannot enforce max_turns.")}const minutes=params.runConfig.max_time_minutes;if(minutes!==void 0&&(!Number.isFinite(minutes)||minutes<=0||minutes*6e4>2147483647)){throw new Error("External ACP max_time_minutes must be positive, finite, and within the Node timer range.")}const child=spawn(params.spec.command,params.spec.args??[],{cwd:params.runtimeContext.getTargetDir(),stdio:["pipe","pipe","pipe"],detached:process.platform!=="win32",windowsHide:true,env:sanitizeChildEnv(process.env)});const tracked=new ProcessRegistry().reserve().attach(child,{ownsProcessTree:true});const executor=new _AcpSubagentExecutor(params,tracked,params.eventEmitter??new AgentEventEmitter);child.on("error",error=>executor.fail(error));child.stdin.on("error",error=>executor.fail(error));child.stdout.on("error",error=>executor.fail(error));const forwarder=createStderrForwarder({prefix:`[external-agent ${params.name}] `});child.stderr.setEncoding("utf8");child.stderr.on("data",forwarder.onData);child.stderr.on("end",forwarder.onEnd);child.stderr.on("error",()=>{});try{executor.connection=new ClientSideConnection(()=>executor.buildClient(),ndJsonStream(Writable.toWeb(child.stdin),Readable.toWeb(child.stdout)));void executor.connection.closed.then(()=>executor.fail(new Error("External ACP connection closed")));await executor.wait(executor.connect(),INIT_TIMEOUT_MS);return executor}catch(error){await executor.dispose();throw error}}buildClient(){return{sessionUpdate:__name(async params=>this.onSessionUpdate(params),"sessionUpdate"),requestPermission:__name(params=>this.onRequestPermission(params),"requestPermission"),readTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/read_text_file")},"readTextFile"),writeTextFile:__name(async()=>{throw RequestError.methodNotFound("fs/write_text_file")},"writeTextFile"),extMethod:__name(async method=>{throw RequestError.methodNotFound(method)},"extMethod"),extNotification:__name(async()=>{},"extNotification")}}async connect(){const initialized=await this.connection.initialize({protocolVersion:PROTOCOL_VERSION,clientCapabilities:{fs:{readTextFile:false,writeTextFile:false}}});if(initialized.protocolVersion!==PROTOCOL_VERSION){throw new Error("Unsupported external ACP protocol version")}const session=await this.connection.newSession({cwd:this.params.runtimeContext.getTargetDir(),mcpServers:[]});if(!session.sessionId)throw new Error("External ACP agent returned no sessionId");this.sessionId=session.sessionId;const policy=resolvePermissionMode(this.params.permissionMode,this.params.approvalMode);const availableIds=session.modes?.availableModes.map(mode=>mode.id)??[];const modeId=selectPeerModeId(policy,availableIds);if(!modeId){throw new Error(`External ACP agent does not advertise any mode for the host's ${policy} approval policy (advertised: ${availableIds.join(", ")||"none"})`)}await this.connection.setSessionMode({sessionId:this.sessionId,modeId})}fail(error){this.failure.abort(error);this.drainPermissions()}async wait(operation,timeoutMs,signal){let timer;let onFailure=__name(()=>{},"onFailure");let onAbort=__name(()=>{},"onAbort");const stopped=new Promise((_resolve,reject)=>{onFailure=__name(()=>reject(this.failure.signal.reason),"onFailure");onAbort=__name(()=>reject(signal?.reason??new Error("External agent cancelled")),"onAbort");this.failure.signal.addEventListener("abort",onFailure,{once:true});signal?.addEventListener("abort",onAbort,{once:true});if(this.failure.signal.aborted)onFailure();if(signal?.aborted)onAbort();if(timeoutMs!==void 0){timer=setTimeout(()=>reject(new ExternalAgentTimeoutError(timeoutMs)),timeoutMs)}});try{return await Promise.race([operation,stopped])}finally{clearTimeout(timer);this.failure.signal.removeEventListener("abort",onFailure);signal?.removeEventListener("abort",onAbort)}}async execute(context,signal,options={}){if(context.get("initial_messages_override")!==void 0){throw new Error("External ACP agents cannot import in-process conversation history")}const continuation=this.started;const system=continuation?"":renderSubagentSystemPrompt(this.params.promptConfig,context,this.params.runtimeContext);const task=String(context.get("task_prompt")??"Get Started!");const catalog=system?this.params.runtimeContext.getAutoMemoryContext():"";await this.runTurn([...system?[{type:"text",text:system}]:[],{type:"text",text:task},...catalog?[{type:"text",text:catalog}]:[]],signal,options,continuation?[task]:void 0)}async executeExternalInputs(inputs,signal,options={}){if(inputs.length===0)return;await this.runTurn(this.inputPrompt(inputs),signal,options,inputs)}inputPrompt(inputs){return inputs.map(input=>({type:"text",text:typeof input==="string"?input:input.text}))}emitInputs(inputs){for(const input of inputs){this.emitter.emit("external_message",{subagentId:this.id,kind:typeof input==="string"?"message":input.kind,text:typeof input==="string"?input:input.text,timestamp:Date.now()})}}async runTurn(prompt,signal,options={},inputs){if(this.executing)throw new Error("External ACP agents do not support concurrent turns");if(this.disposed||this.failure.signal.aborted)throw new Error("External ACP agent is closed");this.executing=true;this.started=true;this.cancelled=false;this.finalText="";this.thoughtText="";this.terminateMode="ERROR";if(options.resetStats!==false){this.round=this.durationMs=this.toolCalls=this.toolSucceeded=this.toolFailed=0}this.tools.clear();this.toolNames.clear();this.finishedTools.clear();this.turnStartedAt=Date.now();const timeoutMs=this.params.runConfig.max_time_minutes===void 0?void 0:this.params.runConfig.max_time_minutes*6e4;const cancel=__name(()=>{this.cancelled=true;this.drainPermissions();void this.connection.cancel({sessionId:this.sessionId}).catch(()=>{})},"cancel");signal?.addEventListener("abort",cancel,{once:true});let timedOut=false;try{this.emitter.emit("start",{subagentId:this.id,name:this.params.name,model:this.coreView.modelConfig.model,tools:[],timestamp:Date.now()});if(signal?.aborted){this.terminateMode="CANCELLED";return}const entryRound=this.round;let next=prompt;do{this.round++;const remaining=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remaining!==void 0&&remaining<=0){this.terminateMode="TIMEOUT";break}if(inputs&&this.round===entryRound+1)this.emitInputs(inputs);const result=await this.wait(this.connection.prompt({sessionId:this.sessionId,prompt:next}),remaining,signal);this.terminateMode=this.stopMode(result.stopReason);if(this.terminateMode!=="GOAL")break;if(signal?.aborted){this.terminateMode="CANCELLED";break}const remainingNext=timeoutMs===void 0?void 0:Math.max(0,timeoutMs-this.durationMs-(Date.now()-this.turnStartedAt));if(remainingNext!==void 0&&remainingNext<=0){this.terminateMode="TIMEOUT";break}const queued=this.provider?.()??[];if(queued.length===0)break;this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.finalText="";this.thoughtText="";this.emitInputs(queued);next=this.inputPrompt(queued)}while(!signal?.aborted);if(signal?.aborted)this.terminateMode="CANCELLED"}catch(error){timedOut=error instanceof ExternalAgentTimeoutError;this.terminateMode=signal?.aborted?"CANCELLED":timedOut?"TIMEOUT":"ERROR";if(this.emitter.rawListeners("error").length>0&&!signal?.aborted){this.emitter.emit("error",{subagentId:this.id,error:error instanceof Error?error.message:String(error),timestamp:Date.now()})}await this.dispose();if(!signal?.aborted&&!timedOut)throw error}finally{signal?.removeEventListener("abort",cancel);this.durationMs+=Date.now()-this.turnStartedAt;this.executing=false;this.drainPermissions();this.emitter.emit("round_text",{subagentId:this.id,round:this.round,text:this.finalText,thoughtText:this.thoughtText,timestamp:Date.now()});this.flushOpenTools();this.emitter.emit("finish",{subagentId:this.id,terminateReason:this.terminateMode,rounds:this.round,totalDurationMs:this.durationMs,totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,timestamp:Date.now()})}}stopMode(reason){switch(reason){case"end_turn":return"GOAL";case"max_turn_requests":return"MAX_TURNS";case"cancelled":return"CANCELLED";case"refusal":return"ERROR";default:return"ERROR"}}get id(){return this.params.subagentId??this.params.name}getFinalText(){return this.finalText}getTerminateMode(){return this.terminateMode}getCore(){return this.coreView}setExternalMessageProvider(provider){this.provider=provider}getExecutionSummary(){return{rounds:this.round,totalDurationMs:this.durationMs+(this.executing?Date.now()-this.turnStartedAt:0),totalToolCalls:this.toolCalls,successfulToolCalls:this.toolSucceeded,failedToolCalls:this.toolFailed,successRate:this.toolCalls?this.toolSucceeded/this.toolCalls*100:0,inputTokens:0,outputTokens:0,thoughtTokens:0,cachedTokens:0,totalTokens:0,toolUsage:[]}}dispose(){this.disposed=true;this.fail(new Error("External ACP agent disposed"));return this.disposePromise??=this.child.terminate().catch(error=>{if(isUnprovenExternalAgentTreeExit(error)){const detail=error instanceof Error?error.message:String(error);debugLogger.warn(`External ACP agent process tree was not proven gone after disposal: ${detail}`);if(this.emitter.rawListeners("error").length>0){this.emitter.emit("error",{subagentId:this.id,error:`External agent process tree not proven gone after disposal: ${detail}`,timestamp:Date.now()})}return}if(!isExpectedExternalAgentCleanupExit(error))throw error})}drainPermissions(){for(const cancel of this.pendingPermissions.values())cancel();this.pendingPermissions.clear()}onSessionUpdate({sessionId,update}){if(sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted)return;switch(update.sessionUpdate){case"agent_message_chunk":case"agent_thought_chunk":{const thought=update.sessionUpdate==="agent_thought_chunk";const text=update.content.type==="text"?update.content.text:JSON.stringify(update.content);if(thought)this.thoughtText+=text;else this.finalText+=text;this.emitter.emit("stream_text",{subagentId:this.id,round:this.round,text,thought,timestamp:Date.now()});break}case"tool_call":this.updateTool(update);break;case"tool_call_update":this.updateTool(update);break;default:break}}updateTool(update){if(update._meta?.["toolLifecycle"]!==void 0&&update.status===void 0&&update.content===void 0)return;const callId=update.toolCallId;if(this.finishedTools.has(callId))return;const previous=this.tools.get(callId);const tool={toolCallId:callId,title:previous?.title??"External tool",...previous,...Object.fromEntries(Object.entries(update).filter(([,value])=>value!==null&&value!==void 0))};this.tools.set(callId,tool);const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;if(!previous){this.toolNames.set(callId,name);this.toolCalls++;this.emitter.emit("tool_call",{subagentId:this.id,round:this.round,callId,name,args:isRecord(tool.rawInput)?tool.rawInput:{input:tool.rawInput},description:tool.title,timestamp:Date.now()})}if(tool.status!=="completed"&&tool.status!=="failed")return;this.finishedTools.add(callId);this.tools.delete(callId);const success=tool.status==="completed";if(success)this.toolSucceeded++;else this.toolFailed++;this.toolNames.delete(callId);const response={input:tool.rawInput??null,toolName:reportedName,output:tool.rawOutput??null,content:tool.content??null,status:tool.status};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success,responseParts,resultDisplay:JSON.stringify(tool.rawOutput??tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}flushOpenTools(){for(const[callId,tool]of this.tools){const meta=tool._meta?.["claudeCode"];const reportedName=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:tool.kind??"external_tool";const name=this.toolNames.get(callId)??reportedName;this.toolFailed++;const response={input:tool.rawInput??null,toolName:reportedName,output:null,content:tool.content??null,status:"failed"};const responseParts=[{functionResponse:{id:callId,name,response}}];this.emitter.emit("tool_result",{subagentId:this.id,round:this.round,callId,name,success:false,responseParts,resultDisplay:JSON.stringify(tool.content??null),timestamp:Date.now()});this.emitter.emit("tool_responses_finalized",{subagentId:this.id,round:this.round,responses:[{callId,responseParts}],timestamp:Date.now()})}this.tools.clear();this.toolNames.clear()}async onRequestPermission(params){const cancelled={outcome:{outcome:"cancelled"}};const runtime=this.params.runtimeContext;const callId=params.toolCall.toolCallId;const meta=params.toolCall._meta?.["claudeCode"];const name=isRecord(meta)&&typeof meta["toolName"]==="string"?meta["toolName"]:params.toolCall.kind??"external_tool";if(params.sessionId!==this.sessionId||!this.executing||this.cancelled||this.disposed||this.failure.signal.aborted||this.pendingPermissions.has(callId)||params.options.length===0||new Set(params.options.map(option=>option.optionId)).size!==params.options.length)return cancelled;if(name.replaceAll("_","").toLowerCase()==="askuserquestion"||runtime.getShouldAvoidPermissionPrompts()||!runtime.isInteractive()&&!runtime.getExperimentalZedIntegration()&&runtime.getInputFormat()!=="stream-json"||this.emitter.rawListeners("tool_waiting_approval").length===0){const rejectOptionId=selectRejectOption(params.options);return rejectOptionId?{outcome:{outcome:"selected",optionId:rejectOptionId}}:cancelled}return new Promise(resolve=>{const finish=__name(optionId=>{if(this.pendingPermissions.get(callId)!==deny)return;this.pendingPermissions.delete(callId);resolve(optionId?{outcome:{outcome:"selected",optionId}}:cancelled)},"finish");const deny=__name(()=>finish(),"deny");this.pendingPermissions.set(callId,deny);try{this.emitter.emit("tool_waiting_approval",{subagentId:this.id,round:this.round,callId,name,args:isRecord(params.toolCall.rawInput)?params.toolCall.rawInput:{},description:params.toolCall.title??"External action",confirmationDetails:{type:"info",title:params.toolCall.title??"External action",prompt:describeExternalAction(params.toolCall),renderPromptAsPlainText:true,hideAlwaysAllow:true},respond:__name(async outcome=>finish(selectPermissionOption(params.options,outcome)??(outcome==="cancel"?selectRejectOption(params.options):void 0)),"respond"),timestamp:Date.now()})}catch{deny()}})}};var acpExternalAgentExecutor={create:__name(params=>AcpSubagentExecutor.create(params),"create")};export{externalModelLabel,describeExternalAction,assertExternalAgentSpawnPlatformSupported,resolvePermissionMode,selectPeerModeId,optionKindForOutcome,selectPermissionOption,selectRejectOption,isExpectedExternalAgentCleanupExit,isUnprovenExternalAgentTreeExit,acpExternalAgentExecutor};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Qwen
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{getErrorMessage}from"./chunk-AII4DN7M.js";import{extensionToOutputString,getExtensionManager}from"./chunk-43E3XC2W.js";import{loadSettings}from"./chunk-JV5FCFG4.js";import{initializeI18n,resolveLanguageSetting,t}from"./chunk-4IE26CIN.js";import{writeStderrLine,writeStdoutLine}from"./chunk-SLPJ4OII.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();async function handleList(){try{const settings=loadSettings();await initializeI18n(resolveLanguageSetting(settings.merged.general?.language));const extensionManager=await getExtensionManager();const extensions=extensionManager.getLoadedExtensions();if(!extensions||extensions.length===0){writeStdoutLine(t("No extensions installed."));return}writeStdoutLine(extensions.map((extension,_)=>extensionToOutputString(extension,extensionManager,process.cwd())).join("\n\n"))}catch(error){writeStderrLine(getErrorMessage(error));process.exit(1)}}__name(handleList,"handleList");var listCommand={command:"list",describe:t("Lists installed extensions."),builder:__name(yargs=>yargs,"builder"),handler:__name(async()=>{await handleList()},"handler")};export{handleList,listCommand};
3
+ import{getErrorMessage}from"./chunk-FBV4LUUL.js";import{extensionToOutputString,getExtensionManager}from"./chunk-YQEOEO5V.js";import{loadSettings}from"./chunk-4WFWZWR3.js";import{initializeI18n,resolveLanguageSetting,t}from"./chunk-4IE26CIN.js";import{writeStderrLine,writeStdoutLine}from"./chunk-SLPJ4OII.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();async function handleList(){try{const settings=loadSettings();await initializeI18n(resolveLanguageSetting(settings.merged.general?.language));const extensionManager=await getExtensionManager();const extensions=extensionManager.getLoadedExtensions();if(!extensions||extensions.length===0){writeStdoutLine(t("No extensions installed."));return}writeStdoutLine(extensions.map((extension,_)=>extensionToOutputString(extension,extensionManager,process.cwd())).join("\n\n"))}catch(error){writeStderrLine(getErrorMessage(error));process.exit(1)}}__name(handleList,"handleList");var listCommand={command:"list",describe:t("Lists installed extensions."),builder:__name(yargs=>yargs,"builder"),handler:__name(async()=>{await handleList()},"handler")};export{handleList,listCommand};
4
4
  /**
5
5
  * @license
6
6
  * Copyright 2025 Google LLC
@@ -1,7 +1,7 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
3
  import{DEFAULT_QWEN_MODEL}from"./chunk-4ZBZL23U.js";import{preloadRuntimeFetchModule}from"./chunk-ZZZAYAJW.js";import{init_esbuild_shims}from"./chunk-VKDAXTCZ.js";import{__name}from"./chunk-KBWJGX7I.js";init_esbuild_shims();function getDefaultApiKeyEnvVar(authType){switch(authType){case"openai":case"openai-responses":return"OPENAI_API_KEY";case"anthropic":return"ANTHROPIC_API_KEY";case"gemini":return"GEMINI_API_KEY";case"vertex-ai":return"GOOGLE_API_KEY";default:return"API_KEY"}}__name(getDefaultApiKeyEnvVar,"getDefaultApiKeyEnvVar");function getDefaultModelEnvVar(authType){switch(authType){case"openai":case"openai-responses":return"OPENAI_MODEL";case"anthropic":return"ANTHROPIC_MODEL";case"gemini":return"GEMINI_MODEL";case"vertex-ai":return"GOOGLE_MODEL";default:return"MODEL"}}__name(getDefaultModelEnvVar,"getDefaultModelEnvVar");var VERTEX_ADC_HINT=" Alternatively, set GOOGLE_CLOUD_PROJECT to authenticate with Application Default Credentials instead of an API key.";function adcHint(authType,explicitEnvKey){return authType==="vertex-ai"&&!explicitEnvKey?VERTEX_ADC_HINT:""}__name(adcHint,"adcHint");var ModelConfigError=class extends Error{static{__name(this,"ModelConfigError")}constructor(message){super(message);this.name=new.target.name;Object.setPrototypeOf(this,new.target.prototype)}};var StrictMissingCredentialsError=class extends ModelConfigError{static{__name(this,"StrictMissingCredentialsError")}code="STRICT_MISSING_CREDENTIALS";constructor(authType,model,envKey){const providerKey=authType||"(unknown)";const modelName=model||"(unknown)";super(`Missing credentials for modelProviders model '${modelName}'. `+(envKey?`Current configured envKey: '${envKey}'. Set that environment variable, or update modelProviders.${providerKey}[].envKey.`:`Configure modelProviders.${providerKey}[].envKey and set that environment variable.`)+adcHint(authType,envKey))}};var StrictMissingModelIdError=class extends ModelConfigError{static{__name(this,"StrictMissingModelIdError")}code="STRICT_MISSING_MODEL_ID";constructor(authType){super(`Missing model id for strict modelProviders resolution (authType: ${authType}).`)}};var MissingApiKeyError=class extends ModelConfigError{static{__name(this,"MissingApiKeyError")}code="MISSING_API_KEY";constructor(params){super(`Missing API key for ${params.authType} auth. Current model: '${params.model||"(unknown)"}', baseUrl: '${params.baseUrl||"(default)"}'. Provide an API key via settings (security.auth.apiKey), or set the environment variable '${params.envKey}'.`+adcHint(params.authType,params.explicitEnvKey))}};var MissingModelError=class extends ModelConfigError{static{__name(this,"MissingModelError")}code="MISSING_MODEL";constructor(params){super(`Missing model for ${params.authType} auth. Set the environment variable '${params.envKey}'.`)}};var MissingBaseUrlError=class extends ModelConfigError{static{__name(this,"MissingBaseUrlError")}code="MISSING_BASE_URL";constructor(params){super(`Missing baseUrl for modelProviders model '${params.model||"(unknown)"}'. Configure modelProviders.${params.authType||"(unknown)"}[].baseUrl.`)}};var MissingAnthropicBaseUrlEnvError=class extends ModelConfigError{static{__name(this,"MissingAnthropicBaseUrlEnvError")}code="MISSING_ANTHROPIC_BASE_URL_ENV";constructor(){super("ANTHROPIC_BASE_URL environment variable not found.")}};init_esbuild_shims();var DEFAULT_QWEN_EMBEDDING_MODEL="text-embedding-v4";var MAINLINE_CODER_MODEL="qwen3.7-max";init_esbuild_shims();var MODEL_GENERATION_CONFIG_FIELDS=["samplingParams","timeout","streamIdleTimeoutMs","maxRetries","retryInitialDelayMs","retryMaxDelayMs","retryErrorCodes","enableCacheControl","enableRequestMetadata","forceGlobalCacheScope","cacheRetention","cacheRetentionByBlock","schemaCompliance","reasoning","contextWindowSize","customHeaders","extra_body","thinkingMandatory","modalities","splitToolMedia","toolResultContentFormat"];var CREDENTIAL_FIELDS=["model","apiKey","apiKeyEnvKey","baseUrl"];var PROVIDER_SOURCED_FIELDS=[...CREDENTIAL_FIELDS,...MODEL_GENERATION_CONFIG_FIELDS];var AUTH_ENV_MAPPINGS={openai:{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL","QWEN_MODEL"]},"openai-responses":{apiKey:["OPENAI_API_KEY"],baseUrl:["OPENAI_BASE_URL"],model:["OPENAI_MODEL"]},anthropic:{apiKey:["ANTHROPIC_API_KEY"],baseUrl:["ANTHROPIC_BASE_URL"],model:["ANTHROPIC_MODEL"]},gemini:{apiKey:["GEMINI_API_KEY"],baseUrl:[],model:["GEMINI_MODEL"]},"vertex-ai":{apiKey:["GOOGLE_API_KEY"],baseUrl:[],model:["GOOGLE_MODEL"]},"qwen-oauth":{apiKey:[],baseUrl:[],model:[]}};var DEFAULT_MODELS={openai:MAINLINE_CODER_MODEL,"qwen-oauth":DEFAULT_QWEN_MODEL};var QWEN_OAUTH_MODELS=[{id:"coder-model",name:"coder-model",description:"Qwen 3.7 Max \u2014 efficient hybrid model with leading coding performance",capabilities:{vision:true}}];var QWEN_OAUTH_ALLOWED_MODELS=QWEN_OAUTH_MODELS.map(model=>model.id);init_esbuild_shims();function setSource(sources,path,source){sources[path]=source}__name(setSource,"setSource");function getSeedSource(seed,path){return seed?.[path]}__name(getSeedSource,"getSeedSource");function resolveContentGeneratorConfigWithSources(config,authType,generationConfig,seedSources,options){const sources={...seedSources||{}};const strictModelProvider=options?.strictModelProvider===true;const newContentGeneratorConfig={...generationConfig||{},authType,reasoningSnapshot:generationConfig?.reasoningSnapshot??config?.getReasoningSnapshot?.(),reasoningRouteBaseUrl:generationConfig&&"reasoningRouteBaseUrl"in generationConfig?generationConfig.reasoningRouteBaseUrl:config?.getCurrentModelRegistryBaseUrl?.(),proxy:config?.getProxy()};setSource(sources,"authType",{kind:"computed",detail:"provided by caller"});if(config?.getProxy()){setSource(sources,"proxy",{kind:"computed",detail:"Config.getProxy()"})}const seedOrUnknown=__name(path=>getSeedSource(seedSources,path)??{kind:"unknown"},"seedOrUnknown");for(const field of PROVIDER_SOURCED_FIELDS){if(generationConfig&&field in generationConfig&&!sources[field]){setSource(sources,field,seedOrUnknown(field))}}const validation=validateModelConfig(newContentGeneratorConfig,strictModelProvider);if(!validation.valid){throw new Error(validation.errors.map(e=>e.message).join("\n"))}return{config:newContentGeneratorConfig,sources}}__name(resolveContentGeneratorConfigWithSources,"resolveContentGeneratorConfigWithSources");var VERTEX_PROJECT_ENV_VAR="GOOGLE_CLOUD_PROJECT";function hasVertexProjectConfigured(lookup=key=>process.env[key]){return!!lookup(VERTEX_PROJECT_ENV_VAR)?.trim()}__name(hasVertexProjectConfigured,"hasVertexProjectConfigured");function usesVertexApplicationDefaultCredentials(config){return config.authType==="vertex-ai"&&!config.apiKeyEnvKey&&hasVertexProjectConfigured()}__name(usesVertexApplicationDefaultCredentials,"usesVertexApplicationDefaultCredentials");function validateModelConfig(config,isStrictModelProvider=false){const errors=[];if(config.authType==="qwen-oauth"){return{valid:true,errors:[]}}if(!config.apiKey&&!usesVertexApplicationDefaultCredentials(config)){if(isStrictModelProvider){errors.push(new StrictMissingCredentialsError(config.authType,config.model,config.apiKeyEnvKey))}else{const envKey=config.apiKeyEnvKey||getDefaultApiKeyEnvVar(config.authType);errors.push(new MissingApiKeyError({authType:config.authType,model:config.model,baseUrl:config.baseUrl,envKey,explicitEnvKey:config.apiKeyEnvKey}))}}if(!config.model){if(isStrictModelProvider){errors.push(new StrictMissingModelIdError(config.authType))}else{const envKey=getDefaultModelEnvVar(config.authType);errors.push(new MissingModelError({authType:config.authType,envKey}))}}if(config.authType==="anthropic"&&!config.baseUrl){if(isStrictModelProvider){errors.push(new MissingBaseUrlError({authType:config.authType,model:config.model}))}else if(config.authType==="anthropic"){errors.push(new MissingAnthropicBaseUrlEnvError)}}return{valid:errors.length===0,errors}}__name(validateModelConfig,"validateModelConfig");function getModuleNotFoundError(error){let current=error;while(current instanceof Error){if("code"in current&&current.code==="ERR_MODULE_NOT_FOUND"){return current}current=current.cause}return void 0}__name(getModuleNotFoundError,"getModuleNotFoundError");function wrapProviderLoadError(error,authType){const moduleNotFoundError=getModuleNotFoundError(error);if(!moduleNotFoundError){return error}return new Error(`Qwen Code was updated in the background and needs to be restarted.
4
- Please exit and restart Qwen Code to use the '${authType}' provider.`,{cause:moduleNotFoundError})}__name(wrapProviderLoadError,"wrapProviderLoadError");var LazyContentGenerator=class{constructor(loader){this.loader=loader}static{__name(this,"LazyContentGenerator")}generatorPromise;preloadedOnly=false;getGenerator(){this.generatorPromise??=this.loader();return this.generatorPromise}getGeneratorForUse(){this.preloadedOnly=false;return this.getGenerator()}preload(){if(!this.generatorPromise){this.preloadedOnly=true}return this.getGenerator()}resetPreload(){if(!this.preloadedOnly)return;this.preloadedOnly=false;this.generatorPromise=void 0}async generateContent(request,userPromptId){return(await this.getGeneratorForUse()).generateContent(request,userPromptId)}async generateContentStream(request,userPromptId){return(await this.getGeneratorForUse()).generateContentStream(request,userPromptId)}async embedContent(request){return(await this.getGeneratorForUse()).embedContent(request)}};async function preloadContentGenerator(generator){if(generator instanceof LazyContentGenerator){await generator.preload()}}__name(preloadContentGenerator,"preloadContentGenerator");function resetPreloadedContentGenerator(generator){if(generator instanceof LazyContentGenerator){generator.resetPreload()}}__name(resetPreloadedContentGenerator,"resetPreloadedContentGenerator");async function createContentGenerator(generatorConfig,config,isInitialAuth){const validation=validateModelConfig(generatorConfig,false);if(!validation.valid){throw new Error(validation.errors.map(e=>e.message).join("\n"))}const authType=generatorConfig.authType;if(!authType){throw new Error("ContentGeneratorConfig must have an authType")}await preloadRuntimeFetchModule();let loadBaseGenerator;try{if(authType==="openai"){loadBaseGenerator=__name(async()=>{const{createOpenAIContentGenerator}=await import("./openaiContentGenerator-RT4S6OYR.js");return createOpenAIContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else if(authType==="openai-responses"){loadBaseGenerator=__name(async()=>{const{createOpenAIResponsesContentGenerator}=await import("./openaiResponsesContentGenerator-JD4ZBCAL.js");return createOpenAIResponsesContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else if(authType==="qwen-oauth"){const{getQwenOAuthClient:getQwenOauthClient}=await import("./qwenOAuth2-MQZYNYWO.js");try{const qwenClient=await getQwenOauthClient(config,isInitialAuth?{requireCachedCredentials:true}:void 0);loadBaseGenerator=__name(async()=>{const{QwenContentGenerator}=await import("./qwenContentGenerator-6SGQI4ES.js");return new QwenContentGenerator(qwenClient,generatorConfig,config)},"loadBaseGenerator")}catch(error){if(getModuleNotFoundError(error)){throw error}throw new Error(error instanceof Error?error.message:String(error))}}else if(authType==="anthropic"){loadBaseGenerator=__name(async()=>{const{createAnthropicContentGenerator}=await import("./anthropicContentGenerator-6I25Q3Y6.js");return createAnthropicContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else if(authType==="gemini"||authType==="vertex-ai"){loadBaseGenerator=__name(async()=>{const{createLlmContentGenerator}=await import("./llm-content-generator-6RPOZ2YR.js");return createLlmContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else{throw new Error(`Error creating contentGenerator: Unsupported authType: ${authType}`)}}catch(error){throw wrapProviderLoadError(error,authType)}return new LazyContentGenerator(async()=>{try{const[baseGenerator,{LoggingContentGenerator}]=await Promise.all([loadBaseGenerator(),import("./loggingContentGenerator-AOKEDXK6.js")]);return new LoggingContentGenerator(baseGenerator,config,generatorConfig)}catch(error){throw wrapProviderLoadError(error,authType)}})}__name(createContentGenerator,"createContentGenerator");export{getDefaultApiKeyEnvVar,VERTEX_ADC_HINT,DEFAULT_QWEN_EMBEDDING_MODEL,MAINLINE_CODER_MODEL,MODEL_GENERATION_CONFIG_FIELDS,PROVIDER_SOURCED_FIELDS,AUTH_ENV_MAPPINGS,DEFAULT_MODELS,QWEN_OAUTH_MODELS,QWEN_OAUTH_ALLOWED_MODELS,resolveContentGeneratorConfigWithSources,hasVertexProjectConfigured,preloadContentGenerator,resetPreloadedContentGenerator,createContentGenerator};
4
+ Please exit and restart Qwen Code to use the '${authType}' provider.`,{cause:moduleNotFoundError})}__name(wrapProviderLoadError,"wrapProviderLoadError");var LazyContentGenerator=class{constructor(loader){this.loader=loader}static{__name(this,"LazyContentGenerator")}generatorPromise;preloadedOnly=false;getGenerator(){this.generatorPromise??=this.loader();return this.generatorPromise}getGeneratorForUse(){this.preloadedOnly=false;return this.getGenerator()}preload(){if(!this.generatorPromise){this.preloadedOnly=true}return this.getGenerator()}resetPreload(){if(!this.preloadedOnly)return;this.preloadedOnly=false;this.generatorPromise=void 0}async generateContent(request,userPromptId){return(await this.getGeneratorForUse()).generateContent(request,userPromptId)}async generateContentStream(request,userPromptId){return(await this.getGeneratorForUse()).generateContentStream(request,userPromptId)}async embedContent(request){return(await this.getGeneratorForUse()).embedContent(request)}};async function preloadContentGenerator(generator){if(generator instanceof LazyContentGenerator){await generator.preload()}}__name(preloadContentGenerator,"preloadContentGenerator");function resetPreloadedContentGenerator(generator){if(generator instanceof LazyContentGenerator){generator.resetPreload()}}__name(resetPreloadedContentGenerator,"resetPreloadedContentGenerator");async function createContentGenerator(generatorConfig,config,isInitialAuth){const validation=validateModelConfig(generatorConfig,false);if(!validation.valid){throw new Error(validation.errors.map(e=>e.message).join("\n"))}const authType=generatorConfig.authType;if(!authType){throw new Error("ContentGeneratorConfig must have an authType")}await preloadRuntimeFetchModule();let loadBaseGenerator;try{if(authType==="openai"){loadBaseGenerator=__name(async()=>{const{createOpenAIContentGenerator}=await import("./openaiContentGenerator-KNZTYVNK.js");return createOpenAIContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else if(authType==="openai-responses"){loadBaseGenerator=__name(async()=>{const{createOpenAIResponsesContentGenerator}=await import("./openaiResponsesContentGenerator-G7GRJXES.js");return createOpenAIResponsesContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else if(authType==="qwen-oauth"){const{getQwenOAuthClient:getQwenOauthClient}=await import("./qwenOAuth2-MQZYNYWO.js");try{const qwenClient=await getQwenOauthClient(config,isInitialAuth?{requireCachedCredentials:true}:void 0);loadBaseGenerator=__name(async()=>{const{QwenContentGenerator}=await import("./qwenContentGenerator-A7WREYLV.js");return new QwenContentGenerator(qwenClient,generatorConfig,config)},"loadBaseGenerator")}catch(error){if(getModuleNotFoundError(error)){throw error}throw new Error(error instanceof Error?error.message:String(error))}}else if(authType==="anthropic"){loadBaseGenerator=__name(async()=>{const{createAnthropicContentGenerator}=await import("./anthropicContentGenerator-MDETV5LU.js");return createAnthropicContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else if(authType==="gemini"||authType==="vertex-ai"){loadBaseGenerator=__name(async()=>{const{createLlmContentGenerator}=await import("./llm-content-generator-MJPR2TWC.js");return createLlmContentGenerator(generatorConfig,config)},"loadBaseGenerator")}else{throw new Error(`Error creating contentGenerator: Unsupported authType: ${authType}`)}}catch(error){throw wrapProviderLoadError(error,authType)}return new LazyContentGenerator(async()=>{try{const[baseGenerator,{LoggingContentGenerator}]=await Promise.all([loadBaseGenerator(),import("./loggingContentGenerator-722BJL7T.js")]);return new LoggingContentGenerator(baseGenerator,config,generatorConfig)}catch(error){throw wrapProviderLoadError(error,authType)}})}__name(createContentGenerator,"createContentGenerator");export{getDefaultApiKeyEnvVar,VERTEX_ADC_HINT,DEFAULT_QWEN_EMBEDDING_MODEL,MAINLINE_CODER_MODEL,MODEL_GENERATION_CONFIG_FIELDS,PROVIDER_SOURCED_FIELDS,AUTH_ENV_MAPPINGS,DEFAULT_MODELS,QWEN_OAUTH_MODELS,QWEN_OAUTH_ALLOWED_MODELS,resolveContentGeneratorConfigWithSources,hasVertexProjectConfigured,preloadContentGenerator,resetPreloadedContentGenerator,createContentGenerator};
5
5
  /**
6
6
  * @license
7
7
  * Copyright 2025 Qwen Team